From fa484156174a6553b4155a0a7455f69e404b61a7 Mon Sep 17 00:00:00 2001 From: Sosuke Suzuki Date: Wed, 5 Jul 2023 21:50:05 +0900 Subject: [PATCH] Bump Prettier dependency to 3.0.0 --- CHANGELOG.md | 2 +- CONTRIBUTING.md | 2 +- README.md | 2 +- changelog_unreleased/api/13268.md | 2 +- changelog_unreleased/api/14317.md | 8 +- commands.md | 6 +- docs/browser.md | 4 +- docs/index.md | 2 +- docs/plugins.md | 48 +++---- jest.config.js | 4 +- package.json | 4 +- scripts/benchmark/bench.js | 6 +- scripts/build-website.js | 4 +- scripts/build/build-javascript-module.js | 14 +- scripts/build/build-license.js | 8 +- scripts/build/build-package-json.js | 12 +- scripts/build/build-types.js | 4 +- scripts/build/build.js | 10 +- scripts/build/config.js | 50 +++---- scripts/build/esbuild-plugins/license.js | 2 +- .../build/esbuild-plugins/primitive-define.js | 4 +- .../build/esbuild-plugins/replace-module.js | 6 +- .../esbuild-plugins/shim-commonjs-objects.js | 2 +- .../esbuild-plugins/strip-node-protocol.js | 2 +- .../build/esbuild-plugins/throw-warnings.js | 4 +- scripts/build/esbuild-plugins/umd.js | 2 +- scripts/build/modify-typescript-module.js | 14 +- scripts/build/transform/index.js | 2 +- .../create-method-call-transform.js | 4 +- .../transform-string-replace-all.js | 2 +- scripts/changelog-for-patch.js | 6 +- scripts/check-deps.js | 4 +- scripts/clean-changelog-unreleased.js | 2 +- scripts/clean-cspell.js | 4 +- scripts/draft-blog-post.js | 12 +- scripts/generate-changelog.js | 8 +- scripts/generate-schema.js | 2 +- scripts/lint-changelog.js | 24 ++-- scripts/release/run.js | 68 +++++----- scripts/release/steps/bump-prettier.js | 13 +- scripts/release/steps/check-git-status.js | 2 +- scripts/release/steps/generate-bundles.js | 6 +- scripts/release/steps/install-dependencies.js | 2 +- scripts/release/steps/post-publish-steps.js | 10 +- .../show-instructions-after-npm-publish.js | 4 +- scripts/release/steps/update-changelog.js | 8 +- .../release/steps/update-dependents-count.js | 22 ++-- scripts/release/steps/update-version.js | 10 +- scripts/release/steps/validate-new-version.js | 4 +- scripts/release/steps/wait-for-bot-release.js | 30 ++--- scripts/release/tests/publish-to-npm.test.js | 10 +- .../tests/validate-new-version.test.js | 8 +- scripts/sync-flow-tests.cjs | 10 +- scripts/tools/bundle-test/index.js | 2 +- ...r-parent-property-check-in-needs-parens.js | 2 +- .../flat-ast-path-call.js | 8 +- .../jsx-identifier-case.js | 2 +- .../no-doc-public-import.js | 6 +- .../no-node-comments.js | 2 +- .../prefer-ast-path-getters.js | 2 +- .../prefer-create-type-check-function.js | 8 +- .../prefer-indent-if-break.js | 6 +- .../prefer-is-non-empty-array.js | 4 +- .../test.js | 2 +- scripts/utils/changelog.js | 10 +- scripts/utils/generate-schema.js | 4 +- src/cli/expand-patterns.js | 6 +- src/cli/find-cache-file.js | 2 +- src/cli/format-results-cache.js | 4 +- src/cli/format.js | 48 +++---- src/cli/index.js | 4 +- src/cli/options/get-context-options.js | 2 +- src/cli/options/get-options-for-file.js | 24 ++-- src/cli/options/minimist.js | 4 +- src/cli/options/normalize-cli-options.js | 2 +- src/cli/options/parse-cli-arguments.js | 6 +- src/cli/print-support-info.js | 2 +- src/cli/usage.js | 26 ++-- src/common/ast-path.js | 9 +- src/common/get-file-info.js | 2 +- src/common/parser-create-error.js | 2 +- src/config/get-prettier-config-explorer.js | 2 +- src/config/resolve-config.js | 6 +- src/document/invalid-doc-error.js | 2 +- src/document/printer.js | 8 +- src/document/public.d.ts | 14 +- src/document/utils.js | 4 +- src/index.cjs | 4 +- src/index.d.ts | 124 +++++++++--------- src/index.js | 2 +- src/language-css/clean.js | 8 +- src/language-css/loc.js | 2 +- src/language-css/parse/parse-value.js | 4 +- src/language-css/parser-postcss.js | 8 +- .../print/comma-separated-value-group.js | 4 +- src/language-css/print/misc.js | 4 +- .../print/parenthesized-value-group.js | 8 +- src/language-css/printer-postcss.js | 16 +-- .../utils/has-string-or-function.js | 2 +- src/language-css/utils/index.js | 8 +- src/language-css/utils/is-scss-variable.js | 2 +- src/language-graphql/printer-graphql.js | 18 +-- src/language-handlebars/parser-glimmer.js | 4 +- src/language-handlebars/printer-glimmer.js | 8 +- src/language-html/ast.js | 4 +- src/language-html/conditional-comment.js | 2 +- src/language-html/constants.evaluate.js | 4 +- src/language-html/embed.js | 2 +- src/language-html/embed/angular-attributes.js | 4 +- .../embed/angular-interpolation.js | 2 +- src/language-html/embed/attribute.js | 6 +- src/language-html/embed/srcset.js | 6 +- src/language-html/embed/style.js | 2 +- src/language-html/embed/utils.js | 2 +- src/language-html/embed/vue-attributes.js | 6 +- .../embed/vue-v-for-directive.js | 4 +- src/language-html/parser-html.js | 30 ++--- src/language-html/print-preprocess.js | 24 ++-- src/language-html/print/children.js | 6 +- src/language-html/print/element.js | 4 +- src/language-html/print/tag.js | 6 +- src/language-html/printer-html.js | 4 +- .../html-elements-attributes.evaluate.js | 2 +- src/language-html/utils/index.js | 4 +- .../is-vue-sfc-with-typescript-script.js | 4 +- src/language-js/clean.js | 6 +- src/language-js/comments/handle-comments.js | 12 +- src/language-js/embed/css.js | 4 +- src/language-js/embed/graphql.js | 2 +- src/language-js/embed/html.js | 6 +- src/language-js/embed/markdown.js | 4 +- src/language-js/embed/utils.js | 6 +- src/language-js/needs-parens.js | 38 +++--- src/language-js/parse/acorn.js | 2 +- src/language-js/parse/babel.js | 16 +-- src/language-js/parse/meriyah.js | 4 +- src/language-js/parse/postprocess/index.js | 6 +- .../parse/postprocess/typescript.js | 50 +++---- src/language-js/parse/typescript.js | 6 +- src/language-js/print/angular.js | 8 +- src/language-js/print/array.js | 14 +- src/language-js/print/arrow-function.js | 22 ++-- src/language-js/print/assignment.js | 18 +-- src/language-js/print/binaryish.js | 29 ++-- src/language-js/print/call-arguments.js | 2 +- src/language-js/print/class.js | 14 +- src/language-js/print/comment.js | 4 +- src/language-js/print/decorators.js | 2 +- src/language-js/print/estree.js | 34 ++--- src/language-js/print/expression-statement.js | 4 +- src/language-js/print/function-parameters.js | 8 +- src/language-js/print/function.js | 12 +- src/language-js/print/interface.js | 6 +- src/language-js/print/jsx.js | 47 ++++--- src/language-js/print/mapped-type.js | 4 +- src/language-js/print/member-chain.js | 8 +- src/language-js/print/member.js | 3 +- src/language-js/print/misc.js | 2 +- src/language-js/print/module.js | 8 +- src/language-js/print/object.js | 18 +-- src/language-js/print/property.js | 12 +- src/language-js/print/semicolon.js | 2 +- src/language-js/print/template-literal.js | 20 +-- src/language-js/print/ternary.js | 12 +- src/language-js/print/type-annotation.js | 28 ++-- src/language-js/print/type-parameters.js | 10 +- src/language-js/print/typescript.js | 8 +- .../traverse/visitor-keys.evaluate.js | 4 +- src/language-js/utils/index.js | 13 +- src/language-js/utils/is-node-matches.js | 2 +- src/language-json/parser-json.js | 6 +- src/language-json/printer-estree-json.js | 2 +- src/language-markdown/constants.evaluate.js | 2 +- src/language-markdown/embed.js | 4 +- src/language-markdown/pragma.js | 2 +- src/language-markdown/print-preprocess.js | 10 +- src/language-markdown/print-whitespace.js | 6 +- src/language-markdown/printer-markdown.js | 52 ++++---- src/language-markdown/utils.js | 14 +- src/language-yaml/print/block.js | 10 +- .../print/flow-mapping-sequence.js | 2 +- src/language-yaml/print/mapping-item.js | 6 +- src/language-yaml/printer-yaml.js | 28 ++-- src/language-yaml/utils.js | 32 ++--- src/language-yaml/visitor-keys.js | 2 +- src/main/ast-to-doc.js | 2 +- src/main/comments/attach.js | 6 +- src/main/comments/print.js | 12 +- src/main/comments/utils.js | 2 +- src/main/core.js | 20 +-- src/main/create-print-pre-check-function.js | 2 +- src/main/get-cursor-node.js | 2 +- src/main/multiparser.js | 12 +- src/main/normalize-format-options.js | 12 +- src/main/normalize-options.js | 12 +- src/main/parse.js | 2 +- src/main/plugins/load-plugin.js | 2 +- src/main/range-util.js | 17 +-- src/main/support.js | 6 +- src/standalone.d.ts | 2 +- src/standalone.js | 2 +- src/utils/create-get-visitor-keys.js | 2 +- src/utils/front-matter/parse.js | 2 +- src/utils/get-indent-size.js | 2 +- src/utils/get-max-continuous-count.js | 4 +- .../get-min-not-present-continuous-count.js | 2 +- src/utils/has-newline.js | 2 +- src/utils/has-spaces.js | 2 +- src/utils/ignore.js | 4 +- src/utils/infer-parser.js | 8 +- src/utils/object-omit.js | 2 +- src/utils/print-string.js | 2 +- src/utils/public.js | 2 +- src/utils/unexpected-node-error.js | 4 +- src/utils/whitespace-utils.js | 12 +- tests/config/format-test.js | 34 ++--- tests/config/get-prettier.js | 4 +- tests/config/install-prettier.js | 6 +- .../prettier-plugin-async-printer/index.cjs | 2 +- tests/config/require-standalone.cjs | 6 +- tests/config/utils/check-parsers.js | 10 +- tests/config/utils/create-snapshot.js | 4 +- .../utils/stringify-options-for-title.js | 2 +- tests/config/utils/visualize-range.js | 2 +- tests/dts/unit/cases/print.ts | 18 +-- tests/dts/unit/run.js | 2 +- .../handlebars/element-node/jsfmt.spec.js | 2 +- .../html-whitespace-sensitivity/jsfmt.spec.js | 2 +- tests/format/html/whitespace/jsfmt.spec.js | 2 +- tests/format/js/bom/jsfmt.spec.js | 2 +- tests/format/js/cursor/jsfmt.spec.js | 19 ++- .../js/directives/comments/jsfmt.spec.js | 2 +- tests/format/js/directives/jsfmt.spec.js | 2 +- tests/format/js/empty/jsfmt.spec.js | 2 +- .../js/identifier/parentheses/jsfmt.spec.js | 2 +- tests/format/js/shebang/jsfmt.spec.js | 2 +- .../js/trailing-whitespace/jsfmt.spec.js | 2 +- tests/format/json/json-superset/jsfmt.spec.js | 4 +- tests/format/jsx/whitespace/jsfmt.spec.js | 2 +- tests/format/markdown/auto-link/jsfmt.spec.js | 2 +- .../markdown/fenced-code-block/jsfmt.spec.js | 2 +- tests/format/markdown/list/jsfmt.spec.js | 2 +- .../markdown/splitCjkText/jsfmt.spec.js | 4 +- tests/format/misc/empty/jsfmt.spec.js | 2 +- .../misc/errors/broken-plugin/jsfmt.spec.js | 2 +- .../misc/errors/flow/interface/jsfmt.spec.js | 2 +- .../misc/errors/handlebars/jsfmt.spec.js | 2 +- .../format/misc/errors/invalid/jsfmt.spec.js | 4 +- .../misc/errors/js/assignment/jsfmt.spec.js | 8 +- .../misc/errors/js/async-await/jsfmt.spec.js | 4 +- .../misc/errors/js/decorators/jsfmt.spec.js | 2 +- .../js/export-default-from/jsfmt.spec.js | 2 +- .../misc/errors/js/for-of/jsfmt.spec.js | 12 +- .../errors/js/hack-pipeline/jsfmt.spec.js | 2 +- .../misc/errors/js/import/jsfmt.spec.js | 2 +- tests/format/misc/errors/js/jsfmt.spec.js | 2 +- .../errors/js/known-source-type/jsfmt.spec.js | 2 +- .../errors/js/optional-chaining/jsfmt.spec.js | 2 +- .../misc/errors/js/record/jsfmt.spec.js | 2 +- .../errors/js/reserved-word/jsfmt.spec.js | 2 +- tests/format/misc/errors/json/jsfmt.spec.js | 4 +- .../errors/json/json-stringify/jsfmt.spec.js | 2 +- .../errors/typescript/babel-ts/jsfmt.spec.js | 2 +- .../errors/typescript/interface/jsfmt.spec.js | 2 +- .../misc/errors/typescript/jsfmt.spec.js | 2 +- .../errors/typescript/modifiers/jsfmt.spec.js | 22 ++-- .../module-declaration/jsfmt.spec.js | 2 +- .../errors/typescript/tuple/jsfmt.spec.js | 2 +- .../plugins/embed-async-printer/jsfmt.spec.js | 2 +- .../misc/require-pragma/js/jsfmt.spec.js | 2 +- .../format/typescript/tsx/comma/jsfmt.spec.js | 2 +- .../jsfmt.spec.js | 2 +- tests/format/vue/multiparser/jsfmt.spec.js | 2 +- tests/format/vue/with-plugins/jsfmt.spec.js | 2 +- tests/integration/__tests__/arg-parsing.js | 2 +- tests/integration/__tests__/bundle.js | 18 +-- tests/integration/__tests__/cache.js | 112 ++++++++-------- tests/integration/__tests__/check.js | 4 +- tests/integration/__tests__/config-invalid.js | 6 +- .../__tests__/config-resolution.js | 56 ++++---- tests/integration/__tests__/debug-api.js | 16 +-- tests/integration/__tests__/debug-check.js | 2 +- tests/integration/__tests__/doc-printer.js | 2 +- tests/integration/__tests__/file-info.js | 54 ++++---- tests/integration/__tests__/format-ast.js | 10 +- tests/integration/__tests__/format.js | 20 +-- .../__tests__/ignore-in-subdirectories.js | 4 +- tests/integration/__tests__/ignore-path.js | 10 +- tests/integration/__tests__/infer-parser.js | 6 +- tests/integration/__tests__/invalid-ignore.js | 4 +- tests/integration/__tests__/list-different.js | 4 +- tests/integration/__tests__/log-level.js | 2 +- tests/integration/__tests__/mockable.js | 2 +- tests/integration/__tests__/parser-api.js | 6 +- tests/integration/__tests__/patterns-dirs.js | 32 ++--- .../__tests__/performance-flags.js | 8 +- tests/integration/__tests__/piped-output.js | 16 +-- .../integration/__tests__/plugin-api-embed.js | 4 +- .../__tests__/plugin-default-options.js | 4 +- .../__tests__/plugin-options-string.js | 6 +- tests/integration/__tests__/plugin-options.js | 6 +- .../__tests__/print-doc-to-string.js | 4 +- .../__tests__/printer-and-parser.js | 4 +- tests/integration/__tests__/stdin-filepath.js | 14 +- tests/integration/__tests__/support-info.js | 4 +- tests/integration/__tests__/util-shared.js | 32 ++--- .../__tests__/with-config-precedence.js | 6 +- .../__tests__/with-parser-inference.js | 22 ++-- tests/integration/cli-worker.js | 6 +- tests/integration/env.js | 2 +- tests/integration/run-cli.js | 4 +- tests/unit/get-descendants.js | 2 +- tests/unit/print-doc-to-string.js | 7 +- tests/unit/resolve-parser.js | 4 +- tests/unit/syntax-transform.js | 8 +- website/blog/2017-05-03-1.3.0.md | 2 +- website/blog/2018-11-07-1.15.0.md | 2 +- website/pages/en/index.js | 5 +- website/pages/playground-redirect.html | 6 +- website/pages/playground/index.html | 2 +- website/playground/BottomBar.js | 2 +- website/playground/Playground.js | 14 +- website/playground/VersionLink.js | 2 +- website/playground/dummyId.js | 2 +- website/playground/markdown.js | 4 +- website/playground/panels.js | 6 +- website/playground/sidebar/SidebarOptions.js | 2 +- website/playground/util.js | 2 +- website/siteConfig.js | 2 +- website/static/js/code-block-buttons.js | 2 +- website/static/overrides.css | 14 +- website/static/separate-css/playground.css | 6 +- website/static/service-worker.js | 4 +- website/static/worker.js | 10 +- .../versioned_docs/version-stable/browser.md | 4 +- .../versioned_docs/version-stable/index.md | 2 +- .../versioned_docs/version-stable/plugins.md | 48 +++---- yarn.lock | 13 +- 338 files changed, 1483 insertions(+), 1434 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ec495f72d..59efeeb98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -934,7 +934,7 @@ prettier --loglevel silent --help no-color Fixes two problems when bundling our UMD files with webpack: -- A error `` "`....__exportStar` is not a function" `` throws when running the bundles. +- A error ``"`....__exportStar` is not a function"`` throws when running the bundles. - Some files cause warning about `"Critical dependency: the request of a dependency is an expression"`. #### Fix non-idempotent formatting of function calls with complex type arguments ([#12508](https://github.com/prettier/prettier/pull/12508) by [@sosukesuzuki](https://github.com/sosukesuzuki)) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index be52fdc7c..f48cd8d08 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -41,7 +41,7 @@ function run_spec( parsers: string[], options?: PrettierOptions & { errors: true | { [parserName: string]: true | string[] }; - } + }, ): void; ``` diff --git a/README.md b/README.md index 4076b3ad5..c3ec34c1e 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ foo( reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), - isThereSeriouslyAnotherOne() + isThereSeriouslyAnotherOne(), ); ``` diff --git a/changelog_unreleased/api/13268.md b/changelog_unreleased/api/13268.md index 62d1448a1..3fcf51690 100644 --- a/changelog_unreleased/api/13268.md +++ b/changelog_unreleased/api/13268.md @@ -38,7 +38,7 @@ The second argument `parsers` has been removed, if you still need other parser d ```js function getParserFromOptions(options, parserName) { const parserOrParserInitFunction = options.plugins.find( - (plugin) => plugin.parsers && Object.hasOwn(plugin.parsers, parserName) + (plugin) => plugin.parsers && Object.hasOwn(plugin.parsers, parserName), )?.parsers[parserName]; return typeof parserOrParserInitFunction === "function" ? parserOrParserInitFunction() diff --git a/changelog_unreleased/api/14317.md b/changelog_unreleased/api/14317.md index 2d714e0b8..26028effa 100644 --- a/changelog_unreleased/api/14317.md +++ b/changelog_unreleased/api/14317.md @@ -9,7 +9,7 @@ function getNextNonSpaceNonCommentCharacterIndex( text: string, node: N, - locEnd: (node: N) => number + locEnd: (node: N) => number, ): number | false; ``` @@ -18,7 +18,7 @@ ```ts function getNextNonSpaceNonCommentCharacterIndex( text: string, - startIndex: number + startIndex: number, ): number | false; ``` @@ -30,7 +30,7 @@ function isPreviousLineEmpty( text: string, node: N, - locStart: (node: N) => number + locStart: (node: N) => number, ): boolean; ``` @@ -48,7 +48,7 @@ function isNextLineEmpty( text: string, node: N, - locEnd: (node: N) => number + locEnd: (node: N) => number, ): boolean; ``` diff --git a/commands.md b/commands.md index 368798f87..f7ca26626 100644 --- a/commands.md +++ b/commands.md @@ -55,7 +55,7 @@ This should be used as **last resort** as it triggers an exponential complexity ```ts declare function conditionalGroup( alternatives: Doc[], - options?: GroupOptions + options?: GroupOptions, ): Doc; ``` @@ -85,7 +85,7 @@ Expects the `docs` argument to be an array of alternating content and line break declare function ifBreak( breakContents: Doc, flatContents?: Doc, - options?: { groupId?: symbol } + options?: { groupId?: symbol }, ): Doc; ``` @@ -261,7 +261,7 @@ _Added in v2.3.0_ ```ts declare function indentIfBreak( doc: Doc, - opts: { groupId: symbol; negate?: boolean } + opts: { groupId: symbol; negate?: boolean }, ): Doc; ``` diff --git a/docs/browser.md b/docs/browser.md index f24045b4c..c6c56bf46 100644 --- a/docs/browser.md +++ b/docs/browser.md @@ -112,7 +112,7 @@ If you want to format [embedded code](options.md#embedded-language-formatting), await prettier.format("const html=/* HTML */ `
`", { parser: "babel", plugins: [pluginBabel], - }) + }), ); // Output: const html = /* HTML */ `
`; @@ -130,7 +130,7 @@ The HTML code embedded in JavaScript stays unformatted because the `html` parser await prettier.format("const html=/* HTML */ `
`", { parser: "babel", plugins: [pluginBabel, pluginHtml], - }) + }), ); // Output: const html = /* HTML */ `
`; diff --git a/docs/index.md b/docs/index.md index 735d3f2a5..6bbb459a2 100644 --- a/docs/index.md +++ b/docs/index.md @@ -43,7 +43,7 @@ foo( reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), - isThereSeriouslyAnotherOne() + isThereSeriouslyAnotherOne(), ); ``` diff --git a/docs/plugins.md b/docs/plugins.md index 5c1aaf27c..ab9c92a55 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -194,7 +194,7 @@ function print( path: AstPath, options: object, // Recursively print a child node - print: (selector?: string | number | Array | AstPath) => Doc + print: (selector?: string | number | Array | AstPath) => Doc, ): Doc; ``` @@ -250,7 +250,7 @@ function embed( // Path to the current AST node path: AstPath, // Current options - options: Options + options: Options, ): | (( // Parses and prints the passed text using a different parser. @@ -258,12 +258,12 @@ function embed( textToDoc: (text: string, options: Options) => Promise, // Prints the current node or its descendant node with the current printer print: ( - selector?: string | number | Array | AstPath + selector?: string | number | Array | AstPath, ) => Doc, // The following two arguments are passed for convenience. // They're the same `path` and `options` that are passed to `embed`. path: AstPath, - options: Options + options: Options, ) => Promise | Doc | undefined) | Doc | undefined; @@ -346,7 +346,7 @@ const ignoredKeys = new Set(["prev", "next", "range"]); function getVisitorKeys(node, nonTraversableKeys) { return Object.keys(node).filter( - (key) => !nonTraversableKeys.has(key) && !ignoredKeys.has(key) + (key) => !nonTraversableKeys.has(key) && !ignoredKeys.has(key), ); } ``` @@ -374,7 +374,7 @@ function getCommentChildNodes( // The node whose children should be returned. node: AST, // Current options - options: object + options: object, ): AST[] | undefined; ``` @@ -389,7 +389,7 @@ function printComment( // Path to the current comment node commentPath: AstPath, // Current options - options: object + options: object, ): Doc; ``` @@ -430,7 +430,7 @@ The `handleComments` object contains three optional functions, each with signatu // The AST ast: AST, // Whether this comment is the last comment - isLastComment: boolean + isLastComment: boolean, ) => boolean; ``` @@ -517,91 +517,91 @@ function getStringWidth(text: string): number; function getAlignmentSize( text: string, tabWidth: number, - startIndex?: number + startIndex?: number, ): number; function getIndentSize(value: string, tabWidth: number): number; function skip( - characters: string | RegExp + characters: string | RegExp, ): ( text: string, startIndex: number | false, - options?: SkipOptions + options?: SkipOptions, ) => number | false; function skipWhitespace( text: string, startIndex: number | false, - options?: SkipOptions + options?: SkipOptions, ): number | false; function skipSpaces( text: string, startIndex: number | false, - options?: SkipOptions + options?: SkipOptions, ): number | false; function skipToLineEnd( text: string, startIndex: number | false, - options?: SkipOptions + options?: SkipOptions, ): number | false; function skipEverythingButNewLine( text: string, startIndex: number | false, - options?: SkipOptions + options?: SkipOptions, ): number | false; function skipInlineComment( text: string, - startIndex: number | false + startIndex: number | false, ): number | false; function skipTrailingComment( text: string, - startIndex: number | false + startIndex: number | false, ): number | false; function skipNewline( text: string, startIndex: number | false, - options?: SkipOptions + options?: SkipOptions, ): number | false; function hasNewline( text: string, startIndex: number, - options?: SkipOptions + options?: SkipOptions, ): boolean; function hasNewlineInRange( text: string, startIndex: number, - startIndex: number + startIndex: number, ): boolean; function hasSpaces( text: string, startIndex: number, - options?: SkipOptions + options?: SkipOptions, ): boolean; function makeString( rawText: string, enclosingQuote: Quote, - unescapeUnnecessaryEscapes?: boolean + unescapeUnnecessaryEscapes?: boolean, ): string; function getNextNonSpaceNonCommentCharacter( text: string, - startIndex: number + startIndex: number, ): string; function getNextNonSpaceNonCommentCharacterIndex( text: string, - startIndex: number + startIndex: number, ): number | false; function isNextLineEmpty(text: string, startIndex: number): boolean; diff --git a/jest.config.js b/jest.config.js index 92d04600c..35d4b69c7 100644 --- a/jest.config.js +++ b/jest.config.js @@ -36,7 +36,7 @@ if (isProduction) { } else { // Only test bundles for production testPathIgnorePatterns.push( - "/tests/integration/__tests__/bundle.js" + "/tests/integration/__tests__/bundle.js", ); } @@ -45,7 +45,7 @@ if (SKIP_TESTS_WITH_NEW_SYNTAX) { "/tests/integration/__tests__/help-options.js", "/tests/integration/__tests__/plugin-parsers.js", "/tests/integration/__tests__/normalize-doc.js", - "/tests/integration/__tests__/doc-utils-clean-doc.js" + "/tests/integration/__tests__/doc-utils-clean-doc.js", ); } diff --git a/package.json b/package.json index 1f891adee..da1571fcd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "prettier", - "version": "3.0.0", + "version": "3.1.0-dev", "description": "Prettier is an opinionated code formatter", "bin": "./bin/prettier.cjs", "repository": "prettier/prettier", @@ -143,7 +143,7 @@ "magic-string": "0.30.0", "npm-run-all": "4.1.5", "path-browserify": "1.0.1", - "prettier": "2.8.8", + "prettier": "3.0.0", "pretty-bytes": "6.1.0", "rollup-plugin-license": "3.0.1", "semver": "7.5.3", diff --git a/scripts/benchmark/bench.js b/scripts/benchmark/bench.js index 62b3e8f3f..59bc10cbe 100644 --- a/scripts/benchmark/bench.js +++ b/scripts/benchmark/bench.js @@ -8,7 +8,7 @@ const { format } = await import(`./${version}/dist/index.mjs`); const sourceText = readFileSync( process.env.PRETTIER_PERF_FILENAME || "../../src/language-js/utils/index.js", - "utf8" + "utf8", ); for (let i = 0; i < groupCount; i++) { @@ -21,8 +21,8 @@ for (let i = 0; i < groupCount; i++) { if (method === "parallel") { await Promise.allSettled( Array.from({ length: groupSize }, () => - format(sourceText, { parser: "typescript" }) - ) + format(sourceText, { parser: "typescript" }), + ), ); } } diff --git a/scripts/build-website.js b/scripts/build-website.js index 68530b3af..5d598f00b 100644 --- a/scripts/build-website.js +++ b/scripts/build-website.js @@ -91,8 +91,8 @@ async function buildPlaygroundFiles() { const prettierPackageManifest = ${JSON.stringify(packageManifest)}; `, - { parser: "meriyah" } - ) + { parser: "meriyah" }, + ), ); } diff --git a/scripts/build/build-javascript-module.js b/scripts/build/build-javascript-module.js index 87e0c5971..dfd60db74 100644 --- a/scripts/build/build-javascript-module.js +++ b/scripts/build/build-javascript-module.js @@ -84,11 +84,11 @@ function getEsbuildOptions({ file, files, shouldCollectLicenses, cliOptions }) { text .replace( "const line = (0, _detectNewline().default)(docblock) ?? _os().EOL;", - 'const line = "\\n"' + 'const line = "\\n"', ) .replace( "const line = (0, _detectNewline().default)(comments) ?? _os().EOL;", - 'const line = "\\n"' + 'const line = "\\n"', ) .replace(/\nfunction _os\(\).*?\n}/s, "") .replace(/\nfunction _detectNewline\(\).*?\n}/s, ""), @@ -134,7 +134,7 @@ function getEsbuildOptions({ file, files, shouldCollectLicenses, cliOptions }) { .filter( (bundle) => bundle.input === "package.json" || - (file.input !== bundle.input && bundle.output.format === "esm") + (file.input !== bundle.input && bundle.output.format === "esm"), ) .map((bundle) => { let output = bundle.output.file; @@ -149,7 +149,7 @@ function getEsbuildOptions({ file, files, shouldCollectLicenses, cliOptions }) { module: path.join(PROJECT_ROOT, bundle.input), external: getRelativePath(file.output.file, output), }; - }) + }), ); } else { replaceModule.push( @@ -165,7 +165,7 @@ function getEsbuildOptions({ file, files, shouldCollectLicenses, cliOptions }) { module: "*", find: ' from "node:assert";', replacement: ` from ${JSON.stringify( - path.join(dirname, "./shims/assert.js") + path.join(dirname, "./shims/assert.js"), )};`, }, // Prevent `esbuildPluginNodeModulePolyfills` include shim for this module @@ -182,7 +182,7 @@ function getEsbuildOptions({ file, files, shouldCollectLicenses, cliOptions }) { { module: path.join(PROJECT_ROOT, "src/utils/get-interpreter.js"), text: "export default undefined;", - } + }, ); } @@ -240,7 +240,7 @@ function getEsbuildOptions({ file, files, shouldCollectLicenses, cliOptions }) { esbuildOptions.plugins.push( esbuildPluginUmd({ name: file.output.umdVariableName, - }) + }), ); } } else { diff --git a/scripts/build/build-license.js b/scripts/build/build-license.js index 4334e3b73..2031e7fb0 100644 --- a/scripts/build/build-license.js +++ b/scripts/build/build-license.js @@ -26,14 +26,14 @@ async function getLicenseText(files) { index === dependencies.findIndex( ({ name, version }) => - dependency.name === name && dependency.version === version - ) + dependency.name === name && dependency.version === version, + ), ); dependencies.sort( (dependencyA, dependencyB) => dependencyA.name.localeCompare(dependencyB.name) || - dependencyA.version.localeCompare(dependencyB.version) + dependencyA.version.localeCompare(dependencyB.version), ); const prettierLicense = await fs.readFile(PROJECT_LICENSE_FILE, "utf8"); @@ -42,7 +42,7 @@ async function getLicenseText(files) { ...new Set( dependencies .filter(({ license }) => license) - .map(({ license }) => license) + .map(({ license }) => license), ), ]; diff --git a/scripts/build/build-package-json.js b/scripts/build/build-package-json.js index ae1df5828..590bd5107 100644 --- a/scripts/build/build-package-json.js +++ b/scripts/build/build-package-json.js @@ -25,7 +25,7 @@ async function buildPackageJson({ file, files }) { const bin = files.find( (file) => path.join(PROJECT_ROOT, packageJson.bin) === - path.join(PROJECT_ROOT, file.input) + path.join(PROJECT_ROOT, file.input), ).output.file; const overrides = { @@ -57,7 +57,7 @@ async function buildPackageJson({ file, files }) { default: `./${file.output.file.replace(/\.js$/, ".mjs")}`, }, ]; - }) + }), ), // Legacy entries // TODO: Remove bellow in v4 @@ -68,7 +68,7 @@ async function buildPackageJson({ file, files }) { (file) => file.isPlugin && file.output.format === "umd" && - file.output.file !== "plugins/estree.js" + file.output.file !== "plugins/estree.js", ) .flatMap((file) => { let basename = path.basename(file.output.file, ".js"); @@ -83,7 +83,7 @@ async function buildPackageJson({ file, files }) { `./${file.output.file.replace(/\.js$/, ".mjs")}`, ], ]; - }) + }), ), }, files: files.map(({ output: { file } }) => file).sort(), @@ -95,14 +95,14 @@ async function buildPackageJson({ file, files }) { await writeJson( path.join(DIST_DIR, file.output.file), - Object.assign(pick(packageJson, keysToKeep), overrides) + Object.assign(pick(packageJson, keysToKeep), overrides), ); } function pick(object, keys) { keys = new Set(keys); return Object.fromEntries( - Object.entries(object).filter(([key]) => keys.has(key)) + Object.entries(object).filter(([key]) => keys.has(key)), ); } diff --git a/scripts/build/build-types.js b/scripts/build/build-types.js index c8687131f..546c9233e 100644 --- a/scripts/build/build-types.js +++ b/scripts/build/build-types.js @@ -20,7 +20,7 @@ async function typesFileBuilder({ file }) { for (const { from, to } of replacements) { text = text.replaceAll( new RegExp(` from "${from}";`, "g"), - ` from "${to}";` + ` from "${to}";`, ); } await writeFile(path.join(DIST_DIR, file.output.file), text); @@ -49,7 +49,7 @@ async function buildPluginTypes({ file: { input, output } }) { ${parserNames .map( (parserName) => - `${" ".repeat(2)}${toPropertyKey(parserName)}: Parser;` + `${" ".repeat(2)}${toPropertyKey(parserName)}: Parser;`, ) .join("\n")} };\n diff --git a/scripts/build/build.js b/scripts/build/build.js index a72371d98..fd8eeb229 100644 --- a/scripts/build/build.js +++ b/scripts/build/build.js @@ -109,7 +109,7 @@ async function buildFile({ file, files, shouldCollectLicenses, cliOptions }) { const { size } = await fs.stat(path.join(DIST_DIR, result.file)); const sizeDiff = size - stableSize; const message = chalk[sizeDiff > 0 ? "yellow" : "green"]( - prettyBytes(sizeDiff) + prettyBytes(sizeDiff), ); sizeMessages.push(`${message}`); @@ -122,7 +122,7 @@ async function buildFile({ file, files, shouldCollectLicenses, cliOptions }) { // Clear previous line clear(); process.stdout.write( - fitTerminal(displayName, `${sizeMessages.join(", ")} `) + fitTerminal(displayName, `${sizeMessages.join(", ")} `), ); } @@ -183,13 +183,13 @@ async function run(cliOptions) { if (cliOptions.compareSize) { if (cliOptions.minify === false) { throw new Error( - "'--compare-size' can not use together with '--no-minify' flag" + "'--compare-size' can not use together with '--no-minify' flag", ); } if (cliOptions.saveAs) { throw new Error( - "'--compare-size' can not use together with '--save-as' flag" + "'--compare-size' can not use together with '--save-as' flag", ); } } @@ -218,5 +218,5 @@ await run( unknown(flag) { throw new Error(`Unknown flag ${chalk.red(flag)}`); }, - }) + }), ); diff --git a/scripts/build/config.js b/scripts/build/config.js index 20a5759c5..0d74ae4c0 100644 --- a/scripts/build/config.js +++ b/scripts/build/config.js @@ -21,7 +21,7 @@ const resolveEsmModulePath = async (specifier) => const copyFileBuilder = ({ file }) => copyFile( path.join(PROJECT_ROOT, file.input), - path.join(DIST_DIR, file.output.file) + path.join(DIST_DIR, file.output.file), ); function getTypesFileConfig({ input: jsFileInput, outputBaseName, isPlugin }) { @@ -97,7 +97,7 @@ const pluginFiles = [ process: (text) => text.replaceAll( "const entity = entities[desc];", - "const entity = undefined" + "const entity = undefined", ), }, ], @@ -109,7 +109,7 @@ const pluginFiles = [ module: require.resolve("flow-parser"), process(text) { const { fsModuleNameVariableName } = text.match( - /,(?\w+)="fs",/ + /,(?\w+)="fs",/, ).groups; return text @@ -129,7 +129,7 @@ const pluginFiles = [ }, { module: getPackageFile( - "@typescript-eslint/typescript-estree/dist/parser.js" + "@typescript-eslint/typescript-estree/dist/parser.js", ), process(text) { text = text @@ -142,69 +142,69 @@ const pluginFiles = [ }, { module: getPackageFile( - "@typescript-eslint/typescript-estree/dist/parseSettings/createParseSettings.js" + "@typescript-eslint/typescript-estree/dist/parseSettings/createParseSettings.js", ), process(text) { return text .replace('require("./resolveProjectList")', "{}") .replace( 'require("../create-program/shared")', - "{ensureAbsolutePath: path => path}" + "{ensureAbsolutePath: path => path}", ) .replace( "process.cwd()", - JSON.stringify("/prettier-security-dirname-placeholder") + JSON.stringify("/prettier-security-dirname-placeholder"), ) .replace( "parseSettings.projects = ", - "parseSettings.projects = [] || " + "parseSettings.projects = [] || ", ); }, }, { module: getPackageFile( - "@typescript-eslint/typescript-estree/dist/parseSettings/inferSingleRun.js" + "@typescript-eslint/typescript-estree/dist/parseSettings/inferSingleRun.js", ), text: "exports.inferSingleRun = () => false;", }, { module: getPackageFile( - "@typescript-eslint/typescript-estree/dist/parseSettings/ExpiringCache.js" + "@typescript-eslint/typescript-estree/dist/parseSettings/ExpiringCache.js", ), text: "exports.ExpiringCache = class {};", }, { module: getPackageFile( - "@typescript-eslint/typescript-estree/dist/parseSettings/getProjectConfigFiles.js" + "@typescript-eslint/typescript-estree/dist/parseSettings/getProjectConfigFiles.js", ), text: "exports.resolveProjectList = () => [];", }, { module: getPackageFile( - "@typescript-eslint/typescript-estree/dist/parseSettings/warnAboutTSVersion.js" + "@typescript-eslint/typescript-estree/dist/parseSettings/warnAboutTSVersion.js", ), text: "exports.warnAboutTSVersion = () => {};", }, { module: getPackageFile( - "@typescript-eslint/typescript-estree/dist/create-program/getScriptKind.js" + "@typescript-eslint/typescript-estree/dist/create-program/getScriptKind.js", ), process: (text) => text.replace( 'require("path")', - '{extname: file => "." + file.split(".").pop()}' + '{extname: file => "." + file.split(".").pop()}', ), }, { module: getPackageFile( - "@typescript-eslint/typescript-estree/dist/version-check.js" + "@typescript-eslint/typescript-estree/dist/version-check.js", ), text: "exports.typescriptVersionIsAtLeast = new Proxy({}, {get: () => true})", }, // Only needed if `range`/`loc` in parse options is `false` { module: getPackageFile( - "@typescript-eslint/typescript-estree/dist/ast-converter.js" + "@typescript-eslint/typescript-estree/dist/ast-converter.js", ), process: (text) => text.replace('require("./simple-traverse")', "{}"), }, @@ -223,11 +223,11 @@ const pluginFiles = [ text .replaceAll( /exports\.(?:Syntax|VisitorKeys|latestEcmaVersion|supportedEcmaVersions|tokenize|version) = .*?;/g, - "" + "", ) .replaceAll( /const (Syntax|VisitorKeys|latestEcmaVersion|supportedEcmaVersions) = /g, - "const $1 = undefined && " + "const $1 = undefined && ", ) .replace("require('eslint-visitor-keys')", "{}"), }, @@ -305,11 +305,11 @@ const pluginFiles = [ .replace("require('util')", "{}") .replace( "let message = util.format('Unclosed %s at line: %d, column: %d, token: %d', what, line, pos - offset, pos);", - "let message = `Unclosed ${what} at line: ${line}, column: ${pos - offset}, token: ${pos}`;" + "let message = `Unclosed ${what} at line: ${line}, column: ${pos - offset}, token: ${pos}`;", ) .replace( "let message = util.format('Syntax error at line: %d, column: %d, token: %d', line, pos - offset, pos);", - "let message = `Syntax error at line: ${line}, column: ${pos - offset}, token: ${pos}`;" + "let message = `Syntax error at line: ${line}, column: ${pos - offset}, token: ${pos}`;", ), }, ], @@ -330,16 +330,16 @@ const pluginFiles = [ // See comment in `src/language-handlebars/parser-glimmer.js` file { module: getPackageFile( - "@glimmer/syntax/dist/commonjs/es2017/lib/parser/tokenizer-event-handlers.js" + "@glimmer/syntax/dist/commonjs/es2017/lib/parser/tokenizer-event-handlers.js", ), path: getPackageFile( - "@glimmer/syntax/dist/modules/es2017/lib/parser/tokenizer-event-handlers.js" + "@glimmer/syntax/dist/modules/es2017/lib/parser/tokenizer-event-handlers.js", ), }, // This passed to plugins, our plugin don't need access to the options { module: getPackageFile( - "@glimmer/syntax/dist/modules/es2017/lib/parser/tokenizer-event-handlers.js" + "@glimmer/syntax/dist/modules/es2017/lib/parser/tokenizer-event-handlers.js", ), process: (text) => text.replace(/\nconst syntax = \{.*?\n\};/su, "\nconst syntax = {};"), @@ -445,7 +445,7 @@ const universalFiles = [...nonPluginUniversalFiles, ...pluginFiles].flatMap( })), getTypesFileConfig({ input, outputBaseName, isPlugin }), ]; - } + }, ); const nodejsFiles = [ @@ -464,7 +464,7 @@ const nodejsFiles = [ replacement: ` var semver = { gte: require(${JSON.stringify( - require.resolve("semver/functions/gte") + require.resolve("semver/functions/gte"), )}) }; `, diff --git a/scripts/build/esbuild-plugins/license.js b/scripts/build/esbuild-plugins/license.js index a9d121943..b43201eab 100644 --- a/scripts/build/esbuild-plugins/license.js +++ b/scripts/build/esbuild-plugins/license.js @@ -17,7 +17,7 @@ export default function esbuildPluginLicense(options) { const files = Object.keys(result.metafile.inputs); const chunk = { modules: Object.fromEntries( - files.map((file) => [file, { renderedLength: 1 }]) + files.map((file) => [file, { renderedLength: 1 }]), ), }; plugin.renderChunk("", chunk); diff --git a/scripts/build/esbuild-plugins/primitive-define.js b/scripts/build/esbuild-plugins/primitive-define.js index 103b05a0c..5c4c850a3 100644 --- a/scripts/build/esbuild-plugins/primitive-define.js +++ b/scripts/build/esbuild-plugins/primitive-define.js @@ -20,12 +20,12 @@ export default function esbuildPluginPrimitiveDefine(define) { const esbuildConfig = build.initialOptions; if (esbuildConfig.define) { throw new Error( - "Use `esbuildPluginPrimitiveDefine(define)` instead of 'define' option" + "Use `esbuildPluginPrimitiveDefine(define)` instead of 'define' option", ); } esbuildConfig.define = Object.fromEntries( - Object.entries(define).map(([key, value]) => [key, stringify(value)]) + Object.entries(define).map(([key, value]) => [key, stringify(value)]), ); }, }; diff --git a/scripts/build/esbuild-plugins/replace-module.js b/scripts/build/esbuild-plugins/replace-module.js index 5351c5afe..fa6da5997 100644 --- a/scripts/build/esbuild-plugins/replace-module.js +++ b/scripts/build/esbuild-plugins/replace-module.js @@ -25,7 +25,7 @@ function processReplacements(replacements) { } throw new Error( - `module: '${module}' already replaced with another content.` + `module: '${module}' already replaced with another content.`, ); }; @@ -50,7 +50,7 @@ function processReplacements(replacements) { module, Object.hasOwn(replacement, "external") ? { external: true, path: replacement.external } - : { path: replacement.path } + : { path: replacement.path }, ); continue; @@ -96,7 +96,7 @@ function processReplacements(replacements) { Object.hasOwn(replacement, "replacement") ) { processFunctions.push((text) => - text.replaceAll(replacement.find, replacement.replacement) + text.replaceAll(replacement.find, replacement.replacement), ); continue; } diff --git a/scripts/build/esbuild-plugins/shim-commonjs-objects.js b/scripts/build/esbuild-plugins/shim-commonjs-objects.js index 11e708379..47ccfd980 100644 --- a/scripts/build/esbuild-plugins/shim-commonjs-objects.js +++ b/scripts/build/esbuild-plugins/shim-commonjs-objects.js @@ -28,7 +28,7 @@ export default function esbuildPluginShimCommonjsObjects() { const __dirname = __prettierDirname(__filename); ${text} - ` + `, ); }); }, diff --git a/scripts/build/esbuild-plugins/strip-node-protocol.js b/scripts/build/esbuild-plugins/strip-node-protocol.js index 4fcf6a7b9..60fd0cadf 100644 --- a/scripts/build/esbuild-plugins/strip-node-protocol.js +++ b/scripts/build/esbuild-plugins/strip-node-protocol.js @@ -3,7 +3,7 @@ export default function esbuildPluginStripNodeProtocol() { name: "strip-node-protocol", setup(build) { build.onResolve({ filter: /^node:/ }, ({ path, kind }) => - build.resolve(path.slice(5), { kind }) + build.resolve(path.slice(5), { kind }), ); }, }; diff --git a/scripts/build/esbuild-plugins/throw-warnings.js b/scripts/build/esbuild-plugins/throw-warnings.js index e126d3edf..6875e6710 100644 --- a/scripts/build/esbuild-plugins/throw-warnings.js +++ b/scripts/build/esbuild-plugins/throw-warnings.js @@ -54,7 +54,7 @@ const ESBUILD_MESSAGE_IDS = [ "tsconfig.json", ]; const logOverride = Object.fromEntries( - ESBUILD_MESSAGE_IDS.map((id) => [id, "warning"]) + ESBUILD_MESSAGE_IDS.map((id) => [id, "warning"]), ); export default function esbuildPluginThrowWarnings({ @@ -79,7 +79,7 @@ export default function esbuildPluginThrowWarnings({ if ( allowDynamicRequire && ["unsupported-require-call", "indirect-require"].includes( - warning.id + warning.id, ) ) { continue; diff --git a/scripts/build/esbuild-plugins/umd.js b/scripts/build/esbuild-plugins/umd.js index 1a15a5c7f..de7da7294 100644 --- a/scripts/build/esbuild-plugins/umd.js +++ b/scripts/build/esbuild-plugins/umd.js @@ -138,7 +138,7 @@ export default function esbuildPluginUmd(options) { text .slice(expectedOutput.start.length, -expectedOutput.end.length) .trimEnd() + - outro + outro, ); }); }, diff --git a/scripts/build/modify-typescript-module.js b/scripts/build/modify-typescript-module.js index aedaf233e..5fe145562 100644 --- a/scripts/build/modify-typescript-module.js +++ b/scripts/build/modify-typescript-module.js @@ -25,7 +25,7 @@ function* getModules(text) { "\\s*}", "\\s*}\\);", ].join("\\n"), - "s" + "s", ); const match = code.match(esmRegExp); @@ -69,7 +69,7 @@ class TypeScriptModuleSource { this.#source.overwrite( module.start, module.end, - moduleInitCode + replacement + moduleInitCode + replacement, ); return this; } @@ -94,7 +94,7 @@ class TypeScriptModuleSource { escapeStringRegexp(end), "(?=\n)", ].join(""), - "gsu" + "gsu", ); this.#source.replaceAll(regexp, replacement); @@ -188,7 +188,7 @@ function modifyTypescriptModule(text) { init_debug(); scanner = createScanner(99 /* Latest */, /*skipTrivia*/ true); }; - ` + `, ); continue; } @@ -246,7 +246,7 @@ function modifyTypescriptModule(text) { // perfLogger source.replaceModule( "src/compiler/perfLogger.ts", - "var perfLogger = new Proxy(() => {}, {get: () => perfLogger});" + "var perfLogger = new Proxy(() => {}, {get: () => perfLogger});", ); // performanceCore @@ -255,7 +255,7 @@ function modifyTypescriptModule(text) { outdent` var tryGetNativePerformanceHooks = () => {}; var timestamp = Date.now; - ` + `, ); // `factory` @@ -265,7 +265,7 @@ function modifyTypescriptModule(text) { "src/compiler/factory/nodeConverters.ts", outdent` var createNodeConverters = () => new Proxy({}, {get: () => () => {}}); - ` + `, ); /* spell-checker: disable */ diff --git a/scripts/build/transform/index.js b/scripts/build/transform/index.js index 1663cf4b1..ddb9d9a40 100644 --- a/scripts/build/transform/index.js +++ b/scripts/build/transform/index.js @@ -15,7 +15,7 @@ function transform(original, file) { } const transforms = allTransforms.filter( - (transform) => !transform.shouldSkip(original, file) + (transform) => !transform.shouldSkip(original, file), ); if (transforms.length === 0) { diff --git a/scripts/build/transform/transforms/create-method-call-transform.js b/scripts/build/transform/transforms/create-method-call-transform.js index 4ac104319..acb980340 100644 --- a/scripts/build/transform/transforms/create-method-call-transform.js +++ b/scripts/build/transform/transforms/create-method-call-transform.js @@ -35,7 +35,7 @@ function transformMethodCallToFunctionCall(node, functionName) { value: node.callee.type === "OptionalMemberExpression", leadingComments: [{ type: "CommentBlock", value: " isOptionalObject" }], }, - node.callee.object + node.callee.object, ); node.callee = { type: "Identifier", name: functionName }; @@ -55,7 +55,7 @@ function createMethodCallTransform({ test: (node) => isMethodCall(node, { methodName, argumentsLength }), transform: (node) => transformMethodCallToFunctionCall(node, functionName), inject: `import ${functionName} from ${JSON.stringify( - functionImplementationPath + functionImplementationPath, )};`, }; } diff --git a/scripts/build/transform/transforms/transform-string-replace-all.js b/scripts/build/transform/transforms/transform-string-replace-all.js index ade622218..f3038fcde 100644 --- a/scripts/build/transform/transforms/transform-string-replace-all.js +++ b/scripts/build/transform/transforms/transform-string-replace-all.js @@ -6,7 +6,7 @@ const transformStringReplaceAll = createMethodCallTransform({ functionName: "__stringReplaceAll", functionImplementationUrl: new URL( "../../shims/string-replace-all.js", - import.meta.url + import.meta.url, ), }); diff --git a/scripts/changelog-for-patch.js b/scripts/changelog-for-patch.js index 9f79898b6..eca2d3319 100644 --- a/scripts/changelog-for-patch.js +++ b/scripts/changelog-for-patch.js @@ -23,8 +23,8 @@ console.log( printEntries(entries).join("\n\n"), previousVersion, newVersion, - /** isPatch */ true - ) + /** isPatch */ true, + ), ); function parseArgv() { @@ -37,7 +37,7 @@ function parseArgv() { semver.compare(previousVersion, newVersion) !== -1 ) { throw new Error( - `Invalid argv, prev-version: ${previousVersion}, new-version: ${newVersion}` + `Invalid argv, prev-version: ${previousVersion}, new-version: ${newVersion}`, ); } return { previousVersion, newVersion }; diff --git a/scripts/check-deps.js b/scripts/check-deps.js index 61e7b9fdb..097a2867a 100644 --- a/scripts/check-deps.js +++ b/scripts/check-deps.js @@ -2,7 +2,7 @@ import fs from "node:fs/promises"; import chalk from "chalk"; const packageJson = JSON.parse( - await fs.readFile(new URL("../package.json", import.meta.url)) + await fs.readFile(new URL("../package.json", import.meta.url)), ); validateDependencyObject(packageJson.dependencies); @@ -13,7 +13,7 @@ function validateDependencyObject(object) { if (object[key][0] === "^" || object[key][0] === "~") { console.error( chalk.red("error"), - `Dependency "${chalk.bold.red(key)}" should be pinned.` + `Dependency "${chalk.bold.red(key)}" should be pinned.`, ); process.exitCode = 1; } diff --git a/scripts/clean-changelog-unreleased.js b/scripts/clean-changelog-unreleased.js index dcc75641d..f8b0fa883 100644 --- a/scripts/clean-changelog-unreleased.js +++ b/scripts/clean-changelog-unreleased.js @@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url"; import fastGlob from "fast-glob"; const changelogUnreleasedDir = fileURLToPath( - new URL("../changelog_unreleased", import.meta.url) + new URL("../changelog_unreleased", import.meta.url), ); const files = fastGlob.sync(["blog-post-intro.md", "*/*.md"], { diff --git a/scripts/clean-cspell.js b/scripts/clean-cspell.js index d1165dccc..24752b357 100644 --- a/scripts/clean-cspell.js +++ b/scripts/clean-cspell.js @@ -42,7 +42,7 @@ if (removed.length > 0) { console.log( `${removed.length} words removed: \n${removed .map((word) => ` - ${word}`) - .join("\n")}` + .join("\n")}`, ); } const added = words.filter((word) => !original.includes(word)); @@ -50,7 +50,7 @@ if (added.length > 0) { console.log( `${added.length} words added: \n${added .map((word) => ` - ${word}`) - .join("\n")}` + .join("\n")}`, ); } diff --git a/scripts/draft-blog-post.js b/scripts/draft-blog-post.js index 06a138d82..54df7538f 100644 --- a/scripts/draft-blog-post.js +++ b/scripts/draft-blog-post.js @@ -17,7 +17,7 @@ const { __dirname, require } = createEsmUtils(import.meta); const blogDir = path.join(__dirname, "../website/blog"); const introTemplateFile = path.join( changelogUnreleasedDirPath, - "BLOG_POST_INTRO_TEMPLATE.md" + "BLOG_POST_INTRO_TEMPLATE.md", ); const introFile = path.join(changelogUnreleasedDirPath, "blog-post-intro.md"); if (!fs.existsSync(introFile)) { @@ -27,13 +27,13 @@ if (!fs.existsSync(introFile)) { const prevVersion = require("../node_modules/prettier/package.json").version; const { version } = require("../package.json"); const nextVersion = `${semver.major(version)}.${semver.minor( - version + version, )}.${semver.patch(version)}`; const postGlob = path.join(blogDir, `????-??-??-${nextVersion}.md`); const postFile = path.join( blogDir, - `${new Date().toISOString().replace(/T.+/, "")}-${nextVersion}.md` + `${new Date().toISOString().replace(/T.+/, "")}-${nextVersion}.md`, ); const categories = [ @@ -59,7 +59,7 @@ const categories = [ ]; const categoriesByDir = new Map( - categories.map((category) => [category.dir, category]) + categories.map((category) => [category.dir, category]), ); for (const dir of changelogUnreleasedDirs) { @@ -108,8 +108,8 @@ fs.writeFileSync( .filter(Boolean) .join("\n\n") + "\n", prevVersion, - nextVersion - ) + nextVersion, + ), ); function printEntriesWithTitle({ title, filter }) { diff --git a/scripts/generate-changelog.js b/scripts/generate-changelog.js index f13c5fee3..2bcdb153c 100644 --- a/scripts/generate-changelog.js +++ b/scripts/generate-changelog.js @@ -79,7 +79,7 @@ async function getPr(prNumber) { async function addNewChangelog(prNumber, category, newChangelog) { const newChangelogPath = path.resolve( __dirname, - `../changelog_unreleased/${category}/${prNumber}.md` + `../changelog_unreleased/${category}/${prNumber}.md`, ); await fs.writeFile(newChangelogPath, newChangelog); return newChangelogPath; @@ -95,7 +95,7 @@ async function addNewChangelog(prNumber, category, newChangelog) { async function createChangelog(title, user, prNumber, category) { const changelogTemplatePath = path.resolve( __dirname, - "../changelog_unreleased/TEMPLATE.md" + "../changelog_unreleased/TEMPLATE.md", ); const changelogTemplate = await fs.readFile(changelogTemplatePath, "utf8"); @@ -117,11 +117,11 @@ async function createChangelog(title, user, prNumber, category) { .replace(inputCommentPart, getCommentForSyntax(syntax, "Input") + "\n") .replace( stableCommentPart, - getCommentForSyntax(syntax, "Prettier stable") + "\n" + getCommentForSyntax(syntax, "Prettier stable") + "\n", ) .replace( mainCommentPart, - getCommentForSyntax(syntax, "Prettier main") + "\n" + getCommentForSyntax(syntax, "Prettier main") + "\n", ); } diff --git a/scripts/generate-schema.js b/scripts/generate-schema.js index 1ad4405ad..05ef19414 100644 --- a/scripts/generate-schema.js +++ b/scripts/generate-schema.js @@ -7,5 +7,5 @@ import generateSchema from "./utils/generate-schema.mjs"; console.log( await format(JSON.stringify(generateSchema(getSupportInfo().options)), { parser: "json", - }) + }), ); diff --git a/scripts/lint-changelog.js b/scripts/lint-changelog.js index 642875549..cf0093480 100644 --- a/scripts/lint-changelog.js +++ b/scripts/lint-changelog.js @@ -44,7 +44,7 @@ const titleRegex = /^#{4} (.*?)\((#\d{4,}|\[#\d{4,}])/; const template = fs.readFileSync( path.join(CHANGELOG_ROOT, TEMPLATE_FILE), - "utf8" + "utf8", ); const templateComments = template.match(//gs); const [templateAuthorLink] = template.match(authorRegex); @@ -54,7 +54,7 @@ for (const category of CHANGELOG_CATEGORIES) { const files = fs.readdirSync(path.join(CHANGELOG_ROOT, category)); if (!files.includes(".gitkeep")) { showErrorMessage( - `Please don't remove ".gitkeep" from "${CHANGELOG_DIR}/${category}".` + `Please don't remove ".gitkeep" from "${CHANGELOG_DIR}/${category}".`, ); } @@ -68,7 +68,7 @@ for (const category of CHANGELOG_CATEGORIES) { if (!match) { showErrorMessage( - `[${displayPath}]: Filename is not in form of "{PR_NUMBER}.md".` + `[${displayPath}]: Filename is not in form of "{PR_NUMBER}.md".`, ); continue; } @@ -80,13 +80,13 @@ for (const category of CHANGELOG_CATEGORIES) { Duplicate files for ${prLink} found. - ${checkedFiles.get(prFile)} - ${displayPath} - ` + `, ); } checkedFiles.set(prFile, displayPath); const content = fs.readFileSync( path.join(CHANGELOG_DIR, category, prFile), - "utf8" + "utf8", ); if (!content.includes(prLink)) { @@ -100,14 +100,14 @@ for (const category of CHANGELOG_CATEGORIES) { showErrorMessage( `[${displayPath}]: Please remove ${getCommentDescription( content, - comment - )}` + comment, + )}`, ); } } if (content.includes(templateAuthorLink)) { showErrorMessage( - `[${displayPath}]: Please change author link to your github account.` + `[${displayPath}]: Please change author link to your github account.`, ); } if (!content.startsWith("#### ")) { @@ -124,19 +124,19 @@ for (const category of CHANGELOG_CATEGORIES) { [...CHANGELOG_CATEGORIES, "js"].includes(categoryInTitle.toLowerCase()) ) { showErrorMessage( - `[${displayPath}]: Please remove "${categoryInTitle}:" in title.` + `[${displayPath}]: Please remove "${categoryInTitle}:" in title.`, ); } if (!title.endsWith(" ") || title.length - title.trimEnd().length !== 1) { showErrorMessage( - `[${displayPath}]: Please put one space between title and PR link.` + `[${displayPath}]: Please put one space between title and PR link.`, ); } if (/prettier master/i.test(content)) { showErrorMessage( - `[${displayPath}]: Please use "main" instead of "master".` + `[${displayPath}]: Please use "main" instead of "master".`, ); } } @@ -147,7 +147,7 @@ function getCommentDescription(content, comment) { const end = start + comment.length; const linesAndColumns = new LinesAndColumns(content); const [startLine, endLine] = [start, end].map( - (index) => linesAndColumns.locationForIndex(index).line + 1 + (index) => linesAndColumns.locationForIndex(index).line + 1, ); if (startLine === endLine) { diff --git a/scripts/release/run.js b/scripts/release/run.js index 231610a57..0fc4803e4 100644 --- a/scripts/release/run.js +++ b/scripts/release/run.js @@ -19,40 +19,40 @@ if (semver.parse(previousVersion) === null) { } for (let step of [ - { - name: "Validating new version", - process: steps.validateNewVersion, - }, - { - name: "Checking git status", - process: steps.checkGitStatus, - skip: params.dry, - }, - { - name: "Installing NPM dependencies", - process: steps.installDependencies, - skip: params.dry || params.skipDependenciesInstall || !params.manual, - }, - { - name: "Linting files", - process: steps.lintFiles, - skip: params.dry, - }, - { - name: "Bumping version", - process: steps.updateVersion, - skip: params.dry, - }, - steps.generateBundles, - steps.updateChangelog, - { - name: "Committing and pushing to remote", - process: steps.pushToGit, - skip: params.dry, - }, - params.manual ? steps.publishToNpm : steps.waitForBotRelease, - steps.showInstructionsAfterNpmPublish, - steps.updateDependentsCount, + // { + // name: "Validating new version", + // process: steps.validateNewVersion, + // }, + // { + // name: "Checking git status", + // process: steps.checkGitStatus, + // skip: params.dry, + // }, + // { + // name: "Installing NPM dependencies", + // process: steps.installDependencies, + // skip: params.dry || params.skipDependenciesInstall || !params.manual, + // }, + // { + // name: "Linting files", + // process: steps.lintFiles, + // skip: params.dry, + // }, + // { + // name: "Bumping version", + // process: steps.updateVersion, + // skip: params.dry, + // }, + // steps.generateBundles, + // steps.updateChangelog, + // { + // name: "Committing and pushing to remote", + // process: steps.pushToGit, + // skip: params.dry, + // }, + // params.manual ? steps.publishToNpm : steps.waitForBotRelease, + // steps.showInstructionsAfterNpmPublish, + // steps.updateDependentsCount, steps.bumpPrettier, steps.postPublishSteps, ]) { diff --git a/scripts/release/steps/bump-prettier.js b/scripts/release/steps/bump-prettier.js index 924b73381..6e9d45c1c 100644 --- a/scripts/release/steps/bump-prettier.js +++ b/scripts/release/steps/bump-prettier.js @@ -37,16 +37,19 @@ async function bump({ } export default async function bumpPrettier(params) { - const { dry, version } = params; + const { + dry, + // version + } = params; if (dry) { return; } - await logPromise( - "Installing Prettier", - runYarn(["add", "--dev", `prettier@${version}`]) - ); + // await logPromise( + // "Installing Prettier", + // runYarn(["add", "--dev", `prettier@${version}`]) + // ); await logPromise("Updating files", format()); await logPromise("Bump default branch version", bump(params)); diff --git a/scripts/release/steps/check-git-status.js b/scripts/release/steps/check-git-status.js index 400cc8b0e..bb13636f7 100644 --- a/scripts/release/steps/check-git-status.js +++ b/scripts/release/steps/check-git-status.js @@ -6,7 +6,7 @@ export default async function checkGitStatus() { if (status) { throw new Error( "Uncommitted local changes. " + - "Please revert or commit all local changes before making a release." + "Please revert or commit all local changes before making a release.", ); } } diff --git a/scripts/release/steps/generate-bundles.js b/scripts/release/steps/generate-bundles.js index 9de180cd5..419f23fca 100644 --- a/scripts/release/steps/generate-bundles.js +++ b/scripts/release/steps/generate-bundles.js @@ -8,20 +8,20 @@ export default async function generateBundles({ dry, version, manual }) { await logPromise( "Generating bundles", - runYarn(["build", "--clean", "--print-size", "--compare-size"]) + runYarn(["build", "--clean", "--print-size", "--compare-size"]), ); const builtPkg = await readJson("dist/package.json"); if (!dry && builtPkg.version !== version) { throw new Error( - `Expected ${version} in dist/package.json but found ${builtPkg.version}` + `Expected ${version} in dist/package.json but found ${builtPkg.version}`, ); } await logPromise( "Running tests on generated bundles", () => runYarn("test:dist"), - /* shouldSkip */ dry + /* shouldSkip */ dry, ); console.log(chalk.green.bold("Build successful!\n")); diff --git a/scripts/release/steps/install-dependencies.js b/scripts/release/steps/install-dependencies.js index 78f890cb9..8ca56a563 100644 --- a/scripts/release/steps/install-dependencies.js +++ b/scripts/release/steps/install-dependencies.js @@ -11,7 +11,7 @@ export default async function installDependencies() { const { stdout: status } = await runGit(["ls-files", "-m"]); if (status) { throw new Error( - "The lockfile needs to be updated, commit it before making the release." + "The lockfile needs to be updated, commit it before making the release.", ); } } diff --git a/scripts/release/steps/post-publish-steps.js b/scripts/release/steps/post-publish-steps.js index 8f967e74d..cdaf5e598 100644 --- a/scripts/release/steps/post-publish-steps.js +++ b/scripts/release/steps/post-publish-steps.js @@ -16,7 +16,7 @@ async function checkSchema() { ]); const remoteSchema = await logPromise( "Checking current schema in SchemaStore", - fetchText(RAW_URL) + fetchText(RAW_URL), ); if (schema === remoteSchema.trim()) { @@ -25,11 +25,11 @@ async function checkSchema() { return outdent` ${chalk.bold.underline( - "The schema in {yellow SchemaStore" + "The schema in {yellow SchemaStore", )} needs an update.} - Open ${chalk.cyan.underline(EDIT_URL)} - Run ${chalk.yellow( - "node scripts/generate-schema.mjs" + "node scripts/generate-schema.mjs", )} and copy the new schema - Paste it on GitHub interface - Open a PR @@ -59,10 +59,10 @@ export default async function postPublishSteps({ dry }) { ${chalk.yellow.bold( `The following ${ steps.length === 1 ? "step is" : "steps are" - } optional.` + } optional.`, )} ${steps.join("\n\n")} - ` + `, ); } diff --git a/scripts/release/steps/show-instructions-after-npm-publish.js b/scripts/release/steps/show-instructions-after-npm-publish.js index 944ac2115..e048e9660 100644 --- a/scripts/release/steps/show-instructions-after-npm-publish.js +++ b/scripts/release/steps/show-instructions-after-npm-publish.js @@ -51,12 +51,12 @@ export default async function showInstructionsAfterNpmPublish({ ${chalk.bold.underline("Test the new release")} - In a new session, run ${chalk.yellow( - "npm i prettier@latest" + "npm i prettier@latest", )} in another directory - Test the API and CLI After that, we can proceed to bump this repo's Prettier dependency. - ` + `, ); await waitForEnter(); diff --git a/scripts/release/steps/update-changelog.js b/scripts/release/steps/update-changelog.js index 688634901..c151407d0 100644 --- a/scripts/release/steps/update-changelog.js +++ b/scripts/release/steps/update-changelog.js @@ -51,10 +51,10 @@ export default async function updateChangelog({ } console.warn( `${chalk.yellow("warning")} The file ${chalk.bold( - blogPost.file + blogPost.file, )} doesn't exist, but it will be referenced in ${chalk.bold( - "CHANGELOG.md" - )}. Make sure to create it later.` + "CHANGELOG.md", + )}. Make sure to create it later.`, ); } else { const body = await getChangelogForPatch({ @@ -71,6 +71,6 @@ export default async function updateChangelog({ await waitForEnter(); await logPromise( "Re-running Prettier on docs", - runYarn(["lint:prettier", "--write"]) + runYarn(["lint:prettier", "--write"]), ); } diff --git a/scripts/release/steps/update-dependents-count.js b/scripts/release/steps/update-dependents-count.js index 4915d304c..0bf168f15 100644 --- a/scripts/release/steps/update-dependents-count.js +++ b/scripts/release/steps/update-dependents-count.js @@ -4,32 +4,32 @@ import { runGit, fetchText, logPromise, processFile } from "../utils.js"; async function update() { const npmPage = await logPromise( "Fetching npm dependents count", - fetchText("https://www.npmjs.com/package/prettier") + fetchText("https://www.npmjs.com/package/prettier"), ); const dependentsCountNpm = Number( - npmPage.match(/"dependentsCount":(\d+),/)[1] + npmPage.match(/"dependentsCount":(\d+),/)[1], ); if (Number.isNaN(dependentsCountNpm)) { throw new TypeError( - "Invalid data from https://www.npmjs.com/package/prettier" + "Invalid data from https://www.npmjs.com/package/prettier", ); } const githubPage = await logPromise( "Fetching github dependents count", - fetchText("https://github.com/prettier/prettier/network/dependents") + fetchText("https://github.com/prettier/prettier/network/dependents"), ); const dependentsCountGithub = Number( githubPage .replaceAll("\n", "") .match( - /.*?<\/svg>\s*([\d,]+)\s*Repositories\s*<\/a>/ + /.*?<\/svg>\s*([\d,]+)\s*Repositories\s*<\/a>/, )[1] - .replaceAll(",", "") + .replaceAll(",", ""), ); if (Number.isNaN(dependentsCountNpm)) { throw new TypeError( - "Invalid data from https://github.com/prettier/prettier/network/dependents" + "Invalid data from https://github.com/prettier/prettier/network/dependents", ); } @@ -37,19 +37,19 @@ async function update() { content .replace( /()(.*?)(<\/strong>)/, - `$1${formatNumber(dependentsCountNpm)}$3` + `$1${formatNumber(dependentsCountNpm)}$3`, ) .replace( /()(.*?)(<\/strong>)/, - `$1${formatNumber(dependentsCountGithub)}$3` - ) + `$1${formatNumber(dependentsCountGithub)}$3`, + ), ); const isUpdated = await logPromise( "Checking if dependents count has been updated", async () => (await runGit(["diff", "--name-only"])).stdout === - "website/pages/en/index.js" + "website/pages/en/index.js", ); if (isUpdated) { diff --git a/scripts/release/steps/update-version.js b/scripts/release/steps/update-version.js index a79131b00..63cea4834 100644 --- a/scripts/release/steps/update-version.js +++ b/scripts/release/steps/update-version.js @@ -7,21 +7,21 @@ export default async function updateVersion({ version }) { // Update github issue templates processFile(".github/ISSUE_TEMPLATE/formatting.md", (content) => - content.replace(/^(\*\*Prettier ).*?(\*\*)$/m, `$1${version}$2`) + content.replace(/^(\*\*Prettier ).*?(\*\*)$/m, `$1${version}$2`), ); processFile(".github/ISSUE_TEMPLATE/integration.md", (content) => - content.replace(/^(- Prettier Version: ).*$/m, `$1${version}`) + content.replace(/^(- Prettier Version: ).*$/m, `$1${version}`), ); processFile("docs/install.md", (content) => - content.replace(/^(npx prettier@)\S+/m, `$1${version}`) + content.replace(/^(npx prettier@)\S+/m, `$1${version}`), ); // Update unpkg link in docs processFile("docs/browser.md", (content) => content.replaceAll( /(\/\/unpkg\.com\/(?:browse\/)?prettier@).*?\//g, - `$1${version}/` - ) + `$1${version}/`, + ), ); await runYarn(["update-stable-docs"], { diff --git a/scripts/release/steps/validate-new-version.js b/scripts/release/steps/validate-new-version.js index ccc2a86e8..8ec863ac7 100644 --- a/scripts/release/steps/validate-new-version.js +++ b/scripts/release/steps/validate-new-version.js @@ -8,13 +8,13 @@ export default function validateNewVersion({ version, previousVersion }) { if (!semver.valid(version)) { throw new Error( - `Invalid version '${chalk.red.underline(version)}' specified` + `Invalid version '${chalk.red.underline(version)}' specified`, ); } if (!semver.gt(version, previousVersion)) { throw new Error( - `Version '${chalk.yellow.underline(version)}' has already been published` + `Version '${chalk.yellow.underline(version)}' has already been published`, ); } } diff --git a/scripts/release/steps/wait-for-bot-release.js b/scripts/release/steps/wait-for-bot-release.js index 87a51599a..32021590b 100644 --- a/scripts/release/steps/wait-for-bot-release.js +++ b/scripts/release/steps/wait-for-bot-release.js @@ -35,10 +35,10 @@ export default async function waitForBotRelease({ dry, version }) { console.log( outdent` 1. Go to ${chalk.green.underline( - "https://www.npmjs.com/package/prettier/access" + "https://www.npmjs.com/package/prettier/access", )} 2. Add "${chalk.yellow("prettier-bot")}" as prettier package maintainer. - ` + `, ); await waitForEnter(); @@ -47,14 +47,14 @@ export default async function waitForBotRelease({ dry, version }) { console.log( outdent` 1. Go to ${chalk.green.underline( - "https://www.npmjs.com/package/prettier/access" + "https://www.npmjs.com/package/prettier/access", )} 2. Make sure "${chalk.yellow( - "Publishing access" + "Publishing access", )}" section is set to "${chalk.yellow( - "Require two-factor authentication or automation tokens" - )}". - ` + "Require two-factor authentication or automation tokens", + )}". + `, ); await waitForEnter(); @@ -62,16 +62,16 @@ export default async function waitForBotRelease({ dry, version }) { console.log( outdent` 1. Go to ${chalk.green.underline( - "https://github.com/prettier/release-workflow/actions/workflows/release.yml" + "https://github.com/prettier/release-workflow/actions/workflows/release.yml", )} 2. Click "${chalk.green( - "Run workflow" + "Run workflow", )}" button, type "${chalk.yellow.underline( - version - )}" in "Version to release", uncheck all checkboxes, hit the "${chalk.bgGreen( - "Run workflow" - )}" button. - ` + version, + )}" in "Version to release", uncheck all checkboxes, hit the "${chalk.bgGreen( + "Run workflow", + )}" button. + `, ); await waitForEnter(); @@ -81,7 +81,7 @@ export default async function waitForBotRelease({ dry, version }) { try { released = await logPromise( "Checking release status", - isVersionReleased(version) + isVersionReleased(version), ); } catch { // No op diff --git a/scripts/release/tests/publish-to-npm.test.js b/scripts/release/tests/publish-to-npm.test.js index 4b580a3e8..2b49e553a 100644 --- a/scripts/release/tests/publish-to-npm.test.js +++ b/scripts/release/tests/publish-to-npm.test.js @@ -25,7 +25,7 @@ describe("publish-to-npm", () => { tag: "2.3.1", title: "2.3.1", body: "🔗 [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md#231)", - }) + }), ); }); @@ -39,10 +39,10 @@ describe("publish-to-npm", () => { body: [ "[diff](https://github.com/prettier/prettier/compare/2.3.0...2.4.0)", `🔗 [Release note](https://prettier.io/blog/${getDateParts().join( - "/" + "/", )}/2.4.0.html)`, ].join("\n\n"), - }) + }), ); }); @@ -56,10 +56,10 @@ describe("publish-to-npm", () => { body: [ "[diff](https://github.com/prettier/prettier/compare/2.2.0...2.3.0)", `🔗 [Release note](https://prettier.io/blog/${getDateParts().join( - "/" + "/", )}/2.3.0.html)`, ].join("\n\n"), - }) + }), ); }); }); diff --git a/scripts/release/tests/validate-new-version.test.js b/scripts/release/tests/validate-new-version.test.js index 22dc6df47..635278f78 100644 --- a/scripts/release/tests/validate-new-version.test.js +++ b/scripts/release/tests/validate-new-version.test.js @@ -9,7 +9,7 @@ describe("validate-new-version", () => { () => { validateNewVersion({}); }, - { message: "'--version' is required" } + { message: "'--version' is required" }, ); }); it("throws error for invalid semver", () => { @@ -17,7 +17,7 @@ describe("validate-new-version", () => { () => { validateNewVersion({ version: "foo" }); }, - { message: `Invalid version '${chalk.red.underline("foo")}' specified` } + { message: `Invalid version '${chalk.red.underline("foo")}' specified` }, ); }); it("throws error when version isn't greater than prev version", () => { @@ -27,9 +27,9 @@ describe("validate-new-version", () => { }, { message: `Version '${chalk.yellow( - "0.0.1" + "0.0.1", )}' has already been published`, - } + }, ); }); }); diff --git a/scripts/sync-flow-tests.cjs b/scripts/sync-flow-tests.cjs index a49ff62ed..d6bd27fdc 100644 --- a/scripts/sync-flow-tests.cjs +++ b/scripts/sync-flow-tests.cjs @@ -29,7 +29,7 @@ function tryParse(file, content) { function syncTests(syncDir) { const specFiles = fastGlob.sync( - path.join(FLOW_TESTS_DIR, "**", SPEC_FILE_NAME) + path.join(FLOW_TESTS_DIR, "**", SPEC_FILE_NAME), ); const filesToCopy = fastGlob.sync(path.join(syncDir, "**/*.js")); @@ -38,7 +38,7 @@ function syncTests(syncDir) { [ "Couldn't find any files to copy.", `Please make sure that \`${syncDir}\` exists and contains the flow tests.`, - ].join("\n") + ].join("\n"), ); } @@ -79,7 +79,7 @@ function run(argv) { [ "You must provide the path to a flow tests directory to sync from!", "Example: node scripts/sync-flow-tests.cjs ../flow/tests/", - ].join("\n") + ].join("\n"), ); return 1; } @@ -104,7 +104,7 @@ function run(argv) { "", ...skipped, "", - ].join("\n") + ].join("\n"), ); } @@ -116,7 +116,7 @@ function run(argv) { "2. Run `jest -u` to create snapshots.", "3. Run `git diff` to check how tests and snapshots have changed", "4. Take a look at new snapshots to see if they're OK.", - ].join("\n") + ].join("\n"), ); return 0; diff --git a/scripts/tools/bundle-test/index.js b/scripts/tools/bundle-test/index.js index 7edbd4525..5d93180de 100644 --- a/scripts/tools/bundle-test/index.js +++ b/scripts/tools/bundle-test/index.js @@ -27,7 +27,7 @@ function runWebpack(config) { } const TEMPORARY_DIRECTORY = url.fileURLToPath( - new URL("./.tmp", import.meta.url) + new URL("./.tmp", import.meta.url), ); /* `require` in `parser-typescript.js`, #12338 */ diff --git a/scripts/tools/eslint-plugin-prettier-internal-rules/better-parent-property-check-in-needs-parens.js b/scripts/tools/eslint-plugin-prettier-internal-rules/better-parent-property-check-in-needs-parens.js index 29018d85d..6c75d0aa8 100644 --- a/scripts/tools/eslint-plugin-prettier-internal-rules/better-parent-property-check-in-needs-parens.js +++ b/scripts/tools/eslint-plugin-prettier-internal-rules/better-parent-property-check-in-needs-parens.js @@ -67,7 +67,7 @@ module.exports = { [parentPropertyCheckSelector](node) { const { operator, left, right } = node; const { property } = [left, right].find( - ({ type }) => type === "MemberExpression" + ({ type }) => type === "MemberExpression", ); const propertyText = property.type === "Identifier" diff --git a/scripts/tools/eslint-plugin-prettier-internal-rules/flat-ast-path-call.js b/scripts/tools/eslint-plugin-prettier-internal-rules/flat-ast-path-call.js index 135274818..eadaccfba 100644 --- a/scripts/tools/eslint-plugin-prettier-internal-rules/flat-ast-path-call.js +++ b/scripts/tools/eslint-plugin-prettier-internal-rules/flat-ast-path-call.js @@ -83,7 +83,7 @@ module.exports = { // ^ innerCallback.range[0], ], - "" + "", ); // path.call((childPath) => childPath.call(print, "b"), "a") @@ -96,17 +96,17 @@ module.exports = { let innerNamesText = sourceCode.text.slice( innerNamesStart, - innerNamesEnd + innerNamesEnd, ); yield fixer.replaceTextRange( [innerNamesStart, innerNamesEnd + 1], - "" + "", ); const [penultimateToken, lastToken] = sourceCode.getLastTokens( outerCall, - 2 + 2, ); // `outer` call has `trailing comma` diff --git a/scripts/tools/eslint-plugin-prettier-internal-rules/jsx-identifier-case.js b/scripts/tools/eslint-plugin-prettier-internal-rules/jsx-identifier-case.js index e56e20335..3c8a32d86 100644 --- a/scripts/tools/eslint-plugin-prettier-internal-rules/jsx-identifier-case.js +++ b/scripts/tools/eslint-plugin-prettier-internal-rules/jsx-identifier-case.js @@ -24,7 +24,7 @@ module.exports = { const ignored = new Set(context.options); return { "Identifier[name=/JSX/]:not(ObjectExpression > Property.properties > .key)"( - node + node, ) { const { name } = node; diff --git a/scripts/tools/eslint-plugin-prettier-internal-rules/no-doc-public-import.js b/scripts/tools/eslint-plugin-prettier-internal-rules/no-doc-public-import.js index b919e87ed..2c230e847 100644 --- a/scripts/tools/eslint-plugin-prettier-internal-rules/no-doc-public-import.js +++ b/scripts/tools/eslint-plugin-prettier-internal-rules/no-doc-public-import.js @@ -53,7 +53,7 @@ function fix(source, context) { property.type === "Property" && !property.computed && property.key.type === "Identifier" && - docProperties.has(property.key.name) + docProperties.has(property.key.name), ) && identifier.parent.parent.type === "VariableDeclaration" && identifier.parent.parent.kind === "const" && @@ -71,10 +71,10 @@ function fix(source, context) { const propertyName = property.key.name; return `import ${sourceCode.getText( - property.value + property.value, )} from "${source.value.replace( "/document/public.js", - `/document/${propertyName}.js` + `/document/${propertyName}.js`, )}";`; }) .join("\n"); diff --git a/scripts/tools/eslint-plugin-prettier-internal-rules/no-node-comments.js b/scripts/tools/eslint-plugin-prettier-internal-rules/no-node-comments.js index 5920f6e74..44fff07f8 100644 --- a/scripts/tools/eslint-plugin-prettier-internal-rules/no-node-comments.js +++ b/scripts/tools/eslint-plugin-prettier-internal-rules/no-node-comments.js @@ -65,7 +65,7 @@ module.exports = { path.join(__dirname, "../../..", file), functions ? new Set(functions) : true, ]; - }) + }), ); // avoid report on `const {comments} = node` twice const reported = new Set(); diff --git a/scripts/tools/eslint-plugin-prettier-internal-rules/prefer-ast-path-getters.js b/scripts/tools/eslint-plugin-prettier-internal-rules/prefer-ast-path-getters.js index 22736b664..525f208e5 100644 --- a/scripts/tools/eslint-plugin-prettier-internal-rules/prefer-ast-path-getters.js +++ b/scripts/tools/eslint-plugin-prettier-internal-rules/prefer-ast-path-getters.js @@ -89,7 +89,7 @@ module.exports = { const useGetter = (getter) => (fixer) => fixer.replaceTextRange( [callExpression.callee.property.range[0], callExpression.range[1]], - getter + getter, ); if (replacement.getter) { diff --git a/scripts/tools/eslint-plugin-prettier-internal-rules/prefer-create-type-check-function.js b/scripts/tools/eslint-plugin-prettier-internal-rules/prefer-create-type-check-function.js index 451fe13c4..65eb0aa99 100644 --- a/scripts/tools/eslint-plugin-prettier-internal-rules/prefer-create-type-check-function.js +++ b/scripts/tools/eslint-plugin-prettier-internal-rules/prefer-create-type-check-function.js @@ -218,7 +218,7 @@ module.exports = { : types.reduce( (count, { node }) => count + sourceCode.getCommentsInside(node).length, - 0 + 0, ); if (commentsInFunction === commentsInTypes) { @@ -230,8 +230,8 @@ module.exports = { .map( ({ type, node }) => `${type === "single" ? "" : "..."}${sourceCode.getText( - node - )}` + node, + )}`, ) .join(", ")}]`; @@ -248,7 +248,7 @@ module.exports = { ) { return fixer.replaceText( functionNode.parent, - `${text}\nexport default ${functionName};` + `${text}\nexport default ${functionName};`, ); } } diff --git a/scripts/tools/eslint-plugin-prettier-internal-rules/prefer-indent-if-break.js b/scripts/tools/eslint-plugin-prettier-internal-rules/prefer-indent-if-break.js index 7cf0ced68..fe08ff719 100644 --- a/scripts/tools/eslint-plugin-prettier-internal-rules/prefer-indent-if-break.js +++ b/scripts/tools/eslint-plugin-prettier-internal-rules/prefer-indent-if-break.js @@ -48,15 +48,15 @@ module.exports = { *fix(fixer) { yield fixer.replaceText(node.callee, "indentIfBreak"); const openingParenthesisToken = sourceCode.getTokenAfter( - node.callee + node.callee, ); const commaToken = sourceCode.getTokenBefore( doc, - ({ type, value }) => type === "Punctuator" && value === "," + ({ type, value }) => type === "Punctuator" && value === ",", ); yield fixer.replaceTextRange( [openingParenthesisToken.range[1], commaToken.range[1]], - "" + "", ); }, }); diff --git a/scripts/tools/eslint-plugin-prettier-internal-rules/prefer-is-non-empty-array.js b/scripts/tools/eslint-plugin-prettier-internal-rules/prefer-is-non-empty-array.js index 6b4a8e81b..35a09fa0b 100644 --- a/scripts/tools/eslint-plugin-prettier-internal-rules/prefer-is-non-empty-array.js +++ b/scripts/tools/eslint-plugin-prettier-internal-rules/prefer-is-non-empty-array.js @@ -99,7 +99,7 @@ module.exports = { fix(fixer) { return fixer.replaceTextRange( [start, end], - `isNonEmptyArray(${objectText})` + `isNonEmptyArray(${objectText})`, ); }, }); @@ -141,7 +141,7 @@ module.exports = { fix(fixer) { return fixer.replaceTextRange( [start, end], - `!isNonEmptyArray(${objectText})` + `!isNonEmptyArray(${objectText})`, ); }, }); diff --git a/scripts/tools/eslint-plugin-prettier-internal-rules/test.js b/scripts/tools/eslint-plugin-prettier-internal-rules/test.js index 95f90d5d6..94e90fc67 100644 --- a/scripts/tools/eslint-plugin-prettier-internal-rules/test.js +++ b/scripts/tools/eslint-plugin-prettier-internal-rules/test.js @@ -10,7 +10,7 @@ const test = (ruleId, tests) => { new RuleTester({ parserOptions: { ecmaVersion: 2021 } }).run( ruleId, rules[ruleId], - tests + tests, ); }; diff --git a/scripts/utils/changelog.js b/scripts/utils/changelog.js index 4bb05b03c..1b7054312 100644 --- a/scripts/utils/changelog.js +++ b/scripts/utils/changelog.js @@ -7,7 +7,7 @@ const { __dirname } = createEsmUtils(import.meta); export const changelogUnreleasedDirPath = path.join( __dirname, - "../../changelog_unreleased" + "../../changelog_unreleased", ); export const changelogUnreleasedDirs = fs @@ -65,18 +65,18 @@ export function printEntries(entries) { export function replaceVersions(data, prevVer, newVer, isPatch = false) { if (semver.compare(prevVer, newVer) >= 0) { throw new Error( - `[INVALID VERSION] Next version(${newVer}) should be greater than previous version(${prevVer}).` + `[INVALID VERSION] Next version(${newVer}) should be greater than previous version(${prevVer}).`, ); } return data .replaceAll( /prettier stable/gi, - `Prettier ${isPatch ? prevVer : formatVersion(prevVer)}` + `Prettier ${isPatch ? prevVer : formatVersion(prevVer)}`, ) .replaceAll( /prettier main/gi, - `Prettier ${isPatch ? newVer : formatVersion(newVer)}` + `Prettier ${isPatch ? newVer : formatVersion(newVer)}`, ); } @@ -92,6 +92,6 @@ function processTitle(title) { .replaceAll(/(? [option.name, optionToSchema(option)]) + options.map((option) => [option.name, optionToSchema(option)]), ), }, overridesDefinition: { @@ -100,7 +100,7 @@ function optionTypeToSchemaType(optionType) { return optionType; case "choice": throw new Error( - "Please use `oneOf` instead of `enum` for better description support." + "Please use `oneOf` instead of `enum` for better description support.", ); case "path": return "string"; diff --git a/src/cli/expand-patterns.js b/src/cli/expand-patterns.js index 8d162da99..2eb643b4c 100644 --- a/src/cli/expand-patterns.js +++ b/src/cli/expand-patterns.js @@ -130,10 +130,10 @@ async function* expandPatternsInternal(context) { function getSupportedFilesGlob() { if (!supportedFilesGlob) { const extensions = context.languages.flatMap( - (lang) => lang.extensions || [] + (lang) => lang.extensions || [], ); const filenames = context.languages.flatMap( - (lang) => lang.filenames || [] + (lang) => lang.filenames || [], ); supportedFilesGlob = `**/{${[ ...extensions.map((ext) => "*" + (ext[0] === "." ? ext : "." + ext)), @@ -185,7 +185,7 @@ function sortPaths(paths) { function escapePathForGlob(path) { return fastGlob .escapePath( - path.replaceAll("\\", "\0") // Workaround for fast-glob#262 (part 1) + path.replaceAll("\\", "\0"), // Workaround for fast-glob#262 (part 1) ) .replaceAll("\\!", "@(!)") // Workaround for fast-glob#261 .replaceAll("\0", "@(\\\\)"); // Workaround for fast-glob#262 (part 2) diff --git a/src/cli/find-cache-file.js b/src/cli/find-cache-file.js index c59cf3418..050766587 100644 --- a/src/cli/find-cache-file.js +++ b/src/cli/find-cache-file.js @@ -21,7 +21,7 @@ async function findCacheFileFromOption(cacheLocation) { if (stat) { if (stat.isDirectory()) { throw new Error( - `Resolved --cache-location '${cacheFile}' is a directory` + `Resolved --cache-location '${cacheFile}' is a directory`, ); } diff --git a/src/cli/format-results-cache.js b/src/cli/format-results-cache.js index 90c7a71b0..2bb8a0499 100644 --- a/src/cli/format-results-cache.js +++ b/src/cli/format-results-cache.js @@ -18,7 +18,7 @@ function getHashOfOptions(options) { return optionsHashCache.get(options); } const hash = createHash( - `${prettierVersion}_${nodeVersion}_${stringify(options)}` + `${prettierVersion}_${nodeVersion}_${stringify(options)}`, ); optionsHashCache.set(options, hash); return hash; @@ -48,7 +48,7 @@ class FormatResultsCache { this.#fileEntryCache = fileEntryCache.create( /* cacheId */ cacheFileLocation, /* directory */ undefined, - useChecksum + useChecksum, ); } diff --git a/src/cli/format.js b/src/cli/format.js index 3c6a46a23..fe1c05d9f 100644 --- a/src/cli/format.js +++ b/src/cli/format.js @@ -78,7 +78,7 @@ function handleError(context, filename, error, printedFilename) { function writeOutput(context, result, options) { // Don't use `console.log` here since it adds an extra newline at the end. process.stdout.write( - context.argv.debugCheck ? result.filepath : result.formatted + context.argv.debugCheck ? result.filepath : result.formatted, ); if (options && options.cursorOffset >= 0) { @@ -113,9 +113,9 @@ async function format(context, input, opt) { return { formatted: await prettier.format( JSON.stringify( - (await prettier.formatWithCursor(input, opt)).comments || [] + (await prettier.formatWithCursor(input, opt)).comments || [], ), - { parser: "json" } + { parser: "json" }, ), }; } @@ -132,15 +132,15 @@ async function format(context, input, opt) { const pppp = await prettier.format(pp, opt); if (pp !== pppp) { throw new DebugError( - "prettier(input) !== prettier(prettier(input))\n" + diff(pp, pppp) + "prettier(input) !== prettier(prettier(input))\n" + diff(pp, pppp), ); } else { const stringify = (obj) => JSON.stringify(obj, null, 2); const ast = stringify( - (await prettier.__debug.parse(input, opt, { massage: true })).ast + (await prettier.__debug.parse(input, opt, { massage: true })).ast, ); const past = stringify( - (await prettier.__debug.parse(pp, opt, { massage: true })).ast + (await prettier.__debug.parse(pp, opt, { massage: true })).ast, ); /* c8 ignore start */ @@ -154,7 +154,7 @@ async function format(context, input, opt) { "ast(input) !== ast(prettier(input))\n" + astDiff + "\n" + - diff(input, pp) + diff(input, pp), ); } /* c8 ignore end */ @@ -170,12 +170,12 @@ async function format(context, input, opt) { ({ default: benchmark } = await import("benchmark")); } catch { context.logger.debug( - "'--debug-benchmark' requires the 'benchmark' package to be installed." + "'--debug-benchmark' requires the 'benchmark' package to be installed.", ); process.exit(2); } context.logger.debug( - "'--debug-benchmark' option found, measuring formatWithCursor with 'benchmark' module." + "'--debug-benchmark' option found, measuring formatWithCursor with 'benchmark' module.", ); const suite = new benchmark.Suite(); suite.add("format", { @@ -198,12 +198,12 @@ async function format(context, input, opt) { }); context.logger.debug( "'--debug-benchmark' measurements for formatWithCursor: " + - JSON.stringify(result, null, 2) + JSON.stringify(result, null, 2), ); } else if (performanceTestFlag?.debugRepeat) { const repeat = performanceTestFlag.debugRepeat; context.logger.debug( - `'${performanceTestFlag.name}' found, running formatWithCursor ${repeat} times.` + `'${performanceTestFlag.name}' found, running formatWithCursor ${repeat} times.`, ); let totalMs = 0; for (let i = 0; i < repeat; ++i) { @@ -221,7 +221,11 @@ async function format(context, input, opt) { context.logger.debug( `'${ performanceTestFlag.name - }' measurements for formatWithCursor: ${JSON.stringify(results, null, 2)}` + }' measurements for formatWithCursor: ${JSON.stringify( + results, + null, + 2, + )}`, ); } @@ -232,7 +236,7 @@ async function createIsIgnoredFromContextOrDie(context) { try { return await createIsIgnoredFunction( context.argv.ignorePath, - context.argv.withNodeModules + context.argv.withNodeModules, ); } catch (e) { context.logger.error(e.message); @@ -259,7 +263,7 @@ async function formatStdin(context) { const options = await getOptionsForFile( context, - filepath ? path.resolve(process.cwd(), filepath) : process.cwd() + filepath ? path.resolve(process.cwd(), filepath) : process.cwd(), ); if (await listDifferent(context, input, options, "(stdin)")) { @@ -271,7 +275,7 @@ async function formatStdin(context) { const { performanceTestFlag } = context; if (performanceTestFlag) { context.logger.log( - `'${performanceTestFlag.name}' option found, skipped print code to screen.` + `'${performanceTestFlag.name}' option found, skipped print code to screen.`, ); return; } @@ -300,12 +304,12 @@ async function formatFiles(context) { if (context.argv.cache) { formatResultsCache = new FormatResultsCache( cacheFilePath, - context.argv.cacheStrategy || "content" + context.argv.cacheStrategy || "content", ); } else { if (context.argv.cacheStrategy) { context.logger.error( - "`--cache-strategy` cannot be used without `--cache`." + "`--cache-strategy` cannot be used without `--cache`.", ); process.exit(2); } @@ -361,7 +365,7 @@ async function formatFiles(context) { context.logger.log(""); context.logger.error( - `Unable to read file "${fileNameToDisplay}":\n${error.message}` + `Unable to read file "${fileNameToDisplay}":\n${error.message}`, ); // Don't exit the process if one file failed @@ -381,7 +385,7 @@ async function formatFiles(context) { const isCacheExists = formatResultsCache?.existsAvailableFormatResultsCache( filename, - options + options, ); let result; @@ -407,7 +411,7 @@ async function formatFiles(context) { if (performanceTestFlag) { context.logger.log( - `'${performanceTestFlag.name}' option found, skipped print code or write files.` + `'${performanceTestFlag.name}' option found, skipped print code or write files.`, ); return; } @@ -427,7 +431,7 @@ async function formatFiles(context) { shouldSetCache = true; } catch (error) { context.logger.error( - `Unable to write file "${fileNameToDisplay}":\n${error.message}` + `Unable to write file "${fileNameToDisplay}":\n${error.message}`, ); // Don't exit the process if one file failed @@ -484,7 +488,7 @@ async function formatFiles(context) { context.logger.warn( context.argv.write ? `Code style issues fixed in ${files}.` - : `Code style issues found in ${files}. Run Prettier to fix.` + : `Code style issues found in ${files}. Run Prettier to fix.`, ); } } diff --git a/src/cli/index.js b/src/cli/index.js index 1ea953392..954217bc3 100644 --- a/src/cli/index.js +++ b/src/cli/index.js @@ -17,7 +17,7 @@ async function run(rawArguments) { const { logLevel } = parseArgvWithoutPlugins( rawArguments, logger, - "log-level" + "log-level", ); if (logLevel !== logger.logLevel) { logger = createLogger(logLevel); @@ -63,7 +63,7 @@ async function main(context) { printToScreen( typeof context.argv.help === "string" && context.argv.help !== "" ? createDetailedUsage(context, context.argv.help) - : createUsage(context) + : createUsage(context), ); return; } diff --git a/src/cli/options/get-context-options.js b/src/cli/options/get-context-options.js index 3042a880d..cb6e1d700 100644 --- a/src/cli/options/get-context-options.js +++ b/src/cli/options/get-context-options.js @@ -8,7 +8,7 @@ import { import cliOptions from "../cli-options.evaluate.js"; const detailedCliOptions = normalizeOptionSettings(cliOptions).map((option) => - normalizeDetailedOption(option) + normalizeDetailedOption(option), ); function apiOptionToCliOption(apiOption) { diff --git a/src/cli/options/get-options-for-file.js b/src/cli/options/get-options-for-file.js index fefc5ee37..0d0fdbf3f 100644 --- a/src/cli/options/get-options-for-file.js +++ b/src/cli/options/get-options-for-file.js @@ -9,7 +9,7 @@ function getOptions(argv, detailedOptions) { return Object.fromEntries( detailedOptions .filter(({ forwardToApi }) => forwardToApi) - .map(({ forwardToApi, name }) => [forwardToApi, argv[name]]) + .map(({ forwardToApi, name }) => [forwardToApi, argv[name]]), ); } @@ -20,7 +20,7 @@ function cliifyOptions(object, apiDetailedOptionMap) { const cliKey = apiOption ? apiOption.name : key; return [dashify(cliKey), value]; - }) + }), ); } @@ -28,16 +28,16 @@ function createApiDetailedOptionMap(detailedOptions) { return Object.fromEntries( detailedOptions .filter( - (option) => option.forwardToApi && option.forwardToApi !== option.name + (option) => option.forwardToApi && option.forwardToApi !== option.name, ) - .map((option) => [option.forwardToApi, option]) + .map((option) => [option.forwardToApi, option]), ); } function parseArgsToOptions(context, overrideDefaults) { const minimistOptions = createMinimistOptions(context.detailedOptions); const apiDetailedOptionMap = createApiDetailedOptionMap( - context.detailedOptions + context.detailedOptions, ); return getOptions( normalizeCliOptions( @@ -47,9 +47,9 @@ function parseArgsToOptions(context, overrideDefaults) { default: cliifyOptions(overrideDefaults, apiDetailedOptionMap), }), context.detailedOptions, - { logger: false } + { logger: false }, ), - context.detailedOptions + context.detailedOptions, ); } @@ -57,7 +57,7 @@ async function getOptionsOrDie(context, filePath) { try { if (context.argv.config === false) { context.logger.debug( - "'--no-config' option found, skip loading config file." + "'--no-config' option found, skip loading config file.", ); return null; } @@ -65,7 +65,7 @@ async function getOptionsOrDie(context, filePath) { context.logger.debug( context.argv.config ? `load config file from '${context.argv.config}'` - : `resolve config from '${filePath}'` + : `resolve config from '${filePath}'`, ); const options = await resolveConfig(filePath, { @@ -77,7 +77,7 @@ async function getOptionsOrDie(context, filePath) { return options; } catch (error) { context.logger.error( - `Invalid configuration for file "${filePath}":\n` + error.message + `Invalid configuration for file "${filePath}":\n` + error.message, ); process.exit(2); } @@ -116,13 +116,13 @@ async function getOptionsForFile(context, filepath) { options && normalizeApiOptions(options, context.supportOptions, { logger: context.logger, - }) + }), ), }; context.logger.debug( `applied config-precedence (${context.argv.configPrecedence}): ` + - `${JSON.stringify(appliedOptions)}` + `${JSON.stringify(appliedOptions)}`, ); if (hasPlugins) { diff --git a/src/cli/options/minimist.js b/src/cli/options/minimist.js index 638b768bf..e4c6d98e4 100644 --- a/src/cli/options/minimist.js +++ b/src/cli/options/minimist.js @@ -15,13 +15,13 @@ export default function minimistParse(args, options) { const newDefaults = { ...defaults, ...Object.fromEntries( - booleanWithoutDefault.map((key) => [key, PLACEHOLDER]) + booleanWithoutDefault.map((key) => [key, PLACEHOLDER]), ), }; const parsed = minimist(args, { ...options, default: newDefaults }); return Object.fromEntries( - Object.entries(parsed).filter(([, value]) => value !== PLACEHOLDER) + Object.entries(parsed).filter(([, value]) => value !== PLACEHOLDER), ); } diff --git a/src/cli/options/normalize-cli-options.js b/src/cli/options/normalize-cli-options.js index 842fb2440..38371f0b3 100644 --- a/src/cli/options/normalize-cli-options.js +++ b/src/cli/options/normalize-cli-options.js @@ -34,7 +34,7 @@ class FlagSchema extends vnopts.ChoiceSchema { [ `Unknown flag ${chalk.yellow(utils.descriptor.value(value))},`, `did you mean ${chalk.blue(utils.descriptor.value(suggestion))}?`, - ].join(" ") + ].join(" "), ); return suggestion; } diff --git a/src/cli/options/parse-cli-arguments.js b/src/cli/options/parse-cli-arguments.js index 9a7cb1c86..fc15c7fb0 100644 --- a/src/cli/options/parse-cli-arguments.js +++ b/src/cli/options/parse-cli-arguments.js @@ -11,7 +11,7 @@ function parseArgv(rawArguments, detailedOptions, logger, keys) { if (keys) { detailedOptions = detailedOptions.filter((option) => - keys.includes(option.name) + keys.includes(option.name), ); argv = pick(argv, keys); } @@ -26,7 +26,7 @@ function parseArgv(rawArguments, detailedOptions, logger, keys) { // Otherwise use camel case for readability // `--ignore-unknown` -> `ignoreUnknown` return [option.forwardToApi || camelCase(key), value]; - }) + }), ), _: normalized._?.map(String), get __raw() { @@ -42,7 +42,7 @@ function parseArgvWithoutPlugins(rawArguments, logger, keys) { rawArguments, detailedOptionsWithoutPlugins, logger, - typeof keys === "string" ? [keys] : keys + typeof keys === "string" ? [keys] : keys, ); } diff --git a/src/cli/print-support-info.js b/src/cli/print-support-info.js index aa930aaa1..5f776c72f 100644 --- a/src/cli/print-support-info.js +++ b/src/cli/print-support-info.js @@ -10,7 +10,7 @@ async function printSupportInfo() { const supportInfo = { languages: sortByName(languages), options: sortByName(options).map((option) => - omit(option, ["cliName", "cliCategory", "cliDescription"]) + omit(option, ["cliName", "cliCategory", "cliDescription"]), ), }; diff --git a/src/cli/usage.js b/src/cli/usage.js index f3004ede6..d689db350 100644 --- a/src/cli/usage.js +++ b/src/cli/usage.js @@ -20,7 +20,7 @@ function createDefaultValueDisplay(value) { function getOptionDefaultValue(context, optionName) { // --no-option const option = context.detailedOptions.find( - ({ name }) => name === optionName + ({ name }) => name === optionName, ); if (option?.default !== undefined) { @@ -31,7 +31,7 @@ function getOptionDefaultValue(context, optionName) { return ( formatOptionsHiddenDefaults[optionCamelName] ?? context.supportOptions.find( - (option) => !option.deprecated && option.name === optionCamelName + (option) => !option.deprecated && option.name === optionCamelName, )?.default ); } @@ -75,8 +75,8 @@ function createChoiceUsages(choices, margin, indentation) { return activeChoices.map((choice) => indent( createOptionUsageRow(choice.value, choice.description, threshold), - indentation - ) + indentation, + ), ); } @@ -90,7 +90,7 @@ function createOptionUsage(context, option, threshold) { ? "" : `\nDefaults to ${createDefaultValueDisplay(optionDefaultValue)}.` }`, - threshold + threshold, ); } @@ -112,7 +112,7 @@ function getOptionsWithOpposites(options) { function createUsage(context) { const sortedOptions = context.detailedOptions.sort((optionA, optionB) => - optionA.name.localeCompare(optionB.name) + optionA.name.localeCompare(optionB.name), ); const options = getOptionsWithOpposites(sortedOptions).filter( @@ -122,14 +122,14 @@ function createUsage(context) { option.type === "boolean" && option.oppositeDescription && !option.name.startsWith("no-") - ) + ), ); const groupedOptions = groupBy(options, (option) => option.category); const firstCategories = categoryOrder.slice(0, -1); const lastCategories = categoryOrder.slice(-1); const restCategories = Object.keys(groupedOptions).filter( - (category) => !categoryOrder.includes(category) + (category) => !categoryOrder.includes(category), ); const allCategories = [ ...firstCategories, @@ -140,7 +140,7 @@ function createUsage(context) { const optionsUsage = allCategories.map((category) => { const categoryOptions = groupedOptions[category] .map((option) => - createOptionUsage(context, option, OPTION_USAGE_THRESHOLD) + createOptionUsage(context, option, OPTION_USAGE_THRESHOLD), ) .join("\n"); return `${category} options:\n\n${indent(categoryOptions, 2)}`; @@ -156,10 +156,10 @@ function createPluginDefaults(pluginDefaults) { const defaults = Object.entries(pluginDefaults) .sort(([pluginNameA], [pluginNameB]) => - pluginNameA.localeCompare(pluginNameB) + pluginNameA.localeCompare(pluginNameB), ) .map( - ([plugin, value]) => `* ${plugin}: ${createDefaultValueDisplay(value)}` + ([plugin, value]) => `* ${plugin}: ${createDefaultValueDisplay(value)}`, ) .join("\n"); @@ -168,7 +168,7 @@ function createPluginDefaults(pluginDefaults) { function createDetailedUsage(context, flag) { const option = getOptionsWithOpposites(context.detailedOptions).find( - (option) => option.name === flag || option.alias === flag + (option) => option.name === flag || option.alias === flag, ); const header = createOptionUsageHeader(option); @@ -180,7 +180,7 @@ function createDetailedUsage(context, flag) { : `\n\nValid options:\n\n${createChoiceUsages( option.choices, CHOICE_USAGE_MARGIN, - CHOICE_USAGE_INDENTATION + CHOICE_USAGE_INDENTATION, ).join("\n")}`; const optionDefaultValue = getOptionDefaultValue(context, option.name); diff --git a/src/common/ast-path.js b/src/common/ast-path.js index 41f379d1a..50b35942b 100644 --- a/src/common/ast-path.js +++ b/src/common/ast-path.js @@ -179,9 +179,12 @@ class AstPath { // the end of the iteration. map(callback, ...names) { const result = []; - this.each((path, index, value) => { - result[index] = callback(path, index, value); - }, ...names); + this.each( + (path, index, value) => { + result[index] = callback(path, index, value); + }, + ...names, + ); return result; } diff --git a/src/common/get-file-info.js b/src/common/get-file-info.js index faaed1ac8..344763ba2 100644 --- a/src/common/get-file-info.js +++ b/src/common/get-file-info.js @@ -19,7 +19,7 @@ import { isIgnored } from "../utils/ignore.js"; async function getFileInfo(filePath, options) { if (typeof filePath !== "string") { throw new TypeError( - `expect \`filePath\` to be a string, got \`${typeof filePath}\`` + `expect \`filePath\` to be a string, got \`${typeof filePath}\``, ); } diff --git a/src/common/parser-create-error.js b/src/common/parser-create-error.js index 1db7632a6..93810edfc 100644 --- a/src/common/parser-create-error.js +++ b/src/common/parser-create-error.js @@ -8,7 +8,7 @@ function createError(message, options) { options.loc.start.line + ":" + options.loc.start.column + - ")" + ")", ); return Object.assign(error, options); diff --git a/src/config/get-prettier-config-explorer.js b/src/config/get-prettier-config-explorer.js index 9ced373f6..e39379aee 100644 --- a/src/config/get-prettier-config-explorer.js +++ b/src/config/get-prettier-config-explorer.js @@ -64,7 +64,7 @@ async function transform(result) { if (typeof config !== "object") { throw new TypeError( "Config is only allowed to be an object, " + - `but received ${typeof config} in "${filepath}"` + `but received ${typeof config} in "${filepath}"`, ); } diff --git a/src/config/resolve-config.js b/src/config/resolve-config.js index 432cda959..0473e4a2f 100644 --- a/src/config/resolve-config.js +++ b/src/config/resolve-config.js @@ -53,7 +53,7 @@ async function resolveConfig(filePath, options) { merged.plugins = merged.plugins.map((value) => typeof value === "string" && value.startsWith(".") // relative path ? path.resolve(path.dirname(result.filepath), value) - : value + : value, ); } @@ -76,7 +76,7 @@ function mergeOverrides(configResult, filePath) { pathMatchesGlobs( relativeFilePath, override.files, - override.excludeFiles + override.excludeFiles, ) ) { Object.assign(options, override.options); @@ -93,7 +93,7 @@ function pathMatchesGlobs(filePath, patterns, excludedPatterns) { // micromatch always matches against basename when the option is enabled // use only patterns without slashes with it to match minimatch behavior const [withSlashes, withoutSlashes] = partition(patternList, (pattern) => - pattern.includes("/") + pattern.includes("/"), ); return ( diff --git a/src/document/invalid-doc-error.js b/src/document/invalid-doc-error.js index c60d84c0d..09ff9b699 100644 --- a/src/document/invalid-doc-error.js +++ b/src/document/invalid-doc-error.js @@ -22,7 +22,7 @@ function getDocErrorMessage(doc) { } const EXPECTED_TYPE_VALUES = disjunctionListFormat( - [...VALID_OBJECT_DOC_TYPES].map((type) => `'${type}'`) + [...VALID_OBJECT_DOC_TYPES].map((type) => `'${type}'`), ); return `Unexpected doc.type '${doc.type}'.\nExpected it to be ${EXPECTED_TYPE_VALUES}.`; diff --git a/src/document/printer.js b/src/document/printer.js index 18ced4491..c14e72415 100644 --- a/src/document/printer.js +++ b/src/document/printer.js @@ -199,7 +199,7 @@ function fits( width, hasLineSuffix, groupModeMap, - mustBeFlat + mustBeFlat, ) { if (width === Number.POSITIVE_INFINITY) { return true; @@ -473,7 +473,7 @@ function printDocToString(doc, options) { rem, lineSuffix.length > 0, groupModeMap, - true + true, ); if (parts.length === 1) { @@ -518,7 +518,7 @@ function printDocToString(doc, options) { rem, lineSuffix.length > 0, groupModeMap, - true + true, ); if (firstAndSecondContentFits) { @@ -638,7 +638,7 @@ function printDocToString(doc, options) { if (cursorPlaceholderIndex !== -1) { const otherCursorPlaceholderIndex = out.indexOf( CURSOR_PLACEHOLDER, - cursorPlaceholderIndex + 1 + cursorPlaceholderIndex + 1, ); const beforeCursor = out.slice(0, cursorPlaceholderIndex).join(""); const aroundCursor = out diff --git a/src/document/public.d.ts b/src/document/public.d.ts index 84aff5462..473980cec 100644 --- a/src/document/public.d.ts +++ b/src/document/public.d.ts @@ -137,7 +137,7 @@ export namespace builders { function ifBreak( ifBreak: Doc, noBreak?: Doc, - options?: { groupId?: symbol | undefined } + options?: { groupId?: symbol | undefined }, ): IfBreak; /** @see [indent](https://github.com/prettier/prettier/blob/main/commands.md#indent) */ @@ -146,7 +146,7 @@ export namespace builders { /** @see [indentIfBreak](https://github.com/prettier/prettier/blob/main/commands.md#indentifbreak) */ function indentIfBreak( doc: Doc, - opts: { groupId: symbol; negate?: boolean | undefined } + opts: { groupId: symbol; negate?: boolean | undefined }, ): IndentIfBreak; /** @see [join](https://github.com/prettier/prettier/blob/main/commands.md#join) */ @@ -186,7 +186,7 @@ export namespace builders { export namespace printer { function printDocToString( doc: builders.Doc, - options: Options + options: Options, ): { formatted: string; cursorNodeStart?: number | undefined; @@ -219,22 +219,22 @@ export namespace utils { doc: builders.Doc, onEnter?: (doc: builders.Doc) => void | boolean, onExit?: (doc: builders.Doc) => void, - shouldTraverseConditionalGroups?: boolean + shouldTraverseConditionalGroups?: boolean, ): void; function findInDoc( doc: builders.Doc, callback: (doc: builders.Doc) => T, - defaultValue: T + defaultValue: T, ): T; function mapDoc( doc: builders.Doc, - callback: (doc: builders.Doc) => T + callback: (doc: builders.Doc) => T, ): T; function removeLines(doc: builders.Doc): builders.Doc; function stripTrailingHardline(doc: builders.Doc): builders.Doc; function replaceEndOfLine( doc: builders.Doc, - replacement?: builders.Doc + replacement?: builders.Doc, ): builders.Doc; function canBreak(doc: builders.Doc): boolean; } diff --git a/src/document/utils.js b/src/document/utils.js index f53962fad..d9911d978 100644 --- a/src/document/utils.js +++ b/src/document/utils.js @@ -180,7 +180,7 @@ function propagateBreaks(doc) { doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn, - /* shouldTraverseConditionalGroups */ true + /* shouldTraverseConditionalGroups */ true, ); } @@ -408,7 +408,7 @@ function replaceEndOfLine(doc, replacement = literalline) { return mapDoc(doc, (currentDoc) => typeof currentDoc === "string" ? join(replacement, currentDoc.split("\n")) - : currentDoc + : currentDoc, ); } diff --git a/src/index.cjs b/src/index.cjs index 6f10aabec..ef5f11370 100644 --- a/src/index.cjs +++ b/src/index.cjs @@ -46,14 +46,14 @@ if (process.env.NODE_ENV === "production") { util: { get() { throw new Error( - "prettier.util is not available in development CommonJS version" + "prettier.util is not available in development CommonJS version", ); }, }, doc: { get() { throw new Error( - "prettier.doc is not available in development CommonJS version" + "prettier.doc is not available in development CommonJS version", ); }, }, diff --git a/src/index.d.ts b/src/index.d.ts index 88605cad3..0b0c989a8 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -72,12 +72,12 @@ type CallCallback = (path: AstPath, index: number, value: any) => U; type EachCallback = ( path: AstPath>, index: number, - value: any + value: any, ) => void; type MapCallback = ( path: AstPath>, index: number, - value: any + value: any, ) => U; // https://github.com/prettier/prettier/blob/next/src/common/ast-path.js @@ -136,18 +136,18 @@ export class AstPath { call(callback: CallCallback): U; call>( callback: CallCallback, U>, - prop1: P1 + prop1: P1, ): U; call>( callback: CallCallback, P2>, U>, prop1: P1, - prop2: P2 + prop2: P2, ): U; call< U, P1 extends keyof T, P2 extends CallProperties, - P3 extends CallProperties> + P3 extends CallProperties>, >( callback: CallCallback< IndexValue, P2>, P3>, @@ -155,14 +155,14 @@ export class AstPath { >, prop1: P1, prop2: P2, - prop3: P3 + prop3: P3, ): U; call< U, P1 extends keyof T, P2 extends CallProperties, P3 extends CallProperties>, - P4 extends CallProperties, P3>> + P4 extends CallProperties, P3>>, >( callback: CallCallback< IndexValue, P2>, P3>, P4>, @@ -171,7 +171,7 @@ export class AstPath { prop1: P1, prop2: P2, prop3: P3, - prop4: P4 + prop4: P4, ): U; call( callback: CallCallback, @@ -185,28 +185,28 @@ export class AstPath { each(callback: EachCallback): void; each>( callback: EachCallback>, - prop1: P1 + prop1: P1, ): void; each>( callback: EachCallback, P2>>, prop1: P1, - prop2: P2 - ): void; - each< - P1 extends keyof T, - P2 extends IterProperties, - P3 extends IterProperties> - >( - callback: EachCallback, P2>, P3>>, - prop1: P1, prop2: P2, - prop3: P3 ): void; each< P1 extends keyof T, P2 extends IterProperties, P3 extends IterProperties>, - P4 extends IterProperties, P3>> + >( + callback: EachCallback, P2>, P3>>, + prop1: P1, + prop2: P2, + prop3: P3, + ): void; + each< + P1 extends keyof T, + P2 extends IterProperties, + P3 extends IterProperties>, + P4 extends IterProperties, P3>>, >( callback: EachCallback< IndexValue, P2>, P3>, P4> @@ -214,7 +214,7 @@ export class AstPath { prop1: P1, prop2: P2, prop3: P3, - prop4: P4 + prop4: P4, ): void; each( callback: EachCallback, @@ -228,30 +228,30 @@ export class AstPath { map(callback: MapCallback): U[]; map>( callback: MapCallback, U>, - prop1: P1 + prop1: P1, ): U[]; map>( callback: MapCallback, P2>, U>, prop1: P1, - prop2: P2 - ): U[]; - map< - U, - P1 extends keyof T, - P2 extends IterProperties, - P3 extends IterProperties> - >( - callback: MapCallback, P2>, P3>, U>, - prop1: P1, prop2: P2, - prop3: P3 ): U[]; map< U, P1 extends keyof T, P2 extends IterProperties, P3 extends IterProperties>, - P4 extends IterProperties, P3>> + >( + callback: MapCallback, P2>, P3>, U>, + prop1: P1, + prop2: P2, + prop3: P3, + ): U[]; + map< + U, + P1 extends keyof T, + P2 extends IterProperties, + P3 extends IterProperties>, + P4 extends IterProperties, P3>>, >( callback: MapCallback< IndexValue, P2>, P3>, P4>, @@ -260,7 +260,7 @@ export class AstPath { prop1: P1, prop2: P2, prop3: P3, - prop4: P4 + prop4: P4, ): U[]; map( callback: MapCallback, @@ -304,7 +304,7 @@ export type BuiltInParsers = Record; export type CustomParser = ( text: string, - options: Options + options: Options, ) => AST | Promise; /** @@ -467,20 +467,20 @@ export interface Printer { path: AstPath, options: ParserOptions, print: (path: AstPath) => Doc, - args?: unknown + args?: unknown, ): Doc; embed?: | (( path: AstPath, - options: Options + options: Options, ) => | (( textToDoc: (text: string, options: Options) => Promise, print: ( - selector?: string | number | Array | AstPath + selector?: string | number | Array | AstPath, ) => Doc, path: AstPath, - options: Options + options: Options, ) => Promise | Doc | undefined) | Doc | null) @@ -517,7 +517,7 @@ export interface Printer { text: string, options: ParserOptions, ast: T, - isLastComment: boolean + isLastComment: boolean, ) => boolean) | undefined; endOfLine?: @@ -526,7 +526,7 @@ export interface Printer { text: string, options: ParserOptions, ast: T, - isLastComment: boolean + isLastComment: boolean, ) => boolean) | undefined; remaining?: @@ -535,7 +535,7 @@ export interface Printer { text: string, options: ParserOptions, ast: T, - isLastComment: boolean + isLastComment: boolean, ) => boolean) | undefined; } @@ -575,7 +575,7 @@ export function check(source: string, options?: Options): Promise; */ export function formatWithCursor( source: string, - options: CursorOptions + options: CursorOptions, ): Promise; export function formatAST(ast: any, options?: Options): Promise; @@ -616,7 +616,7 @@ export interface ResolveConfigOptions { */ export function resolveConfig( filePath: string, - options?: ResolveConfigOptions + options?: ResolveConfigOptions, ): Promise; /** @@ -792,7 +792,7 @@ export interface FileInfoResult { export function getFileInfo( filePath: string, - options?: FileInfoOptions + options?: FileInfoOptions, ): Promise; /** @@ -820,7 +820,7 @@ export namespace util { function getAlignmentSize( text: string, tabWidth: number, - startIndex?: number | undefined + startIndex?: number | undefined, ): number; function getIndentSize(value: string, tabWidth: number): number; @@ -828,83 +828,83 @@ export namespace util { function skipNewline( text: string, startIndex: number | false, - options?: SkipOptions | undefined + options?: SkipOptions | undefined, ): number | false; function skipInlineComment( text: string, - startIndex: number | false + startIndex: number | false, ): number | false; function skipTrailingComment( text: string, - startIndex: number | false + startIndex: number | false, ): number | false; function skipTrailingComment( text: string, - startIndex: number | false + startIndex: number | false, ): number | false; function hasNewline( text: string, startIndex: number, - options?: SkipOptions | undefined + options?: SkipOptions | undefined, ): boolean; function hasNewlineInRange( text: string, startIndex: number, - endIndex: number + endIndex: number, ): boolean; function hasSpaces( text: string, startIndex: number, - options?: SkipOptions | undefined + options?: SkipOptions | undefined, ): boolean; function getNextNonSpaceNonCommentCharacter( text: string, - startIndex: number + startIndex: number, ): string; function makeString( rawText: string, enclosingQuote: Quote, - unescapeUnnecessaryEscapes?: boolean | undefined + unescapeUnnecessaryEscapes?: boolean | undefined, ): string; function skip( - characters: string | RegExp + characters: string | RegExp, ): ( text: string, startIndex: number | false, - options?: SkipOptions + options?: SkipOptions, ) => number | false; const skipWhitespace: ( text: string, startIndex: number | false, - options?: SkipOptions + options?: SkipOptions, ) => number | false; const skipSpaces: ( text: string, startIndex: number | false, - options?: SkipOptions + options?: SkipOptions, ) => number | false; const skipToLineEnd: ( text: string, startIndex: number | false, - options?: SkipOptions + options?: SkipOptions, ) => number | false; const skipEverythingButNewLine: ( text: string, startIndex: number | false, - options?: SkipOptions + options?: SkipOptions, ) => number | false; function addLeadingComment(node: any, comment: any): void; diff --git a/src/index.js b/src/index.js index 42e7809b3..65c1ed348 100644 --- a/src/index.js +++ b/src/index.js @@ -33,7 +33,7 @@ import omit from "./utils/object-omit.js"; */ function withPlugins( fn, - optionsArgumentIndex = 1 // Usually `options` is the 2nd argument + optionsArgumentIndex = 1, // Usually `options` is the 2nd argument ) { return async (...args) => { const options = args[optionsArgumentIndex] ?? {}; diff --git a/src/language-css/clean.js b/src/language-css/clean.js index 314c76766..a6da441ca 100644 --- a/src/language-css/clean.js +++ b/src/language-css/clean.js @@ -74,7 +74,7 @@ function clean(ast, newObj, parent) { (ast.type === "value-word" && ((ast.isColor && ast.isHex) || ["initial", "inherit", "unset", "revert"].includes( - newObj.value.toLowerCase() + newObj.value.toLowerCase(), ))) || ast.type === "media-feature" || ast.type === "selector-root-invalid" || @@ -144,7 +144,7 @@ function clean(ast, newObj, parent) { (match, numStr, unit) => { const num = Number(numStr); return Number.isNaN(num) ? match : num + unit.toLowerCase(); - } + }, ); } @@ -169,7 +169,7 @@ function clean(ast, newObj, parent) { // Workaround for SCSS arbitrary arguments if (ast.type === "value-comma_group") { const index = ast.groups.findIndex( - (node) => node.type === "value-number" && node.unit === "..." + (node) => node.type === "value-number" && node.unit === "...", ); if (index !== -1) { @@ -189,7 +189,7 @@ function clean(ast, newObj, parent) { ast.groups.some( (node) => (node.type === "value-atword" && node.value.endsWith("[")) || - (node.type === "value-word" && node.value.startsWith("]")) + (node.type === "value-word" && node.value.startsWith("]")), ) ) { return { diff --git a/src/language-css/loc.js b/src/language-css/loc.js index aeb823137..31e1a7ddb 100644 --- a/src/language-css/loc.js +++ b/src/language-css/loc.js @@ -62,7 +62,7 @@ function calculateLoc(node, text) { calculateValueNodeLoc( child, getValueRootOffset(node), - child.text || child.value + child.text || child.value, ); } else { calculateLoc(child, text); diff --git a/src/language-css/parse/parse-value.js b/src/language-css/parse/parse-value.js index df66908be..f1238e1af 100644 --- a/src/language-css/parse/parse-value.js +++ b/src/language-css/parse/parse-value.js @@ -44,8 +44,8 @@ function parseValueNode(valueNode, options) { parseSelector( getValueRoot(valueNode).text.slice( node.group.open.sourceIndex + 1, - node.group.close.sourceIndex - ) + node.group.close.sourceIndex, + ), ), ]; } diff --git a/src/language-css/parser-postcss.js b/src/language-css/parser-postcss.js index 94ad90b71..16f81dd64 100644 --- a/src/language-css/parser-postcss.js +++ b/src/language-css/parser-postcss.js @@ -47,13 +47,13 @@ function parseNestedCSS(node, options) { if (node.value.trimEnd().endsWith("}")) { const textBefore = options.originalText.slice( 0, - node.source.start.offset + node.source.start.offset, ); const nodeText = "a".repeat(node.prop.length) + options.originalText.slice( node.source.start.offset + node.prop.length, - node.source.end.offset + 1 + node.source.end.offset + 1, ); const fakeContent = textBefore.replaceAll(/[^\n]/g, " ") + nodeText; let parse; @@ -234,7 +234,7 @@ function parseNestedCSS(node, options) { const customSelector = node.params.match(/:--\S+\s+/)[0].trim(); node.customSelector = customSelector; node.selector = parseSelector( - node.params.slice(customSelector.length).trim() + node.params.slice(customSelector.length).trim(), ); delete node.params; return node; @@ -421,7 +421,7 @@ function parseLess(text, options = {}) { // See comments for `replaceQuotesInInlineComments` in `loc.js`. (text) => postcssLess.parse(replaceQuotesInInlineComments(text)), text, - options + options, ); } diff --git a/src/language-css/print/comma-separated-value-group.js b/src/language-css/print/comma-separated-value-group.js index 1206aeab6..476876bb1 100644 --- a/src/language-css/print/comma-separated-value-group.js +++ b/src/language-css/print/comma-separated-value-group.js @@ -49,13 +49,13 @@ function printCommaSeparatedValueGroup(path, options, print) { (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template")); const atRuleAncestorNode = path.findAncestor( - (node) => node.type === "css-atrule" + (node) => node.type === "css-atrule", ); const isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode(atRuleAncestorNode, options); const hasInlineComment = node.groups.some((node) => - isInlineValueCommentNode(node) + isInlineValueCommentNode(node), ); const printed = path.map(print, "groups"); diff --git a/src/language-css/print/misc.js b/src/language-css/print/misc.js index 5bb542feb..9a91c6ec8 100644 --- a/src/language-css/print/misc.js +++ b/src/language-css/print/misc.js @@ -18,7 +18,7 @@ const ADJUST_NUMBERS_REGEX = new RegExp( `(${WORD_PART_REGEX.source})?` + `(${NUMBER_REGEX.source})` + `(${STANDARD_UNIT_REGEX.source})?`, - "g" + "g", ); function adjustStrings(value, options) { @@ -38,7 +38,7 @@ function adjustNumbers(value) { (match, quote, wordPart, number, unit) => !wordPart && number ? printCssNumber(number) + maybeToLowerCase(unit || "") - : match + : match, ); } diff --git a/src/language-css/print/parenthesized-value-group.js b/src/language-css/print/parenthesized-value-group.js index f101ac9c8..0280d0c2e 100644 --- a/src/language-css/print/parenthesized-value-group.js +++ b/src/language-css/print/parenthesized-value-group.js @@ -29,7 +29,7 @@ function hasComma({ node, parent }, options) { options.originalText .slice(locStart(node), locStart(parent.close)) .trimEnd() - .endsWith(",") + .endsWith(","), ); } @@ -53,7 +53,7 @@ function printParenthesizedValueGroup(path, options, print) { const { node, parent } = path; const groupDocs = path.map( ({ node }) => (typeof node === "string" ? node : print()), - "groups" + "groups", ); if ( @@ -131,7 +131,7 @@ function printParenthesizedValueGroup(path, options, print) { ], { shouldBreak, - } + }, ); return shouldDedent ? dedent(doc) : doc; @@ -148,7 +148,7 @@ function shouldBreakList(path) { (node, key) => key === "value" && ((node.type === "css-decl" && !node.prop.startsWith("--")) || - (node.type === "css-atrule" && node.variable)) + (node.type === "css-atrule" && node.variable)), ); } diff --git a/src/language-css/printer-postcss.js b/src/language-css/printer-postcss.js index 84abf9fa1..472b60609 100644 --- a/src/language-css/printer-postcss.js +++ b/src/language-css/printer-postcss.js @@ -315,7 +315,7 @@ function genericPrint(path, options, print) { case "media-feature": return maybeToLowerCase( - adjustStrings(node.value.replaceAll(/ +/g, " "), options) + adjustStrings(node.value.replaceAll(/ +/g, " "), options), ); case "media-colon": @@ -330,7 +330,7 @@ function genericPrint(path, options, print) { case "media-url": return adjustStrings( node.value.replaceAll(/^url\(\s+/gi, "url(").replaceAll(/\s+\)$/g, ")"), - options + options, ); case "media-unknown": @@ -353,7 +353,7 @@ function genericPrint(path, options, print) { ? line : hardline, ], - path.map(print, "nodes") + path.map(print, "nodes"), ), ]); @@ -376,7 +376,7 @@ function genericPrint(path, options, print) { : adjustNumbers( isKeyframeAtRuleKeywords(path, node.value) ? node.value.toLowerCase() - : node.value + : node.value, ), ]; @@ -397,7 +397,7 @@ function genericPrint(path, options, print) { node.value ? quoteAttributeValue( adjustStrings(node.value.trim(), options), - options + options, ) : "", node.insensitive ? " i" : "", @@ -453,13 +453,13 @@ function genericPrint(path, options, print) { case "selector-unknown": { const ruleAncestorNode = path.findAncestor( - (node) => node.type === "css-rule" + (node) => node.type === "css-rule", ); // Nested SCSS property if (ruleAncestorNode?.isSCSSNesterProperty) { return adjustNumbers( - adjustStrings(maybeToLowerCase(node.value), options) + adjustStrings(maybeToLowerCase(node.value), options), ); } @@ -544,7 +544,7 @@ function genericPrint(path, options, print) { case "value-string": return printString( node.raws.quote + node.value + node.raws.quote, - options + options, ); case "value-atword": diff --git a/src/language-css/utils/has-string-or-function.js b/src/language-css/utils/has-string-or-function.js index d0ff332ad..96816fe49 100644 --- a/src/language-css/utils/has-string-or-function.js +++ b/src/language-css/utils/has-string-or-function.js @@ -4,7 +4,7 @@ function hasStringOrFunction(groupList) { group.type === "string" || (group.type === "func" && // workaround false-positive func - !group.value.endsWith("\\")) + !group.value.endsWith("\\")), ); } diff --git a/src/language-css/utils/index.js b/src/language-css/utils/index.js index 4514e4da8..9ce647333 100644 --- a/src/language-css/utils/index.js +++ b/src/language-css/utils/index.js @@ -39,7 +39,7 @@ function isWideKeywords(value) { function isKeyframeAtRuleKeywords(path, value) { const atRuleAncestorNode = path.findAncestor( - (node) => node.type === "css-atrule" + (node) => node.type === "css-atrule", ); return ( atRuleAncestorNode?.name?.toLowerCase().endsWith("keyframes") && @@ -61,14 +61,14 @@ function maybeToLowerCase(value) { function insideValueFunctionNode(path, functionName) { const funcAncestorNode = path.findAncestor( - (node) => node.type === "value-func" + (node) => node.type === "value-func", ); return funcAncestorNode?.value?.toLowerCase() === functionName; } function insideICSSRuleNode(path) { const ruleAncestorNode = path.findAncestor( - (node) => node.type === "css-rule" + (node) => node.type === "css-rule", ); const selector = ruleAncestorNode?.raws?.selector; @@ -83,7 +83,7 @@ function insideAtRuleNode(path, atRuleNameOrAtRuleNames) { ? atRuleNameOrAtRuleNames : [atRuleNameOrAtRuleNames]; const atRuleAncestorNode = path.findAncestor( - (node) => node.type === "css-atrule" + (node) => node.type === "css-atrule", ); return ( diff --git a/src/language-css/utils/is-scss-variable.js b/src/language-css/utils/is-scss-variable.js index e077e0cd1..f4eee2250 100644 --- a/src/language-css/utils/is-scss-variable.js +++ b/src/language-css/utils/is-scss-variable.js @@ -2,7 +2,7 @@ function isSCSSVariable(node, options) { return Boolean( options.parser === "scss" && node?.type === "word" && - node.value.startsWith("$") + node.value.startsWith("$"), ); } diff --git a/src/language-graphql/printer-graphql.js b/src/language-graphql/printer-graphql.js index a92ecb73d..0c3cc013c 100644 --- a/src/language-graphql/printer-graphql.js +++ b/src/language-graphql/printer-graphql.js @@ -74,7 +74,7 @@ function genericPrint(path, options, print) { softline, join( [ifBreak("", ", "), softline], - printSequence(path, options, print, "arguments") + printSequence(path, options, print, "arguments"), ), ]), softline, @@ -164,7 +164,7 @@ function genericPrint(path, options, print) { softline, join( [ifBreak("", ", "), softline], - printSequence(path, options, print, "arguments") + printSequence(path, options, print, "arguments"), ), ]), softline, @@ -241,7 +241,7 @@ function genericPrint(path, options, print) { softline, join( [ifBreak("", ", "), softline], - printSequence(path, options, print, "arguments") + printSequence(path, options, print, "arguments"), ), ]), softline, @@ -266,7 +266,7 @@ function genericPrint(path, options, print) { softline, join( [ifBreak("", ", "), softline], - printSequence(path, options, print, "arguments") + printSequence(path, options, print, "arguments"), ), ]), softline, @@ -327,7 +327,7 @@ function genericPrint(path, options, print) { hardline, join( hardline, - printSequence(path, options, print, "operationTypes") + printSequence(path, options, print, "operationTypes"), ), ]), hardline, @@ -347,7 +347,7 @@ function genericPrint(path, options, print) { hardline, join( hardline, - printSequence(path, options, print, "operationTypes") + printSequence(path, options, print, "operationTypes"), ), ]) : "", @@ -470,7 +470,7 @@ function printInterfaces(path, options, print) { if (nextInterfaceNode) { const textBetween = options.originalText.slice( interfaceNode.loc.end, - nextInterfaceNode.loc.start + nextInterfaceNode.loc.start, ); const hasComment = textBetween.includes("#"); @@ -492,7 +492,7 @@ function printVariableDefinitions(path, print) { softline, join( [ifBreak("", ", "), softline], - path.map(print, "variableDefinitions") + path.map(print, "variableDefinitions"), ), ]), softline, @@ -512,7 +512,7 @@ clean.ignoredProperties = new Set(["loc", "comments"]); function hasPrettierIgnore(path) { const { node } = path; return node?.comments?.some( - (comment) => comment.value.trim() === "prettier-ignore" + (comment) => comment.value.trim() === "prettier-ignore", ); } diff --git a/src/language-handlebars/parser-glimmer.js b/src/language-handlebars/parser-glimmer.js index 2a776dbeb..d3b0ce73c 100644 --- a/src/language-handlebars/parser-glimmer.js +++ b/src/language-handlebars/parser-glimmer.js @@ -22,7 +22,7 @@ function addBackslash(node) { ) { childrenOrBody[i].chars = childrenOrBody[i].chars.replace( /\\$/, - "\\\\" + "\\\\", ); } } @@ -115,7 +115,7 @@ function getErrorMessage(error) { lines.length >= 4 && /:\s?$/.test(lines[0]) && /^\(error occurred in '.*?' @ line \d+ : column \d+\)$/.test( - lines.at(-1) + lines.at(-1), ) && lines[1] === "" && lines.at(-2) === "" && diff --git a/src/language-handlebars/printer-glimmer.js b/src/language-handlebars/printer-glimmer.js index 6d6a7eab3..1b317fd4f 100644 --- a/src/language-handlebars/printer-glimmer.js +++ b/src/language-handlebars/printer-glimmer.js @@ -131,7 +131,7 @@ function print(path, options, print) { value.parts .map((part) => (part.type === "TextNode" ? part.chars : "")) .join(""), - options.singleQuote + options.singleQuote, ) : ""; @@ -283,7 +283,7 @@ function print(path, options, print) { if (isWhitespaceOnly && lineBreaksCount) { leadingLineBreaksCount = Math.min( lineBreaksCount, - NEWLINES_TO_PRESERVE_MAX + NEWLINES_TO_PRESERVE_MAX, ); trailingLineBreaksCount = 0; } else { @@ -402,7 +402,7 @@ function printStartingTag(path, print) { const { node } = path; const types = ["attributes", "modifiers", "comments"].filter((property) => - isNonEmptyArray(node[property]) + isNonEmptyArray(node[property]), ); const attributes = types.flatMap((type) => node[type]).sort(sortByLoc); @@ -694,7 +694,7 @@ function printStringLiteral(path, options) { const quote = getPreferredQuote( value, - needsOppositeQuote(path) ? !options.singleQuote : options.singleQuote + needsOppositeQuote(path) ? !options.singleQuote : options.singleQuote, ); return [quote, value.replaceAll(quote, `\\${quote}`), quote]; diff --git a/src/language-html/ast.js b/src/language-html/ast.js index 73992e218..ca9814174 100644 --- a/src/language-html/ast.js +++ b/src/language-html/ast.js @@ -99,7 +99,7 @@ class Node { // @ts-expect-error this.children.indexOf(target), 0, - this.createChild(node) + this.createChild(node), ); } @@ -158,7 +158,7 @@ class Node { get attrMap() { return Object.fromEntries( // @ts-expect-error - this.attrs.map((attr) => [attr.fullName, attr.value]) + this.attrs.map((attr) => [attr.fullName, attr.value]), ); } } diff --git a/src/language-html/conditional-comment.js b/src/language-html/conditional-comment.js index 9cc8ce44b..ea21f27c8 100644 --- a/src/language-html/conditional-comment.js +++ b/src/language-html/conditional-comment.js @@ -57,7 +57,7 @@ function parseIeConditionalStartEndComment(node, parseHtml, match) { sourceSpan: node.sourceSpan, startSourceSpan: new ParseSourceSpan( node.sourceSpan.start, - contentStartSpan + contentStartSpan, ), endSourceSpan: new ParseSourceSpan(contentEndSpan, node.sourceSpan.end), }; diff --git a/src/language-html/constants.evaluate.js b/src/language-html/constants.evaluate.js index 78b41ab3e..204d979b5 100644 --- a/src/language-html/constants.evaluate.js +++ b/src/language-html/constants.evaluate.js @@ -9,8 +9,8 @@ const getCssStyleTags = (property) => .split(",") .map((selector) => selector.trim()) .filter((selector) => /^[\dA-Za-z]+$/.test(selector)) - .map((tagName) => [tagName, htmlStyle.style[property]]) - ) + .map((tagName) => [tagName, htmlStyle.style[property]]), + ), ); const CSS_DISPLAY_TAGS = { diff --git a/src/language-html/embed.js b/src/language-html/embed.js index 067ae260d..e06426e8a 100644 --- a/src/language-html/embed.js +++ b/src/language-html/embed.js @@ -111,7 +111,7 @@ function embed(path, options) { } else if (options.parser === "vue") { textToDocOptions.parser = isVueSfcWithTypescriptScript( path, - options + options, ) ? "__vue_ts_expression" : "__vue_expression"; diff --git a/src/language-html/embed/angular-attributes.js b/src/language-html/embed/angular-attributes.js index 8262c25ed..b0de65bc3 100644 --- a/src/language-html/embed/angular-attributes.js +++ b/src/language-html/embed/angular-attributes.js @@ -23,7 +23,7 @@ function createAngularPrinter({ parser }) { // angular does not allow trailing comma trailingComma: "none", }, - shouldHugJsExpression + shouldHugJsExpression, ); } @@ -82,7 +82,7 @@ function printAngularAttribute(path, options) { return () => printExpand( fill(getTextValueParts(node, value.trim())), - !value.includes("@@") + !value.includes("@@"), ); } diff --git a/src/language-html/embed/angular-interpolation.js b/src/language-html/embed/angular-interpolation.js index 29f930792..53caceeb8 100644 --- a/src/language-html/embed/angular-interpolation.js +++ b/src/language-html/embed/angular-interpolation.js @@ -24,7 +24,7 @@ async function printAngularInterpolation(text, textToDoc) { ]), line, "}}", - ]) + ]), ); } catch { parts.push("{{", replaceEndOfLine(part), "}}"); diff --git a/src/language-html/embed/attribute.js b/src/language-html/embed/attribute.js index 1200a7eca..18f72512b 100644 --- a/src/language-html/embed/attribute.js +++ b/src/language-html/embed/attribute.js @@ -23,8 +23,8 @@ function printAttribute(path, options) { /^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test( options.originalText.slice( node.valueSpan.start.offset, - node.valueSpan.end.offset - ) + node.valueSpan.end.offset, + ), ) || // lwc: html`` (options.parser === "lwc" && node.value.startsWith("{") && @@ -60,7 +60,7 @@ function printAttributeWithValuePrinter(printValue) { } valueDoc = mapDoc(valueDoc, (doc) => - typeof doc === "string" ? doc.replaceAll('"', """) : doc + typeof doc === "string" ? doc.replaceAll('"', """) : doc, ); return [path.node.rawName, '="', group(valueDoc), '"']; diff --git a/src/language-html/embed/srcset.js b/src/language-html/embed/srcset.js index 31c1ac69d..bf30adef5 100644 --- a/src/language-html/embed/srcset.js +++ b/src/language-html/embed/srcset.js @@ -30,7 +30,7 @@ function printSrcsetValue(value) { const maxUrlLength = Math.max(...urls.map((url) => url.length)); const descriptors = srcset.map((src) => - src[key] ? String(src[key].value) : "" + src[key] ? String(src[key].value) : "", ); const descriptorLeftLengths = descriptors.map((descriptor) => { const index = descriptor.indexOf("."); @@ -55,8 +55,8 @@ function printSrcsetValue(value) { } return parts; - }) - ) + }), + ), ); } diff --git a/src/language-html/embed/style.js b/src/language-html/embed/style.js index 4e6ac7a90..544a9ea0d 100644 --- a/src/language-html/embed/style.js +++ b/src/language-html/embed/style.js @@ -11,7 +11,7 @@ function printStyleAttribute(path, options) { ) { return async (textToDoc) => printExpand( - await textToDoc(text, { parser: "css", __isHTMLStyleAttribute: true }) + await textToDoc(text, { parser: "css", __isHTMLStyleAttribute: true }), ); } } diff --git a/src/language-html/embed/utils.js b/src/language-html/embed/utils.js index 1c1853cce..1c51e85c3 100644 --- a/src/language-html/embed/utils.js +++ b/src/language-html/embed/utils.js @@ -41,7 +41,7 @@ async function formatAttributeValue( code, textToDoc, options, - shouldHugJsExpression + shouldHugJsExpression, ) { options = { // strictly prefer single quote to avoid unnecessary html entity escape diff --git a/src/language-html/embed/vue-attributes.js b/src/language-html/embed/vue-attributes.js index a754edb55..47bc0125f 100644 --- a/src/language-html/embed/vue-attributes.js +++ b/src/language-html/embed/vue-attributes.js @@ -74,7 +74,7 @@ function printVueVOnDirective(text, textToDoc, { parseWithTs }) { text, textToDoc, { parser: parseWithTs ? "__vue_ts_event_binding" : "__vue_event_binding" }, - shouldHugJsExpression + shouldHugJsExpression, ); } @@ -86,7 +86,7 @@ function printVueVBindDirective(text, textToDoc, { parseWithTs }) { text, textToDoc, { parser: parseWithTs ? "__vue_ts_expression" : "__vue_expression" }, - shouldHugJsExpression + shouldHugJsExpression, ); } @@ -98,7 +98,7 @@ function printExpression(text, textToDoc, { parseWithTs }) { text, textToDoc, { parser: parseWithTs ? "__ts_expression" : "__js_expression" }, - shouldHugJsExpression + shouldHugJsExpression, ); } diff --git a/src/language-html/embed/vue-v-for-directive.js b/src/language-html/embed/vue-v-for-directive.js index 0f9999b68..1e1eaa38b 100644 --- a/src/language-html/embed/vue-v-for-directive.js +++ b/src/language-html/embed/vue-v-for-directive.js @@ -25,7 +25,7 @@ async function printVueVForDirective(textToDoc, print, path, options) { await formatAttributeValue(`function _(${left}) {}`, textToDoc, { parser: parseWithTs ? "babel-ts" : "babel", __isVueForBindingLeft: true, - }) + }), ), " ", operator, @@ -69,7 +69,7 @@ function parseVueVForDirective(value) { if ( left.some( (part, index) => - !part && (index === 0 || left.slice(index + 1).some(Boolean)) + !part && (index === 0 || left.slice(index + 1).some(Boolean)), ) ) { return; diff --git a/src/language-html/parser-html.js b/src/language-html/parser-html.js index 27bc1f1f6..e0ccf8649 100644 --- a/src/language-html/parser-html.js +++ b/src/language-html/parser-html.js @@ -68,7 +68,7 @@ function ngHtmlParser(input, parseOptions, options) { const isHtml = rootNodes.some( (node) => (node.type === "docType" && node.value === "html") || - (node.type === "element" && node.name.toLowerCase() === "html") + (node.type === "element" && node.name.toLowerCase() === "html"), ); // If not Vue SFC, treat as html @@ -89,7 +89,7 @@ function ngHtmlParser(input, parseOptions, options) { getHtmlParseResult().rootNodes.find( ({ startSourceSpan }) => startSourceSpan && - startSourceSpan.start.offset === node.startSourceSpan.start.offset + startSourceSpan.start.offset === node.startSourceSpan.start.offset, ) ?? node; for (const [index, node] of rootNodes.entries()) { const { endSourceSpan, startSourceSpan } = node; @@ -101,7 +101,7 @@ function ngHtmlParser(input, parseOptions, options) { const error = getHtmlParseResult().errors.find( (error) => error.span.start.offset > startSourceSpan.start.offset && - error.span.start.offset < endSourceSpan.end.offset + error.span.start.offset < endSourceSpan.end.offset, ); if (error) { throwParseError(error); @@ -178,7 +178,7 @@ function ngHtmlParser(input, parseOptions, options) { isUnknownNamespace(node)) ) { node.name = lowerCaseIfFn(node.name, (lowerCasedName) => - HTML_TAGS.has(lowerCasedName) + HTML_TAGS.has(lowerCasedName), ); } @@ -191,8 +191,8 @@ function ngHtmlParser(input, parseOptions, options) { HTML_ELEMENT_ATTRIBUTES.has(node.name) && (HTML_ELEMENT_ATTRIBUTES.get("*").has(lowerCasedAttrName) || HTML_ELEMENT_ATTRIBUTES.get(node.name).has( - lowerCasedAttrName - )) + lowerCasedAttrName, + )), ); } } @@ -204,7 +204,7 @@ function ngHtmlParser(input, parseOptions, options) { if (node.sourceSpan && node.endSourceSpan) { node.sourceSpan = new ParseSourceSpan( node.sourceSpan.start, - node.endSourceSpan.end + node.endSourceSpan.end, ); } }; @@ -215,7 +215,7 @@ function ngHtmlParser(input, parseOptions, options) { const addTagDefinition = (node) => { if (node.type === "element") { const tagDefinition = getHtmlTagDefinition( - isTagNameCaseSensitive ? node.name : node.name.toLowerCase() + isTagNameCaseSensitive ? node.name : node.name.toLowerCase(), ); if ( !node.namespace || @@ -238,7 +238,7 @@ function ngHtmlParser(input, parseOptions, options) { fixSourceSpan(node); } })(), - rootNodes + rootNodes, ); return rootNodes; @@ -276,7 +276,7 @@ function parse( text, parseOptions, options = {}, - shouldParseFrontMatter = true + shouldParseFrontMatter = true, ) { const { frontMatter, content } = shouldParseFrontMatter ? parseFrontMatter(text) @@ -309,13 +309,13 @@ function parse( fakeContent + realContent, parseOptions, options, - false + false, ); // @ts-expect-error subAst.sourceSpan = new ParseSourceSpan( startSpan, // @ts-expect-error - subAst.children.at(-1).sourceSpan.end + subAst.children.at(-1).sourceSpan.end, ); // @ts-expect-error const firstText = subAst.children[0]; @@ -325,7 +325,7 @@ function parse( } else { firstText.sourceSpan = new ParseSourceSpan( firstText.sourceSpan.start.moveBy(offset), - firstText.sourceSpan.end + firstText.sourceSpan.end, ); firstText.value = firstText.value.slice(offset); } @@ -336,7 +336,7 @@ function parse( if (node.type === "comment") { const ieConditionalComment = parseIeConditionalComment( node, - parseSubHtml + parseSubHtml, ); if (ieConditionalComment) { node.parent.replaceChild(node, ieConditionalComment); @@ -386,7 +386,7 @@ export const vue = createParser({ name === "lang" && value !== "html" && value !== "" && - value !== undefined + value !== undefined, )) ); }, diff --git a/src/language-html/print-preprocess.js b/src/language-html/print-preprocess.js index b16f869a5..e19ce6c71 100644 --- a/src/language-html/print-preprocess.js +++ b/src/language-html/print-preprocess.js @@ -51,7 +51,7 @@ function removeIgnorableFirstLf(ast /*, options */) { } function mergeIfConditionalStartEndCommentIntoElementOpeningTag( - ast /*, options */ + ast /*, options */, ) { /** * @@ -79,11 +79,11 @@ function mergeIfConditionalStartEndCommentIntoElementOpeningTag( const startSourceSpan = new ParseSourceSpan( ieConditionalStartComment.sourceSpan.start, - ieConditionalEndComment.sourceSpan.end + ieConditionalEndComment.sourceSpan.end, ); const sourceSpan = new ParseSourceSpan( startSourceSpan.start, - child.sourceSpan.end + child.sourceSpan.end, ); child.condition = ieConditionalStartComment.condition; @@ -118,7 +118,7 @@ function mergeNodeIntoText(ast, shouldMerge, getValue) { prevChild.value += child.value; prevChild.sourceSpan = new ParseSourceSpan( prevChild.sourceSpan.start, - child.sourceSpan.end + child.sourceSpan.end, ); node.removeChild(child); @@ -132,7 +132,7 @@ function mergeCdataIntoText(ast /*, options */) { return mergeNodeIntoText( ast, (node) => node.type === "cdata", - (node) => `` + (node) => ``, ); } @@ -168,7 +168,7 @@ function mergeSimpleElementIntoText(ast /*, options */) { nextChild.value; prevChild.sourceSpan = new ParseSourceSpan( prevChild.sourceSpan.start, - nextChild.sourceSpan.end + nextChild.sourceSpan.end, ); prevChild.isTrailingSpaceSensitive = nextChild.isTrailingSpaceSensitive; prevChild.hasTrailingSpaces = nextChild.hasTrailingSpaces; @@ -232,7 +232,7 @@ function extractInterpolation(ast, options) { value, sourceSpan: new ParseSourceSpan( startSourceSpan.moveBy(2), - endSourceSpan.moveBy(-2) + endSourceSpan.moveBy(-2), ), }, ], @@ -300,7 +300,7 @@ function extractWhitespaces(ast /*, options*/) { child.value = text; child.sourceSpan = new ParseSourceSpan( child.sourceSpan.start.moveBy(leadingWhitespace.length), - child.sourceSpan.end.moveBy(-trailingWhitespace.length) + child.sourceSpan.end.moveBy(-trailingWhitespace.length), ); if (leadingWhitespace) { @@ -348,8 +348,8 @@ function addHasHtmComponentClosingTag(ast, options) { /^<\s*\/\s*\/\s*>$/.test( options.originalText.slice( node.endSourceSpan.start.offset, - node.endSourceSpan.end.offset - ) + node.endSourceSpan.end.offset, + ), ); }); } @@ -378,11 +378,11 @@ function addIsSpaceSensitive(ast, options) { for (const child of children) { child.isLeadingSpaceSensitive = isLeadingSpaceSensitiveNode( child, - options + options, ); child.isTrailingSpaceSensitive = isTrailingSpaceSensitiveNode( child, - options + options, ); } for (let index = 0; index < children.length; index++) { diff --git a/src/language-html/print/children.js b/src/language-html/print/children.js index 6da03f347..dd31bed87 100644 --- a/src/language-html/print/children.js +++ b/src/language-html/print/children.js @@ -40,8 +40,8 @@ function printChild(childPath, options, print) { locEnd(child) - (child.next && needsToBorrowPrevClosingTagEndMarker(child.next) ? printClosingTagEndMarker(child, options).length - : 0) - ) + : 0), + ), ), printClosingTagSuffix(child, options), ]; @@ -176,7 +176,7 @@ function printChildren(path, options, print) { leadingParts.push( ifBreak("", softline, { groupId: groupIds[childIndex - 1], - }) + }), ); } } diff --git a/src/language-html/print/element.js b/src/language-html/print/element.js index 0b0723755..7dff2937c 100644 --- a/src/language-html/print/element.js +++ b/src/language-html/print/element.js @@ -138,7 +138,7 @@ function printElement(path, options, print) { node.isWhitespaceSensitive && node.isIndentationSensitive)) && new RegExp( - `\\n[\\t ]{${options.tabWidth * (path.ancestors.length - 1)}}$` + `\\n[\\t ]{${options.tabWidth * (path.ancestors.length - 1)}}$`, ).test(node.lastChild.value) ) { return ""; @@ -148,7 +148,7 @@ function printElement(path, options, print) { if (node.children.length === 0) { return printTag( - node.hasDanglingSpaces && node.isDanglingSpaceSensitive ? line : "" + node.hasDanglingSpaces && node.isDanglingSpaceSensitive ? line : "", ); } diff --git a/src/language-html/print/tag.js b/src/language-html/print/tag.js index 0a51407d6..925809567 100644 --- a/src/language-html/print/tag.js +++ b/src/language-html/print/tag.js @@ -240,10 +240,10 @@ function printAttributes(path, options, print) { ({ node: attribute }) => hasPrettierIgnoreAttribute(attribute) ? replaceEndOfLine( - options.originalText.slice(locStart(attribute), locEnd(attribute)) + options.originalText.slice(locStart(attribute), locEnd(attribute)), ) : print(), - "attrs" + "attrs", ); const forceNotToBreakAttrContent = @@ -295,7 +295,7 @@ function printAttributes(path, options, print) { : "" : node.isSelfClosing ? line - : softline + : softline, ); } diff --git a/src/language-html/printer-html.js b/src/language-html/printer-html.js index 3b424b6e7..ec59926f7 100644 --- a/src/language-html/printer-html.js +++ b/src/language-html/printer-html.js @@ -82,7 +82,7 @@ function genericPrint(path, options, print) { return [ printOpeningTagPrefix(node, options), replaceEndOfLine( - options.originalText.slice(locStart(node), locEnd(node)) + options.originalText.slice(locStart(node), locEnd(node)), ), printClosingTagSuffix(node, options), ]; @@ -100,7 +100,7 @@ function genericPrint(path, options, print) { replaceEndOfLine( quote === '"' ? value.replaceAll('"', """) - : value.replaceAll("'", "'") + : value.replaceAll("'", "'"), ), quote, ]; diff --git a/src/language-html/utils/html-elements-attributes.evaluate.js b/src/language-html/utils/html-elements-attributes.evaluate.js index 2cf5ec8b7..ba445f645 100644 --- a/src/language-html/utils/html-elements-attributes.evaluate.js +++ b/src/language-html/utils/html-elements-attributes.evaluate.js @@ -4,7 +4,7 @@ const HTML_ELEMENT_ATTRIBUTES = new Map( Object.entries(htmlElementAttributes).map(([tagName, attributes]) => [ tagName, new Set(attributes), - ]) + ]), ); export default HTML_ELEMENT_ATTRIBUTES; diff --git a/src/language-html/utils/index.js b/src/language-html/utils/index.js index abe37f1ba..f93d89346 100644 --- a/src/language-html/utils/index.js +++ b/src/language-html/utils/index.js @@ -59,7 +59,7 @@ function shouldPreserveContent(node, options) { if ( isPreLikeNode(node) && node.children.some( - (child) => child.type !== "text" && child.type !== "interpolation" + (child) => child.type !== "text" && child.type !== "interpolation", ) ) { return true; @@ -612,7 +612,7 @@ function getTextValueParts(node, value = node.value) { ? replaceEndOfLine(value) : replaceEndOfLine( dedentString(htmlTrimPreserveIndentation(value)), - hardline + hardline, ) : join(line, htmlWhitespaceUtils.split(value)); } diff --git a/src/language-html/utils/is-vue-sfc-with-typescript-script.js b/src/language-html/utils/is-vue-sfc-with-typescript-script.js index 4260b0393..544e448bd 100644 --- a/src/language-html/utils/is-vue-sfc-with-typescript-script.js +++ b/src/language-html/utils/is-vue-sfc-with-typescript-script.js @@ -9,8 +9,8 @@ function isVueSfcWithTypescriptScript(path, options) { root.children.some( (child) => isVueScriptTag(child, options) && - ["ts", "typescript"].includes(child.attrMap.lang) - ) + ["ts", "typescript"].includes(child.attrMap.lang), + ), ); } diff --git a/src/language-js/clean.js b/src/language-js/clean.js index 006021fc6..51fdb1fba 100644 --- a/src/language-js/clean.js +++ b/src/language-js/clean.js @@ -125,7 +125,7 @@ function clean(ast, newObj, parent) { ) { newObj.value.value = newObj.value.value.replaceAll( /["']|"|'/g, - '"' + '"', ); } @@ -182,8 +182,8 @@ function clean(ast, newObj, parent) { (comment) => isBlockComment(comment) && ["GraphQL", "HTML"].some( - (languageName) => comment.value === ` ${languageName} ` - ) + (languageName) => comment.value === ` ${languageName} `, + ), ); if ( hasLanguageComment || diff --git a/src/language-js/comments/handle-comments.js b/src/language-js/comments/handle-comments.js index a90507dda..62b8df5b5 100644 --- a/src/language-js/comments/handle-comments.js +++ b/src/language-js/comments/handle-comments.js @@ -115,7 +115,7 @@ function handleRemainingComment(context) { function addBlockStatementFirstComment(node, comment) { // @ts-expect-error const firstNonEmptyNode = (node.body || node.properties).find( - ({ type }) => type !== "EmptyStatement" + ({ type }) => type !== "EmptyStatement", ); if (firstNonEmptyNode) { addLeadingComment(firstNonEmptyNode, comment); @@ -178,7 +178,7 @@ function handleIfStatementComments({ // it is a ). const nextCharacter = getNextNonSpaceNonCommentCharacter( text, - locEnd(comment) + locEnd(comment), ); if (nextCharacter === ")") { addTrailingComment(precedingNode, comment); @@ -208,7 +208,7 @@ function handleIfStatementComments({ addDanglingComment( precedingNode, comment, - markerForIfWithoutBlockAndSameLineComment + markerForIfWithoutBlockAndSameLineComment, ); } else { addDanglingComment(enclosingNode, comment); @@ -258,7 +258,7 @@ function handleWhileComments({ // it is a ). const nextCharacter = getNextNonSpaceNonCommentCharacter( text, - locEnd(comment) + locEnd(comment), ); if (nextCharacter === ")") { addTrailingComment(precedingNode, comment); @@ -592,7 +592,7 @@ function handleLastFunctionArgComments({ if (parameters.length > 0) { return getNextNonSpaceNonCommentCharacterIndex( text, - locEnd(parameters.at(-1)) + locEnd(parameters.at(-1)), ); } const functionParamLeftParenIndex = @@ -601,7 +601,7 @@ function handleLastFunctionArgComments({ functionParamLeftParenIndex !== false && getNextNonSpaceNonCommentCharacterIndex( text, - functionParamLeftParenIndex + 1 + functionParamLeftParenIndex + 1, ) ); })(); diff --git a/src/language-js/embed/css.js b/src/language-js/embed/css.js index 96779c1af..731395e93 100644 --- a/src/language-js/embed/css.js +++ b/src/language-js/embed/css.js @@ -19,7 +19,7 @@ async function printEmbedCss(textToDoc, print, path /*, options*/) { placeholderID++ + "-id" + currVal, - "" + "", ); const quasisDoc = await textToDoc(text, { parser: "scss" }); const expressionDocs = printTemplateExpressions(path, print); @@ -75,7 +75,7 @@ function isStyledJsx({ node, parent, grandparent }) { grandparent.type === "JSXElement" && grandparent.openingElement.name.name === "style" && grandparent.openingElement.attributes.some( - (attribute) => attribute.name.name === "jsx" + (attribute) => attribute.name.name === "jsx", )) || (parent?.type === "TaggedTemplateExpression" && parent.tag.type === "Identifier" && diff --git a/src/language-js/embed/graphql.js b/src/language-js/embed/graphql.js index f9fa73b60..0172b07d8 100644 --- a/src/language-js/embed/graphql.js +++ b/src/language-js/embed/graphql.js @@ -31,7 +31,7 @@ async function printEmbedGraphQL(textToDoc, print, path /*, options*/) { lines[numLines - 2].trim() === ""; const commentsAndWhitespaceOnly = lines.every((line) => - /^\s*(?:#[^\n\r]*)?$/.test(line) + /^\s*(?:#[^\n\r]*)?$/.test(line), ); // Bail out if an interpolation occurs within a comment. diff --git a/src/language-js/embed/html.js b/src/language-js/embed/html.js index 7b1f283a4..8d301dccb 100644 --- a/src/language-js/embed/html.js +++ b/src/language-js/embed/html.js @@ -26,7 +26,7 @@ async function printEmbedHtmlLike(parser, textToDoc, print, path, options) { .map((quasi, index, quasis) => index === quasis.length - 1 ? quasi.value.cooked - : quasi.value.cooked + composePlaceholder(index) + : quasi.value.cooked + composePlaceholder(index), ) .join(""); @@ -92,7 +92,7 @@ async function printEmbedHtmlLike(parser, textToDoc, print, path, options) { topLevelCount > 1 ? indent(group(contentDoc)) : group(contentDoc), trailingWhitespace, "`", - ]) + ]), ); } @@ -109,7 +109,7 @@ function isHtml(path) { node.type === "TaggedTemplateExpression" && node.tag.type === "Identifier" && node.tag.name === "html" && - name === "quasi" + name === "quasi", ) ); } diff --git a/src/language-js/embed/markdown.js b/src/language-js/embed/markdown.js index cb293947b..3effc23c7 100644 --- a/src/language-js/embed/markdown.js +++ b/src/language-js/embed/markdown.js @@ -10,7 +10,7 @@ async function printEmbedMarkdown(textToDoc, print, path /*, options*/) { const { node } = path; let text = node.quasis[0].value.raw.replaceAll( /((?:\\\\)*)\\`/g, - (_, backslashes) => "\\".repeat(backslashes.length / 2) + "`" + (_, backslashes) => "\\".repeat(backslashes.length / 2) + "`", ); const indentation = getIndentation(text); const hasIndent = indentation !== ""; @@ -19,7 +19,7 @@ async function printEmbedMarkdown(textToDoc, print, path /*, options*/) { } const doc = escapeTemplateCharacters( await textToDoc(text, { parser: "markdown", __inJsTemplate: true }), - true + true, ); return [ "`", diff --git a/src/language-js/embed/utils.js b/src/language-js/embed/utils.js index 70c98e7b6..aab006fbd 100644 --- a/src/language-js/embed/utils.js +++ b/src/language-js/embed/utils.js @@ -38,7 +38,7 @@ function isAngularComponentStyles(path) { node.key.type === "Identifier" && node.key.name === "styles" && name === "value", - ...angularComponentObjectExpressionPredicates + ...angularComponentObjectExpressionPredicates, ); } function isAngularComponentTemplate(path) { @@ -49,7 +49,7 @@ function isAngularComponentTemplate(path) { node.key.type === "Identifier" && node.key.name === "template" && name === "value", - ...angularComponentObjectExpressionPredicates + ...angularComponentObjectExpressionPredicates, ); } @@ -62,7 +62,7 @@ function hasLanguageComment(node, languageName) { return hasComment( node, CommentCheckFlags.Block | CommentCheckFlags.Leading, - ({ value }) => value === ` ${languageName} ` + ({ value }) => value === ` ${languageName} `, ); } diff --git a/src/language-js/needs-parens.js b/src/language-js/needs-parens.js index 98821f07c..0fccfddc9 100644 --- a/src/language-js/needs-parens.js +++ b/src/language-js/needs-parens.js @@ -65,13 +65,13 @@ function needsParens(path, options) { // `for ((let.a) of []);` if (node.name === "let") { const expression = path.findAncestor( - (node) => node.type === "ForOfStatement" + (node) => node.type === "ForOfStatement", )?.left; if ( expression && startsWithNoLookaheadToken( expression, - (leftmostNode) => leftmostNode === node + (leftmostNode) => leftmostNode === node, ) ) { return true; @@ -90,7 +90,7 @@ function needsParens(path, options) { (node) => node.type === "ExpressionStatement" || node.type === "ForStatement" || - node.type === "ForInStatement" + node.type === "ForInStatement", ); const expression = !statement ? undefined @@ -103,7 +103,7 @@ function needsParens(path, options) { expression && startsWithNoLookaheadToken( expression, - (leftmostNode) => leftmostNode === node + (leftmostNode) => leftmostNode === node, ) ) { return true; @@ -120,13 +120,13 @@ function needsParens(path, options) { node.type === "DoExpression" ) { const expression = path.findAncestor( - (node) => node.type === "ExpressionStatement" + (node) => node.type === "ExpressionStatement", )?.expression; if ( expression && startsWithNoLookaheadToken( expression, - (leftmostNode) => leftmostNode === node + (leftmostNode) => leftmostNode === node, ) ) { return true; @@ -135,7 +135,7 @@ function needsParens(path, options) { if (node.type === "ObjectExpression") { const arrowFunctionBody = path.findAncestor( - (node) => node.type === "ArrowFunctionExpression" + (node) => node.type === "ArrowFunctionExpression", )?.body; if ( arrowFunctionBody && @@ -143,7 +143,7 @@ function needsParens(path, options) { arrowFunctionBody.type !== "AssignmentExpression" && startsWithNoLookaheadToken( arrowFunctionBody, - (leftmostNode) => leftmostNode === node + (leftmostNode) => leftmostNode === node, ) ) { return true; @@ -234,7 +234,7 @@ function needsParens(path, options) { undefined, undefined, (node, key) => - key === "returnType" && node.type === "ArrowFunctionExpression" + key === "returnType" && node.type === "ArrowFunctionExpression", ) && includesFunctionTypeInObjectType(node) ) { @@ -476,7 +476,7 @@ function needsParens(path, options) { (node, key) => key === "typeAnnotation" && node.type === "TSTypeAnnotation", (node, key) => - key === "returnType" && node.type === "ArrowFunctionExpression" + key === "returnType" && node.type === "ArrowFunctionExpression", ) ) { return true; @@ -579,7 +579,7 @@ function needsParens(path, options) { (node, key) => key === "typeAnnotation" && node.type === "TypeAnnotation", (node, key) => - key === "returnType" && node.type === "ArrowFunctionExpression" + key === "returnType" && node.type === "ArrowFunctionExpression", ) ) { return true; @@ -600,7 +600,7 @@ function needsParens(path, options) { (node, key) => key === "typeAnnotation" && node.type === "TypeAnnotation", (node, key) => - key === "returnType" && node.type === "ArrowFunctionExpression" + key === "returnType" && node.type === "ArrowFunctionExpression", ) ) { return true; @@ -629,7 +629,7 @@ function needsParens(path, options) { (parent.type === "FunctionTypeParam" && parent.name === null && getFunctionParameters(node).some( - (param) => param.typeAnnotation?.type === "NullableTypeAnnotation" + (param) => param.typeAnnotation?.type === "NullableTypeAnnotation", )) ); } @@ -989,7 +989,7 @@ function includesFunctionTypeInObjectType(node) { node, (node) => node.type === "ObjectTypeAnnotation" && - hasNode(node, (node) => node.type === "FunctionTypeAnnotation") + hasNode(node, (node) => node.type === "FunctionTypeAnnotation"), ); } @@ -1052,7 +1052,7 @@ function shouldWrapFunctionForExportDefault(path, options) { return path.call( () => shouldWrapFunctionForExportDefault(path, options), - ...getLeftSidePathName(node) + ...getLeftSidePathName(node), ); } @@ -1095,7 +1095,7 @@ function shouldAddParenthesesToChainElement(path) { if ( path.match( () => node.type === "CallExpression" || node.type === "MemberExpression", - (node, name) => name === "expression" && node.type === "ChainExpression" + (node, name) => name === "expression" && node.type === "ChainExpression", ) && (path.match( undefined, @@ -1106,14 +1106,14 @@ function shouldAddParenthesesToChainElement(path) { node.type === "NewExpression")) || (name === "object" && node.type === "MemberExpression" && - !node.optional) + !node.optional), ) || path.match( undefined, undefined, (node, name) => name === "expression" && node.type === "TSNonNullExpression", - (node, name) => name === "object" && node.type === "MemberExpression" + (node, name) => name === "object" && node.type === "MemberExpression", )) ) { return true; @@ -1127,7 +1127,7 @@ function shouldAddParenthesesToChainElement(path) { (node, name) => name === "expression" && node.type === "TSNonNullExpression", (node, name) => name === "expression" && node.type === "ChainExpression", - (node, name) => name === "object" && node.type === "MemberExpression" + (node, name) => name === "object" && node.type === "MemberExpression", ) ) { return true; diff --git a/src/language-js/parse/acorn.js b/src/language-js/parse/acorn.js index 0d733602d..28e7d9916 100644 --- a/src/language-js/parse/acorn.js +++ b/src/language-js/parse/acorn.js @@ -69,7 +69,7 @@ function parseWithOptions(text, sourceType) { function parse(text, options = {}) { const sourceType = getSourceType(options); const combinations = (sourceType ? [sourceType] : ["module", "script"]).map( - (sourceType) => () => parseWithOptions(text, sourceType) + (sourceType) => () => parseWithOptions(text, sourceType), ); let ast; diff --git a/src/language-js/parse/babel.js b/src/language-js/parse/babel.js index 52d188383..1907ae1ba 100644 --- a/src/language-js/parse/babel.js +++ b/src/language-js/parse/babel.js @@ -94,7 +94,7 @@ function isFlowFile(text, options) { function parseWithOptions(parse, text, options) { const ast = parse(text, options); const error = ast.errors.find( - (error) => !allowedMessageCodes.has(error.reasonCode) + (error) => !allowedMessageCodes.has(error.reasonCode), ); if (error) { throw error; @@ -123,7 +123,7 @@ function createParse({ isExpression = false, optionsCombinations }) { if (/#[[{]/.test(text)) { combinations = combinations.map((options) => - appendPlugins([recordAndTuplePlugin], options) + appendPlugins([recordAndTuplePlugin], options), ); } @@ -134,12 +134,12 @@ function createParse({ isExpression = false, optionsCombinations }) { : pipelineOperatorPlugins; combinations = conflictsPlugins.flatMap((pipelineOperatorPlugin) => combinations.map((options) => - appendPlugins([pipelineOperatorPlugin], options) - ) + appendPlugins([pipelineOperatorPlugin], options), + ), ); } else if (shouldEnableV8intrinsicPlugin) { combinations = combinations.map((options) => - appendPlugins([v8intrinsicPlugin], options) + appendPlugins([v8intrinsicPlugin], options), ); } @@ -150,8 +150,8 @@ function createParse({ isExpression = false, optionsCombinations }) { try { ast = tryCombinations( combinations.map( - (options) => () => parseWithOptions(parseFunction, text, options) - ) + (options) => () => parseWithOptions(parseFunction, text, options), + ), ); } catch (/** @type {any} */ { errors: [error] }) { throw createBabelParseError(error); @@ -242,7 +242,7 @@ const babelFlow = createBabelParser({ }); const babelEstree = createBabelParser({ optionsCombinations: babelParserOptionsCombinations.map((options) => - appendPlugins(["estree"], options) + appendPlugins(["estree"], options), ), }); diff --git a/src/language-js/parse/meriyah.js b/src/language-js/parse/meriyah.js index bd46a04d2..6252aa042 100644 --- a/src/language-js/parse/meriyah.js +++ b/src/language-js/parse/meriyah.js @@ -62,7 +62,7 @@ function createParseError(error) { let { message, line, column } = error; const matches = message.match( - /^\[(?\d+):(?\d+)]: (?.*)$/ + /^\[(?\d+):(?\d+)]: (?.*)$/, )?.groups; if (matches) { @@ -89,7 +89,7 @@ function createParseError(error) { function parse(text, options = {}) { const sourceType = getSourceType(options); const combinations = (sourceType ? [sourceType] : ["module", "script"]).map( - (sourceType) => () => parseWithOptions(text, sourceType) + (sourceType) => () => parseWithOptions(text, sourceType), ); let ast; diff --git a/src/language-js/parse/postprocess/index.js b/src/language-js/parse/postprocess/index.js index cc57d2a2d..6bb76b525 100644 --- a/src/language-js/parse/postprocess/index.js +++ b/src/language-js/parse/postprocess/index.js @@ -98,7 +98,7 @@ function postprocess(ast, options) { const invalidProperty = node.properties.find( (property) => property.type === "Property" && - property.value.type === "TSEmptyBodyFunctionExpression" + property.value.type === "TSEmptyBodyFunctionExpression", ); if (invalidProperty) { throwSyntaxError(invalidProperty.value, "Unexpected token."); @@ -109,7 +109,7 @@ function postprocess(ast, options) { if (isNonEmptyArray(node.implements)) { throwSyntaxError( node.implements[0], - "Interface declaration cannot have 'implements' clause." + "Interface declaration cannot have 'implements' clause.", ); } break; @@ -118,7 +118,7 @@ function postprocess(ast, options) { if (node.initializer) { throwSyntaxError( node.initializer, - "An interface property cannot have an initializer." + "An interface property cannot have an initializer.", ); } break; diff --git a/src/language-js/parse/postprocess/typescript.js b/src/language-js/parse/postprocess/typescript.js index b542218cd..4c0735e02 100644 --- a/src/language-js/parse/postprocess/typescript.js +++ b/src/language-js/parse/postprocess/typescript.js @@ -32,7 +32,7 @@ function throwErrorForInvalidAbstractProperty(tsNode, esTreeNode) { tsNode.initializer && esTreeNode.value === null && tsNode.modifiers?.some( - (modifier) => modifier.kind === ts.SyntaxKind.AbstractKeyword + (modifier) => modifier.kind === ts.SyntaxKind.AbstractKeyword, ) ) ) { @@ -41,7 +41,7 @@ function throwErrorForInvalidAbstractProperty(tsNode, esTreeNode) { throwTsSyntaxError( esTreeNode, - "Abstract property cannot have an initializer" + "Abstract property cannot have an initializer", ); } @@ -52,8 +52,8 @@ function nodeCanBeDecorated(node) { useLegacyDecorators, node, node.parent, - node.parent.parent - ) + node.parent.parent, + ), ); } @@ -75,7 +75,7 @@ function throwErrorForInvalidModifier(node) { ) { throwErrorOnTsNode( modifier, - "A decorator can only decorate a method implementation, not an overload." + "A decorator can only decorate a method implementation, not an overload.", ); } @@ -90,8 +90,8 @@ function throwErrorForInvalidModifier(node) { throwErrorOnTsNode( modifier, `'${ts.tokenToString( - modifier.kind - )}' modifier cannot appear on a type member` + modifier.kind, + )}' modifier cannot appear on a type member`, ); } @@ -103,8 +103,8 @@ function throwErrorForInvalidModifier(node) { throwErrorOnTsNode( modifier, `'${ts.tokenToString( - modifier.kind - )}' modifier cannot appear on an index signature` + modifier.kind, + )}' modifier cannot appear on an index signature`, ); } } @@ -118,8 +118,8 @@ function throwErrorForInvalidModifier(node) { throwErrorOnTsNode( modifier, `'${ts.tokenToString( - modifier.kind - )}' modifier cannot appear on a type parameter` + modifier.kind, + )}' modifier cannot appear on a type parameter`, ); } @@ -136,8 +136,8 @@ function throwErrorForInvalidModifier(node) { throwErrorOnTsNode( modifier, `'${ts.tokenToString( - modifier.kind - )}' modifier can only appear on a type parameter of a class, interface or type alias` + modifier.kind, + )}' modifier can only appear on a type parameter of a class, interface or type alias`, ); } @@ -150,7 +150,7 @@ function throwErrorForInvalidModifier(node) { ) { throwErrorOnTsNode( modifier, - "'readonly' modifier can only appear on a property declaration or index signature." + "'readonly' modifier can only appear on a property declaration or index signature.", ); } @@ -162,8 +162,8 @@ function throwErrorForInvalidModifier(node) { throwErrorOnTsNode( modifier, `'${ts.tokenToString( - modifier.kind - )}' modifier cannot appear on class elements of this kind.` + modifier.kind, + )}' modifier cannot appear on class elements of this kind.`, ); } @@ -179,8 +179,8 @@ function throwErrorForInvalidModifier(node) { throwErrorOnTsNode( modifier, `'${ts.tokenToString( - modifier.kind - )}' modifier can only appear on a class, method, or property declaration.` + modifier.kind, + )}' modifier can only appear on a class, method, or property declaration.`, ); } @@ -195,8 +195,8 @@ function throwErrorForInvalidModifier(node) { throwErrorOnTsNode( modifier, `'${ts.tokenToString( - modifier.kind - )}' modifier cannot appear on a module or namespace element.` + modifier.kind, + )}' modifier cannot appear on a module or namespace element.`, ); } @@ -206,7 +206,7 @@ function throwErrorForInvalidModifier(node) { ) { throwErrorOnTsNode( modifier, - "'accessor' modifier can only appear on a property declaration." + "'accessor' modifier can only appear on a property declaration.", ); } @@ -232,8 +232,8 @@ function throwErrorForInvalidModifier(node) { throwErrorOnTsNode( modifier, `'${ts.tokenToString( - modifier.kind - )}' modifier cannot appear on a parameter.` + modifier.kind, + )}' modifier cannot appear on a parameter.`, ); } @@ -255,7 +255,7 @@ function throwErrorForInvalidModifier(node) { ) { throwErrorOnTsNode( modifier, - "A parameter property is only allowed in a constructor implementation." + "A parameter property is only allowed in a constructor implementation.", ); } } @@ -297,7 +297,7 @@ const POSSIBLE_MODIFIERS = [ ]; const decoratorOrModifierRegExp = new RegExp( - ["@", ...POSSIBLE_MODIFIERS].join("|") + ["@", ...POSSIBLE_MODIFIERS].join("|"), ); function throwErrorForInvalidNodes(tsParseResult, text) { diff --git a/src/language-js/parse/typescript.js b/src/language-js/parse/typescript.js index 32b38a939..7765528dd 100644 --- a/src/language-js/parse/typescript.js +++ b/src/language-js/parse/typescript.js @@ -61,8 +61,8 @@ function parse(text, options) { try { result = tryCombinations( parseOptionsCombinations.map( - (parseOptions) => () => parseWithNodeMaps(textToParse, parseOptions) - ) + (parseOptions) => () => parseWithNodeMaps(textToParse, parseOptions), + ), ); } catch (/** @type {any} */ { errors: [ @@ -89,7 +89,7 @@ function isProbablyJsx(text) { "|", "(?:^[^/]{2}.*/>)", // Contains "/>" on line not starting with "//" ].join(""), - "m" + "m", ).test(text); } diff --git a/src/language-js/print/angular.js b/src/language-js/print/angular.js index 20ad67411..811f00ec1 100644 --- a/src/language-js/print/angular.js +++ b/src/language-js/print/angular.js @@ -34,9 +34,9 @@ function printAngular(path, options, print) { [";", line], path.map( () => (hasNgSideEffect(path) ? print() : ["(", print(), ")"]), - "expressions" - ) - ) + "expressions", + ), + ), ); case "NGEmptyExpression": return ""; @@ -46,7 +46,7 @@ function printAngular(path, options, print) { path.isFirst ? "" : isNgForOf(path) ? " " : [";", line], print(), ], - "body" + "body", ); case "NGMicrosyntaxKey": return /^[$_a-z][\w$]*(?:-[$_a-z][\w$])*$/i.test(node.name) diff --git a/src/language-js/print/array.js b/src/language-js/print/array.js index aef143424..cd99d7cd9 100644 --- a/src/language-js/print/array.js +++ b/src/language-js/print/array.js @@ -65,7 +65,7 @@ function printArray(path, options, print) { const elements = node[elementsProperty]; if (elements.length === 0) { parts.push( - printEmptyArrayElements(path, options, openBracket, closeBracket) + printEmptyArrayElements(path, options, openBracket, closeBracket), ); } else { const lastElem = elements.at(-1); @@ -138,14 +138,14 @@ function printArray(path, options, print) { softline, closeBracket, ], - { shouldBreak, id: groupId } - ) + { shouldBreak, id: groupId }, + ), ); } parts.push( printOptionalToken(path), - printTypeAnnotationProperty(path, print) + printTypeAnnotationProperty(path, print), ); return parts; @@ -166,8 +166,8 @@ function isConciselyPrintedArray(node, options) { (comment) => !hasNewline(options.originalText, locStart(comment), { backwards: true, - }) - ) + }), + ), ) ); } @@ -214,7 +214,7 @@ function printArrayElementsConcisely(path, options, print, trailingComma) { ? [hardline, hardline] : hasComment(next, CommentCheckFlags.Leading | CommentCheckFlags.Line) ? hardline - : line + : line, ); } }, "elements"); diff --git a/src/language-js/print/arrow-function.js b/src/language-js/print/arrow-function.js index 8785c5419..d061410d8 100644 --- a/src/language-js/print/arrow-function.js +++ b/src/language-js/print/arrow-function.js @@ -47,8 +47,8 @@ function shouldAddParensIfNotBreak(node) { node.type === "ConditionalExpression" && !startsWithNoLookaheadToken( node, - (node) => node.type === "ObjectExpression" - ) + (node) => node.type === "ObjectExpression", + ), ); } return shouldAddParensIfNotBreakCache.get(node); @@ -76,7 +76,7 @@ function printArrowFunction(path, options, print, args = {}) { path, options, print, - args + args, ); if (signatureDocs.length === 0) { signatureDocs.push(signatureDoc); @@ -92,7 +92,7 @@ function printArrowFunction(path, options, print, args = {}) { (node.returnType && getFunctionParameters(node).length > 0) || node.typeParameters || getFunctionParameters(node).some( - (param) => param.type !== "Identifier" + (param) => param.type !== "Identifier", ); } @@ -145,7 +145,7 @@ function printArrowFunction(path, options, print, args = {}) { shouldIndentSignatures ? indent([softline, signaturesDoc]) : signaturesDoc, - { shouldBreak: shouldBreakSignatures, id: chainGroupId } + { shouldBreak: shouldBreakSignatures, id: chainGroupId }, ), " =>", shouldPrintAsChain @@ -183,10 +183,10 @@ function printArrowFunctionSignature(path, options, print, args) { print, options, expandArg, - /* printTypeParams */ true + /* printTypeParams */ true, ), returnTypeDoc, - ]) + ]), ); } @@ -194,7 +194,7 @@ function printArrowFunctionSignature(path, options, print, args) { filter(comment) { const nextCharacter = getNextNonSpaceNonCommentCharacterIndex( options.originalText, - locEnd(comment) + locEnd(comment), ); return ( nextCharacter !== false && @@ -240,7 +240,7 @@ function mayBreakAfterShortPrefix(functionBody, bodyDoc, options) { function printArrowFunctionSignatures( path, args, - { signatureDocs, shouldBreak } + { signatureDocs, shouldBreak }, ) { if (signatureDocs.length === 1) { return signatureDocs[0]; @@ -257,7 +257,7 @@ function printArrowFunctionSignatures( " =>", indent([line, join([" =>", line], signatureDocs.slice(1))]), ], - { shouldBreak } + { shouldBreak }, ); } @@ -286,7 +286,7 @@ function printArrowFunctionBody( path, options, args, - { bodyDoc, bodyComments, functionBody, shouldPutBodyOnSameLine } + { bodyDoc, bodyComments, functionBody, shouldPutBodyOnSameLine }, ) { const { node, parent } = path; diff --git a/src/language-js/print/assignment.js b/src/language-js/print/assignment.js index e3686efb3..8e8d032dd 100644 --- a/src/language-js/print/assignment.js +++ b/src/language-js/print/assignment.js @@ -32,7 +32,7 @@ function printAssignment( print, leftDoc, operator, - rightPropertyName + rightPropertyName, ) { const layout = chooseLayout(path, options, print, leftDoc, rightPropertyName); @@ -88,7 +88,7 @@ function printAssignmentExpression(path, options, print) { print, print("left"), [" ", node.operator], - "right" + "right", ); } @@ -115,7 +115,7 @@ function chooseLayout(path, options, print, leftDoc, rightPropertyName) { (node) => !isTail || (node.type !== "ExpressionStatement" && - node.type !== "VariableDeclaration") + node.type !== "VariableDeclaration"), ); if (shouldUseChainFormatting) { return !isTail @@ -159,7 +159,7 @@ function chooseLayout(path, options, print, leftDoc, rightPropertyName) { if ( path.call( () => shouldBreakAfterOperator(path, options, print, hasShortKey), - rightPropertyName + rightPropertyName, ) ) { return "break-after-operator"; @@ -219,7 +219,7 @@ function shouldBreakAfterOperator(path, options, print, hasShortKey) { isStringLiteral(node) || path.call( () => isPoorlyBreakableMemberOrCallChain(path, options, print), - ...propertiesForPath + ...propertiesForPath, ) ) { return true; @@ -239,7 +239,7 @@ function isComplexDestructuring(node) { leftNode.properties.some( (property) => isObjectProperty(property) && - (!property.shorthand || property.value?.type === "AssignmentPattern") + (!property.shorthand || property.value?.type === "AssignmentPattern"), ) ); } @@ -288,7 +288,7 @@ function hasComplexTypeAnnotation(node) { return false; } const typeParams = getTypeParametersFromTypeReference( - typeAnnotation.typeAnnotation + typeAnnotation.typeAnnotation, ); return ( isNonEmptyArray(typeParams) && @@ -296,7 +296,7 @@ function hasComplexTypeAnnotation(node) { typeParams.some( (param) => isNonEmptyArray(getTypeParametersFromTypeReference(param)) || - param.type === "TSConditionalType" + param.type === "TSConditionalType", ) ); } @@ -326,7 +326,7 @@ function isPoorlyBreakableMemberOrCallChain( path, options, print, - deep = false + deep = false, ) { const { node } = path; const goDeeper = () => diff --git a/src/language-js/print/binaryish.js b/src/language-js/print/binaryish.js index 2fd890a52..b6e0a31f2 100644 --- a/src/language-js/print/binaryish.js +++ b/src/language-js/print/binaryish.js @@ -43,7 +43,7 @@ function printBinaryishExpression(path, options, print) { print, options, /* isNested */ false, - isInsideParenthesis + isInsideParenthesis, ); // if ( @@ -140,13 +140,13 @@ function printBinaryishExpression(path, options, print) { (part) => typeof part !== "string" && !Array.isArray(part) && - part.type === DOC_TYPE_GROUP + part.type === DOC_TYPE_GROUP, ); // Separate the leftmost expression, possibly with its leading comments. const headParts = parts.slice( 0, - firstGroupIndex === -1 ? 1 : firstGroupIndex + 1 + firstGroupIndex === -1 ? 1 : firstGroupIndex + 1, ); const rest = parts.slice(headParts.length, hasJsx ? -1 : undefined); @@ -161,7 +161,7 @@ function printBinaryishExpression(path, options, print) { ...headParts, indent(rest), ], - { id: groupId } + { id: groupId }, ); if (!hasJsx) { @@ -185,7 +185,7 @@ function printBinaryishExpressions( print, options, isNested, - isInsideParenthesis + isInsideParenthesis, ) { const { node } = path; @@ -217,9 +217,9 @@ function printBinaryishExpressions( print, options, /* isNested */ true, - isInsideParenthesis + isInsideParenthesis, ), - "left" + "left", ); } else { parts.push(group(print("left"))); @@ -241,9 +241,9 @@ function printBinaryishExpressions( ": ", join( [line, ": "], - path.map(() => align(2, group(print())), "arguments") + path.map(() => align(2, group(print())), "arguments"), ), - ]) + ]), ) : ""; @@ -262,9 +262,9 @@ function printBinaryishExpressions( print, options, /* isNested */ true, - isInsideParenthesis + isInsideParenthesis, ), - "right" + "right", ) : print("right"); right = [ @@ -281,7 +281,7 @@ function printBinaryishExpressions( const { parent } = path; const shouldBreak = hasComment( node.left, - CommentCheckFlags.Trailing | CommentCheckFlags.Line + CommentCheckFlags.Trailing | CommentCheckFlags.Line, ); const shouldGroup = shouldBreak || @@ -292,7 +292,7 @@ function printBinaryishExpressions( parts.push( lineBeforeOperator ? "" : " ", - shouldGroup ? group(right, { shouldBreak }) : right + shouldGroup ? group(right, { shouldBreak }) : right, ); // The root comments are already printed, but we need to manually print @@ -343,7 +343,8 @@ function isVueFilterSequenceExpression(path, options) { options.parser === "__vue_ts_expression") && isBitwiseOrExpression(path.node) && !path.hasAncestor( - (node) => !isBitwiseOrExpression(node) && node.type !== "JsExpressionRoot" + (node) => + !isBitwiseOrExpression(node) && node.type !== "JsExpressionRoot", ) ); } diff --git a/src/language-js/print/call-arguments.js b/src/language-js/print/call-arguments.js index 99040ebf9..e5efb0c37 100644 --- a/src/language-js/print/call-arguments.js +++ b/src/language-js/print/call-arguments.js @@ -79,7 +79,7 @@ function printCallArguments(path, options, print) { function allArgsBrokenOut() { return group( ["(", indent([line, ...printedArguments]), maybeTrailingComma, line, ")"], - { shouldBreak: true } + { shouldBreak: true }, ); } diff --git a/src/language-js/print/class.js b/src/language-js/print/class.js index a84259634..fa594ee28 100644 --- a/src/language-js/print/class.js +++ b/src/language-js/print/class.js @@ -83,7 +83,7 @@ function printClass(path, options, print) { ]; const printedWithComments = path.call( (superClass) => ["extends ", printComments(superClass, printed, options)], - "superClass" + "superClass", ); if (groupMode) { extendsParts.push(line, group(printedWithComments)); @@ -96,7 +96,7 @@ function printClass(path, options, print) { extendsParts.push( printHeritageClauses(path, options, print, "mixins"), - printHeritageClauses(path, options, print, "implements") + printHeritageClauses(path, options, print, "implements"), ); if (groupMode) { @@ -126,7 +126,7 @@ function hasMultipleHeritage(node) { return ( ["extends", "mixins", "implements"].reduce( (count, key) => count + (Array.isArray(node[key]) ? node[key].length : 0), - node.superClass ? 1 : 0 + node.superClass ? 1 : 0, ) > 1 ); } @@ -136,7 +136,7 @@ function shouldIndentOnlyHeritageClauses(node) { node.typeParameters && !hasComment( node.typeParameters, - CommentCheckFlags.Trailing | CommentCheckFlags.Line + CommentCheckFlags.Trailing | CommentCheckFlags.Line, ) && !hasMultipleHeritage(node) ); @@ -169,7 +169,7 @@ function printSuperClass(path, options, print) { const { parent } = path; if (parent.type === "AssignmentExpression") { return group( - ifBreak(["(", indent([softline, printed]), softline, ")"], printed) + ifBreak(["(", indent([softline, printed]), softline, ")"], printed), ); } return printed; @@ -237,7 +237,7 @@ function printClassProperty(path, options, print) { printPropertyKey(path, options, print), printOptionalToken(path), printDefiniteToken(path), - printTypeAnnotationProperty(path, print) + printTypeAnnotationProperty(path, print), ); const isAbstractProperty = @@ -251,7 +251,7 @@ function printClassProperty(path, options, print) { print, parts, " =", - isAbstractProperty ? undefined : "value" + isAbstractProperty ? undefined : "value", ), semi, ]; diff --git a/src/language-js/print/comment.js b/src/language-js/print/comment.js index 88131b0b5..bb20656d1 100644 --- a/src/language-js/print/comment.js +++ b/src/language-js/print/comment.js @@ -38,8 +38,8 @@ function printIndentableBlockComment(comment) { lines.map((line, index) => index === 0 ? line.trimEnd() - : " " + (index < lines.length - 1 ? line.trim() : line.trimStart()) - ) + : " " + (index < lines.length - 1 ? line.trim() : line.trimStart()), + ), ), "*/", ]; diff --git a/src/language-js/print/decorators.js b/src/language-js/print/decorators.js index dd38d5b7e..634c57c4f 100644 --- a/src/language-js/print/decorators.js +++ b/src/language-js/print/decorators.js @@ -68,7 +68,7 @@ function printDecorators(path, options, print) { function hasNewlineBetweenOrAfterDecorators(node, options) { return node.decorators.some((decorator) => - hasNewline(options.originalText, locEnd(decorator)) + hasNewline(options.originalText, locEnd(decorator)), ); } diff --git a/src/language-js/print/estree.js b/src/language-js/print/estree.js index ecafe3b1a..319a25091 100644 --- a/src/language-js/print/estree.js +++ b/src/language-js/print/estree.js @@ -152,8 +152,8 @@ function printEstree(path, options, print, args) { parts.push( group( - indent([softline, printBindExpressionCallee(path, options, print)]) - ) + indent([softline, printBindExpressionCallee(path, options, print)]), + ), ); return parts; @@ -201,13 +201,13 @@ function printEstree(path, options, print, args) { // avoid printing `await (await` on one line const parentAwaitOrBlock = path.findAncestor( (node) => - node.type === "AwaitExpression" || node.type === "BlockStatement" + node.type === "AwaitExpression" || node.type === "BlockStatement", ); if ( parentAwaitOrBlock?.type !== "AwaitExpression" || !startsWithNoLookaheadToken( parentAwaitOrBlock.argument, - (leftmostNode) => leftmostNode === node + (leftmostNode) => leftmostNode === node, ) ) { return group(parts); @@ -303,7 +303,7 @@ function printEstree(path, options, print, args) { if (hasComment(node.argument)) { parts.push( - group(["(", indent([softline, print("argument")]), softline, ")"]) + group(["(", indent([softline, print("argument")]), softline, ")"]), ); } else { parts.push(print("argument")); @@ -353,7 +353,7 @@ function printEstree(path, options, print, args) { ",", hasValue && !isParentForLoop ? hardline : line, p, - ]) + ]), ), ]; @@ -385,7 +385,7 @@ function printEstree(path, options, print, args) { const commentOnOwnLine = hasComment( node.consequent, - CommentCheckFlags.Trailing | CommentCheckFlags.Line + CommentCheckFlags.Trailing | CommentCheckFlags.Line, ) || needsHardlineAfterDanglingComment(node); const elseOnSameLine = node.consequent.type === "BlockStatement" && !commentOnOwnLine; @@ -394,7 +394,7 @@ function printEstree(path, options, print, args) { if (hasComment(node, CommentCheckFlags.Dangling)) { parts.push( printDanglingComments(path, options), - commentOnOwnLine ? hardline : " " + commentOnOwnLine ? hardline : " ", ); } @@ -404,9 +404,9 @@ function printEstree(path, options, print, args) { adjustClause( node.alternate, print("alternate"), - node.alternate.type === "IfStatement" - ) - ) + node.alternate.type === "IfStatement", + ), + ), ); } @@ -490,7 +490,7 @@ function printEstree(path, options, print, args) { "while (", group([indent([softline, print("test")]), softline]), ")", - semi + semi, ); return parts; @@ -532,7 +532,7 @@ function printEstree(path, options, print, args) { (comment.trailing && hasNewline(options.originalText, locStart(comment), { backwards: true, - })) + })), ); const param = print("param"); @@ -566,8 +566,8 @@ function printEstree(path, options, print, args) { print(), !isLast && isNextLineEmpty(node, options) ? hardline : "", ], - "cases" - ) + "cases", + ), ), ]) : "", @@ -586,7 +586,7 @@ function printEstree(path, options, print, args) { } const consequent = node.consequent.filter( - (node) => node.type !== "EmptyStatement" + (node) => node.type !== "EmptyStatement", ); if (consequent.length > 0) { @@ -595,7 +595,7 @@ function printEstree(path, options, print, args) { parts.push( consequent.length === 1 && consequent[0].type === "BlockStatement" ? [" ", cons] - : indent([hardline, cons]) + : indent([hardline, cons]), ); } diff --git a/src/language-js/print/expression-statement.js b/src/language-js/print/expression-statement.js index ad18d12be..bbe9f74f4 100644 --- a/src/language-js/print/expression-statement.js +++ b/src/language-js/print/expression-statement.js @@ -27,14 +27,14 @@ function printExpressionStatement(path, options, print) { hasComment( path.node, CommentCheckFlags.Dangling, - ({ marker }) => marker === markerForIfWithoutBlockAndSameLineComment + ({ marker }) => marker === markerForIfWithoutBlockAndSameLineComment, ) ) { parts.push( " ", printDanglingComments(path, options, { marker: markerForIfWithoutBlockAndSameLineComment, - }) + }), ); } diff --git a/src/language-js/print/function-parameters.js b/src/language-js/print/function-parameters.js index 712ef0faf..a70cb9fdd 100644 --- a/src/language-js/print/function-parameters.js +++ b/src/language-js/print/function-parameters.js @@ -35,7 +35,7 @@ function printFunctionParameters( print, options, expandArg, - printTypeParams + printTypeParams, ) { const functionNode = path.node; const parameters = getFunctionParameters(functionNode); @@ -51,7 +51,7 @@ function printFunctionParameters( filter: (comment) => getNextNonSpaceNonCommentCharacter( options.originalText, - locEnd(comment) + locEnd(comment), ) === ")", }), ")", @@ -148,7 +148,7 @@ function printFunctionParameters( ifBreak( !hasRestParameter(functionNode) && shouldPrintComma(options, "all") ? "," - : "" + : "", ), softline, ")", @@ -275,7 +275,7 @@ function isDecoratedFunction(path) { node.left.property.name === "exports"), (node) => node.type !== "VariableDeclaration" || - (node.kind === "const" && node.declarations.length === 1) + (node.kind === "const" && node.declarations.length === 1), ); } diff --git a/src/language-js/print/function.js b/src/language-js/print/function.js index 5f6574ce9..c668e8207 100644 --- a/src/language-js/print/function.js +++ b/src/language-js/print/function.js @@ -70,7 +70,7 @@ function printFunction(path, print, options, args) { isCallExpression(parent) && (getCallArguments(parent).length > 1 || getFunctionParameters(node).every( - (param) => param.type === "Identifier" && !param.typeAnnotation + (param) => param.type === "Identifier" && !param.typeAnnotation, )) ) { expandArg = true; @@ -88,12 +88,12 @@ function printFunction(path, print, options, args) { path, print, options, - expandArg + expandArg, ); const returnTypeDoc = printReturnType(path, print); const shouldGroupParameters = shouldGroupFunctionParameters( node, - returnTypeDoc + returnTypeDoc, ); parts.push( @@ -103,7 +103,7 @@ function printFunction(path, print, options, args) { returnTypeDoc, ]), node.body ? " " : "", - print("body") + print("body"), ); if (options.semi && (node.declare || !node.body)) { @@ -147,7 +147,7 @@ function printMethod(path, options, print) { parts.push( printPropertyKey(path, options, print), node.optional || node.key.optional ? "?" : "", - node === value ? printMethodValue(path, options, print) : print("value") + node === value ? printMethodValue(path, options, print) : print("value"), ); return parts; @@ -160,7 +160,7 @@ function printMethodValue(path, options, print) { const shouldBreakParameters = shouldBreakFunctionParameters(node); const shouldGroupParameters = shouldGroupFunctionParameters( node, - returnTypeDoc + returnTypeDoc, ); const parts = [ printFunctionTypeParameters(path, options, print), diff --git a/src/language-js/print/interface.js b/src/language-js/print/interface.js index 25e9334cc..4ea09a006 100644 --- a/src/language-js/print/interface.js +++ b/src/language-js/print/interface.js @@ -30,7 +30,7 @@ function printInterface(path, options, print) { node.typeParameters && !hasComment( node.typeParameters, - CommentCheckFlags.Trailing | CommentCheckFlags.Line + CommentCheckFlags.Trailing | CommentCheckFlags.Line, ); if (isNonEmptyArray(node.extends)) { @@ -42,8 +42,8 @@ function printInterface(path, options, print) { : line, "extends ", (node.extends.length === 1 ? identity : indent)( - join([",", line], path.map(print, "extends")) - ) + join([",", line], path.map(print, "extends")), + ), ); } diff --git a/src/language-js/print/jsx.js b/src/language-js/print/jsx.js index cbdfd6ecc..be901851f 100644 --- a/src/language-js/print/jsx.js +++ b/src/language-js/print/jsx.js @@ -136,11 +136,11 @@ function printJsxElementInternal(path, options, print) { options, print, jsxWhitespace, - isFacebookTranslationTag + isFacebookTranslationTag, ); const containsText = node.children.some((child) => - isMeaningfulJsxText(child) + isMeaningfulJsxText(child), ); // We can end up we multiple whitespace elements with empty string @@ -292,7 +292,7 @@ function printJsxChildren( options, print, jsxWhitespace, - isFacebookTranslationTag + isFacebookTranslationTag, ) { const parts = []; path.each(({ node, next }) => { @@ -303,7 +303,7 @@ function printJsxChildren( if (isMeaningfulJsxText(node)) { const words = jsxWhitespaceUtils.split( text, - /* captureWhitespace */ true + /* captureWhitespace */ true, ); // Starts with whitespace @@ -316,8 +316,8 @@ function printJsxChildren( isFacebookTranslationTag, words[1], node, - next - ) + next, + ), ); } else { parts.push(jsxWhitespace); @@ -352,8 +352,8 @@ function printJsxChildren( isFacebookTranslationTag, parts.at(-1), node, - next - ) + next, + ), ); } else { parts.push(jsxWhitespace); @@ -364,8 +364,8 @@ function printJsxChildren( isFacebookTranslationTag, parts.at(-1), node, - next - ) + next, + ), ); } } else if (/\n/.test(text)) { @@ -387,7 +387,12 @@ function printJsxChildren( const trimmed = jsxWhitespaceUtils.trim(rawText(next)); const [firstWord] = jsxWhitespaceUtils.split(trimmed); parts.push( - separatorNoWhitespace(isFacebookTranslationTag, firstWord, node, next) + separatorNoWhitespace( + isFacebookTranslationTag, + firstWord, + node, + next, + ), ); } else { parts.push(hardline); @@ -402,7 +407,7 @@ function separatorNoWhitespace( isFacebookTranslationTag, child, childNode, - nextNode + nextNode, ) { if (isFacebookTranslationTag) { return ""; @@ -422,7 +427,7 @@ function separatorWithWhitespace( isFacebookTranslationTag, child, childNode, - nextNode + nextNode, ) { if (isFacebookTranslationTag) { return hardline; @@ -462,7 +467,7 @@ function maybeWrapJsxElementInParens(path, elem, options) { undefined, (node) => node.type === "ArrowFunctionExpression", isCallExpression, - (node) => node.type === "JSXExpressionContainer" + (node) => node.type === "JSXExpressionContainer", ); const needsParens = pathNeedsParens(path, options); @@ -474,7 +479,7 @@ function maybeWrapJsxElementInParens(path, elem, options) { softline, needsParens ? "" : ifBreak(")"), ], - { shouldBreak } + { shouldBreak }, ); } @@ -501,7 +506,7 @@ function printJsxAttribute(path, options, print) { res = path.call( () => printComments(path, replaceEndOfLine(quote + final + quote), options), - "value" + "value", ); } else { res = print("value"); @@ -592,7 +597,7 @@ function printJsxOpeningElement(path, options, print) { (attr) => attr.value && isStringLiteral(attr.value) && - attr.value.value.includes("\n") + attr.value.value.includes("\n"), ); const attributeLine = @@ -608,7 +613,7 @@ function printJsxOpeningElement(path, options, print) { indent(path.map(() => [attributeLine, print()], "attributes")), ...printEndOfOpeningTag(node, options, nameHasComments), ], - { shouldBreak } + { shouldBreak }, ); } @@ -619,7 +624,7 @@ function printEndOfOpeningTag(node, options, nameHasComments) { const bracketSameLine = shouldPrintBracketSameLine( node, options, - nameHasComments + nameHasComments, ); if (bracketSameLine) { return [">"]; @@ -698,7 +703,7 @@ function printJsxElement(path, options, print) { const elem = printComments( path, printJsxElementInternal(path, options, print), - options + options, ); return maybeWrapJsxElementInParens(path, elem, options); } @@ -729,7 +734,7 @@ function printJsxSpreadAttributeOrChild(path, options, print) { softline, ]; }, - node.type === "JSXSpreadAttribute" ? "argument" : "expression" + node.type === "JSXSpreadAttribute" ? "argument" : "expression", ), "}", ]; diff --git a/src/language-js/print/mapped-type.js b/src/language-js/print/mapped-type.js index 9a6302985..3250a86b7 100644 --- a/src/language-js/print/mapped-type.js +++ b/src/language-js/print/mapped-type.js @@ -59,7 +59,7 @@ function printTypescriptMappedType(path, options, print) { options.originalText, locStart(node), // Ideally, this should be the next token after `{`, but there is no node starts with it. - locStart(node.typeParameter) + locStart(node.typeParameter), ); return group( @@ -81,7 +81,7 @@ function printTypescriptMappedType(path, options, print) { options.bracketSpacing ? line : softline, "}", ], - { shouldBreak } + { shouldBreak }, ); } diff --git a/src/language-js/print/member-chain.js b/src/language-js/print/member-chain.js index f5cece850..c37819831 100644 --- a/src/language-js/print/member-chain.js +++ b/src/language-js/print/member-chain.js @@ -65,7 +65,7 @@ function printMemberChain(path, options, print) { const { originalText } = options; const nextCharIndex = getNextNonSpaceNonCommentCharacterIndex( originalText, - locEnd(node) + locEnd(node), ); const nextChar = originalText.charAt(nextCharIndex); @@ -97,7 +97,7 @@ function printMemberChain(path, options, print) { printFunctionTypeParameters(path, options, print), printCallArguments(path, options, print), ], - options + options, ), shouldInsertEmptyLineAfter(node) ? hardline : "", ], @@ -112,7 +112,7 @@ function printMemberChain(path, options, print) { isMemberExpression(node) ? printMemberLookup(path, options, print) : printBindExpressionCallee(path, options, print), - options + options, ), }); path.call((object) => rec(object), "object"); @@ -380,7 +380,7 @@ function printMemberChain(path, options, print) { nodeHasComment || (callExpressions.length > 2 && callExpressions.some( - (expr) => !expr.arguments.every((arg) => isSimpleCallArgument(arg)) + (expr) => !expr.arguments.every((arg) => isSimpleCallArgument(arg)), )) || printedGroups.slice(0, -1).some(willBreak) || lastGroupWillBreakAndOtherCallsHaveFunctionArguments() diff --git a/src/language-js/print/member.js b/src/language-js/print/member.js index 912e43e66..be078a0fc 100644 --- a/src/language-js/print/member.js +++ b/src/language-js/print/member.js @@ -11,7 +11,8 @@ function printMemberExpression(path, options, print) { const lookupDoc = printMemberLookup(path, options, print); const { node, parent } = path; const firstNonMemberParent = path.findAncestor( - (node) => !(isMemberExpression(node) || node.type === "TSNonNullExpression") + (node) => + !(isMemberExpression(node) || node.type === "TSNonNullExpression"), ); const shouldInline = diff --git a/src/language-js/print/misc.js b/src/language-js/print/misc.js index abfc6d658..3c0785ca3 100644 --- a/src/language-js/print/misc.js +++ b/src/language-js/print/misc.js @@ -40,7 +40,7 @@ function printDefiniteToken(path) { path.match( undefined, (node, name) => - name === "id" && node.type === "VariableDeclarator" && node.definite + name === "id" && node.type === "VariableDeclarator" && node.definite, ) ? "!" : ""; diff --git a/src/language-js/print/module.js b/src/language-js/print/module.js index e76cc2d1a..fdae117fe 100644 --- a/src/language-js/print/module.js +++ b/src/language-js/print/module.js @@ -93,7 +93,7 @@ function printExportDeclaration(path, options, print) { parts.push( printModuleSource(path, options, print), - printImportAttributes(path, options, print) + printImportAttributes(path, options, print), ); } @@ -211,7 +211,7 @@ function printModuleSpecifiers(path, options, print) { ifBreak(shouldPrintComma(options) ? "," : ""), options.bracketSpacing ? line : softline, "}", - ]) + ]), ); } else { parts.push([ @@ -242,7 +242,7 @@ function shouldNotPrintSpecifiers(node, options) { // TODO: check tokens return !/{\s*}/.test( - options.originalText.slice(locStart(node), locStart(source)) + options.originalText.slice(locStart(node), locStart(source)), ); } @@ -303,7 +303,7 @@ function printModuleSpecifier(path, options, print) { return [ printImportOrExportKind( type === "ImportSpecifier" ? node.importKind : node.exportKind, - /* spaceBeforeKind */ false + /* spaceBeforeKind */ false, ), left, left && right ? " as " : "", diff --git a/src/language-js/print/object.js b/src/language-js/print/object.js index d0d273c4c..44ddd3f56 100644 --- a/src/language-js/print/object.js +++ b/src/language-js/print/object.js @@ -59,8 +59,8 @@ function printObject(path, options, print) { printed: print(), loc: locStart(node), }), - field - ) + field, + ), ); if (fields.length > 1) { @@ -91,14 +91,14 @@ function printObject(path, options, print) { (property) => property.value && (property.value.type === "ObjectPattern" || - property.value.type === "ArrayPattern") + property.value.type === "ArrayPattern"), )) || (node.type !== "ObjectPattern" && propsAndLoc.length > 0 && hasNewlineInRange( options.originalText, locStart(node), - propsAndLoc[0].loc + propsAndLoc[0].loc, )); const separator = isFlowInterfaceLikeBody @@ -188,7 +188,7 @@ function printObject(path, options, print) { canHaveTrailingSeparator && (separator !== "," || shouldPrintComma(options)) ? separator - : "" + : "", ), options.bracketSpacing ? line : softline, rightBrace, @@ -203,20 +203,20 @@ function printObject(path, options, print) { if ( path.match( (node) => node.type === "ObjectPattern" && !node.decorators, - shouldHugTheOnlyParameter + shouldHugTheOnlyParameter, ) || (isObjectType(node) && (path.match( undefined, (node, name) => name === "typeAnnotation", (node, name) => name === "typeAnnotation", - shouldHugTheOnlyParameter + shouldHugTheOnlyParameter, ) || path.match( undefined, (node, name) => node.type === "FunctionTypeParam" && name === "typeAnnotation", - shouldHugTheOnlyParameter + shouldHugTheOnlyParameter, ))) || // Assignment printing logic (printAssignment) is responsible // for adding a group if needed @@ -225,7 +225,7 @@ function printObject(path, options, print) { (node) => node.type === "ObjectPattern", (node) => node.type === "AssignmentExpression" || - node.type === "VariableDeclarator" + node.type === "VariableDeclarator", )) ) { return content; diff --git a/src/language-js/print/property.js b/src/language-js/print/property.js index 36f19e55d..da11e053c 100644 --- a/src/language-js/print/property.js +++ b/src/language-js/print/property.js @@ -32,7 +32,7 @@ function printPropertyKey(path, options, print) { !prop.computed && prop.key && isStringLiteral(prop.key) && - !isStringPropSafeToUnquote(prop, options) + !isStringPropSafeToUnquote(prop, options), ); needsQuoteProps.set(parent, objectHasStringProp); } @@ -54,9 +54,9 @@ function printPropertyKey(path, options, print) { // 1.5 -> "1.5" const prop = printString( JSON.stringify( - key.type === "Identifier" ? key.name : key.value.toString() + key.type === "Identifier" ? key.name : key.value.toString(), ), - options + options, ); return path.call((keyPath) => printComments(keyPath, prop, options), "key"); } @@ -74,9 +74,9 @@ function printPropertyKey(path, options, print) { printComments( keyPath, /^\d/.test(key.value) ? printNumber(key.value) : key.value, - options + options, ), - "key" + "key", ); } @@ -95,7 +95,7 @@ function printProperty(path, options, print) { print, printPropertyKey(path, options, print), ":", - "value" + "value", ); } diff --git a/src/language-js/print/semicolon.js b/src/language-js/print/semicolon.js index 72c6dce50..69f26f10b 100644 --- a/src/language-js/print/semicolon.js +++ b/src/language-js/print/semicolon.js @@ -85,7 +85,7 @@ function expressionNeedsASIProtection(path, options) { return path.call( () => expressionNeedsASIProtection(path, options), - ...getLeftSidePathName(node) + ...getLeftSidePathName(node), ); } diff --git a/src/language-js/print/template-literal.js b/src/language-js/print/template-literal.js index c4c868b17..25c1dc3b1 100644 --- a/src/language-js/print/template-literal.js +++ b/src/language-js/print/template-literal.js @@ -46,7 +46,7 @@ function printTemplateLiteral(path, print, options) { printDocToString(doc, { ...options, printWidth: Number.POSITIVE_INFINITY, - }).formatted + }).formatted, ); } @@ -144,7 +144,7 @@ function printJestEachTemplateLiteral(path, options, print) { printWidth: Number.POSITIVE_INFINITY, endOfLine: "lf", }).formatted + - "}" + "}", ); const tableBody = [{ hasLineBreak: false, cells: [] }]; @@ -164,7 +164,7 @@ function printJestEachTemplateLiteral(path, options, print) { const maxColumnCount = Math.max( headerNames.length, - ...tableBody.map((row) => row.cells.length) + ...tableBody.map((row) => row.cells.length), ); const maxColumnWidths = Array.from({ length: maxColumnCount }).fill(0); @@ -176,7 +176,7 @@ function printJestEachTemplateLiteral(path, options, print) { for (const [index, cell] of cells.entries()) { maxColumnWidths[index] = Math.max( maxColumnWidths[index], - getStringWidth(cell) + getStringWidth(cell), ); } } @@ -195,14 +195,14 @@ function printJestEachTemplateLiteral(path, options, print) { row.hasLineBreak ? cell : cell + - " ".repeat(maxColumnWidths[index] - getStringWidth(cell)) - ) - ) - ) + " ".repeat(maxColumnWidths[index] - getStringWidth(cell)), + ), + ), + ), ), ]), hardline, - "`" + "`", ); return parts; } @@ -220,7 +220,7 @@ function printTemplateExpression(path, print) { function printTemplateExpressions(path, print) { return path.map( (path) => printTemplateExpression(path, print), - "expressions" + "expressions", ); } diff --git a/src/language-js/print/ternary.js b/src/language-js/print/ternary.js index c6993d0f0..8fecc3d94 100644 --- a/src/language-js/print/ternary.js +++ b/src/language-js/print/ternary.js @@ -228,7 +228,7 @@ function printTernary(path, options, print) { currentParent && currentParent.type === node.type && testNodePropertyNames.every( - (prop) => currentParent[prop] !== previousParent + (prop) => currentParent[prop] !== previousParent, ) ); const firstNonConditionalParent = currentParent || parent; @@ -271,7 +271,7 @@ function printTernary(path, options, print) { " : ", alternateNode.type === node.type || isNil(alternateNode) ? print(alternateNodePropertyName) - : wrap(print(alternateNodePropertyName)) + : wrap(print(alternateNodePropertyName)), ); } else { // normal mode @@ -294,7 +294,7 @@ function printTernary(path, options, print) { ? part : options.useTabs ? dedent(indent(part)) - : align(Math.max(0, options.tabWidth - 2), part) + : align(Math.max(0, options.tabWidth - 2), part), ); } @@ -313,9 +313,9 @@ function printTernary(path, options, print) { hasNewlineInRange( options.originalText, locStart(comment), - locEnd(comment) - ) - ) + locEnd(comment), + ), + ), ); const maybeGroup = (doc) => parent === firstNonConditionalParent diff --git a/src/language-js/print/type-annotation.js b/src/language-js/print/type-annotation.js index 9553371d1..57620bf6c 100644 --- a/src/language-js/print/type-annotation.js +++ b/src/language-js/print/type-annotation.js @@ -44,7 +44,7 @@ function shouldHugType(node) { node.type === "VoidTypeAnnotation" || node.type === "TSVoidKeyword" || node.type === "NullLiteralTypeAnnotation" || - node.type === "TSNullKeyword" + node.type === "TSNullKeyword", ).length; const hasObject = node.types.some( @@ -53,7 +53,7 @@ function shouldHugType(node) { node.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}> node.type === "GenericTypeAnnotation" || - node.type === "TSTypeReference" + node.type === "TSTypeReference", ); const hasComments = node.types.some((node) => hasComment(node)); @@ -141,7 +141,7 @@ function printIntersectionType(path, options, print) { } return [" & ", index > 1 ? indent(doc) : doc]; - }, "types") + }, "types"), ); } @@ -283,7 +283,7 @@ function printFunctionType(path, options, print) { print, options, /* expandArg */ false, - /* printTypeParams */ true + /* printTypeParams */ true, ); const returnTypeDoc = []; @@ -292,15 +292,15 @@ function printFunctionType(path, options, print) { if (node.type === "FunctionTypeAnnotation") { returnTypeDoc.push( isFlowArrowFunctionTypeAnnotation(path) ? " => " : ": ", - print("returnType") + print("returnType"), ); } else { returnTypeDoc.push( printTypeAnnotationProperty( path, print, - node.returnType ? "returnType" : "typeAnnotation" - ) + node.returnType ? "returnType" : "typeAnnotation", + ), ); } @@ -388,7 +388,7 @@ const typeAnnotationNodesCheckedLeadingComments = new WeakSet(); function printTypeAnnotationProperty( path, print, - propertyName = "typeAnnotation" + propertyName = "typeAnnotation", ) { const { node: { [propertyName]: typeAnnotation }, @@ -429,7 +429,7 @@ const getTypeAnnotationFirstToken = (path) => { (node) => node.type === "TSTypeAnnotation", (node, key) => (key === "returnType" || key === "typeAnnotation") && - (node.type === "TSFunctionType" || node.type === "TSConstructorType") + (node.type === "TSFunctionType" || node.type === "TSConstructorType"), ) ) { return "=>"; @@ -443,7 +443,7 @@ const getTypeAnnotationFirstToken = (path) => { key === "typeAnnotation" && (node.type === "TSJSDocNullableType" || node.type === "TSJSDocNonNullableType" || - node.type === "TSTypePredicate") + node.type === "TSTypePredicate"), ) || /* Flow @@ -456,7 +456,7 @@ const getTypeAnnotationFirstToken = (path) => { path.match( (node) => node.type === "TypeAnnotation", (node, key) => key === "typeAnnotation" && node.type === "Identifier", - (node, key) => key === "id" && node.type === "DeclareFunction" + (node, key) => key === "id" && node.type === "DeclareFunction", ) || /* Flow @@ -471,7 +471,7 @@ const getTypeAnnotationFirstToken = (path) => { (node, key) => key === "bound" && node.type === "TypeParameter" && - node.usesExtendsBound + node.usesExtendsBound, ) ) { return ""; @@ -494,9 +494,9 @@ function printTypeAnnotation(path, options, print) { if (!typeAnnotationNodesCheckedLeadingComments.has(node)) { throw Object.assign( new Error( - `'${node.type}' should be printed by '${printTypeAnnotationProperty.name}' function.` + `'${node.type}' should be printed by '${printTypeAnnotationProperty.name}' function.`, ), - { parentNode: path.parent, propertyName: path.key } + { parentNode: path.parent, propertyName: path.key }, ); } } diff --git a/src/language-js/print/type-parameters.js b/src/language-js/print/type-parameters.js index 17555a688..688b6ec55 100644 --- a/src/language-js/print/type-parameters.js +++ b/src/language-js/print/type-parameters.js @@ -63,7 +63,7 @@ function printTypeParameters(path, options, print, paramsKey) { undefined, (node, name) => name === "typeAnnotation", (node) => node.type === "Identifier", - isArrowFunctionVariableDeclarator + isArrowFunctionVariableDeclarator, ); const shouldInline = @@ -100,7 +100,7 @@ function printTypeParameters(path, options, print, paramsKey) { softline, ">", ], - { id: getTypeParametersGroupId(node) } + { id: getTypeParametersGroupId(node) }, ); } @@ -133,7 +133,7 @@ function printTypeParameter(path, options, print) { if (parent.readonly) { parts.push( printTypeScriptMappedTypeModifier(parent.readonly, "readonly"), - " " + " ", ); } parts.push("[", name); @@ -143,7 +143,7 @@ function printTypeParameter(path, options, print) { if (parent.nameType) { parts.push( " as ", - path.callParent(() => print("nameType")) + path.callParent(() => print("nameType")), ); } parts.push("]"); @@ -178,7 +178,7 @@ function printTypeParameter(path, options, print) { " extends", group(indent(line), { id: groupId }), lineSuffixBoundary, - indentIfBreak(print("constraint"), { groupId }) + indentIfBreak(print("constraint"), { groupId }), ); } diff --git a/src/language-js/print/typescript.js b/src/language-js/print/typescript.js index 90b970c61..594b9cbb4 100644 --- a/src/language-js/print/typescript.js +++ b/src/language-js/print/typescript.js @@ -243,7 +243,7 @@ function printTypescript(path, options, print) { node.computed ? "[" : "", print("key"), node.computed ? "]" : "", - printOptionalToken(path) + printOptionalToken(path), ); const parametersDoc = printFunctionParameters( @@ -251,7 +251,7 @@ function printTypescript(path, options, print) { print, options, /* expandArg */ false, - /* printTypeParams */ true + /* printTypeParams */ true, ); const returnTypePropertyName = node.returnType @@ -263,7 +263,7 @@ function printTypescript(path, options, print) { : ""; const shouldGroupParameters = shouldGroupFunctionParameters( node, - returnTypeDoc + returnTypeDoc, ); parts.push(shouldGroupParameters ? group(parametersDoc) : parametersDoc); @@ -318,7 +318,7 @@ function printTypescript(path, options, print) { // TODO: Use `node.kind` when babel update AST (isStringLiteral(node.id) || /(?:^|\s)module(?:\s|$)/.test( - options.originalText.slice(locStart(node), locStart(node.id)) + options.originalText.slice(locStart(node), locStart(node.id)), ) ? "module" : "namespace"); diff --git a/src/language-js/traverse/visitor-keys.evaluate.js b/src/language-js/traverse/visitor-keys.evaluate.js index c3ef07ad3..4ba755060 100644 --- a/src/language-js/traverse/visitor-keys.evaluate.js +++ b/src/language-js/traverse/visitor-keys.evaluate.js @@ -65,13 +65,13 @@ const visitorKeys = Object.fromEntries( flowVisitorKeys, angularVisitorKeys, additionalVisitorKeys, - ]) + ]), ).map(([type, keys]) => [ type, excludeKeys[type] ? keys.filter((key) => !excludeKeys[type].includes(key)) : keys, - ]) + ]), ); // Unsupported diff --git a/src/language-js/utils/index.js b/src/language-js/utils/index.js index a75d6f8ce..f582d2e5b 100644 --- a/src/language-js/utils/index.js +++ b/src/language-js/utils/index.js @@ -496,7 +496,7 @@ function hasLeadingOwnLineComment(text, node) { } return hasComment(node, CommentCheckFlags.Leading, (comment) => - hasNewline(text, locEnd(comment)) + hasNewline(text, locEnd(comment)), ); } @@ -584,7 +584,7 @@ function needsHardlineAfterDanglingComment(node) { return false; } const lastDanglingComment = getComments(node, CommentCheckFlags.Dangling).at( - -1 + -1, ); return lastDanglingComment && !isBlockComment(lastDanglingComment); } @@ -681,7 +681,8 @@ function isSimpleCallArgument(node, depth = 2) { if (isObjectOrRecordExpression(node)) { return node.properties.every( - (p) => !p.computed && (p.shorthand || (p.value && isChildSimple(p.value))) + (p) => + !p.computed && (p.shorthand || (p.value && isChildSimple(p.value))), ); } @@ -875,8 +876,8 @@ const PRECEDENCE = new Map( ["*", "/", "%"], ["**"], ].flatMap((operators, index) => - operators.map((operator) => [operator, index]) - ) + operators.map((operator) => [operator, index]), + ), ); function getPrecedence(operator) { return PRECEDENCE.get(operator); @@ -1097,7 +1098,7 @@ function isObjectProperty(node) { * This is used as a marker for dangling comments. */ const markerForIfWithoutBlockAndSameLineComment = Symbol( - "ifWithoutBlockAndSameLineComment" + "ifWithoutBlockAndSameLineComment", ); const isTSTypeExpression = createTypeCheckFunction([ diff --git a/src/language-js/utils/is-node-matches.js b/src/language-js/utils/is-node-matches.js index 568c7c735..5c5ebb1d3 100644 --- a/src/language-js/utils/is-node-matches.js +++ b/src/language-js/utils/is-node-matches.js @@ -43,7 +43,7 @@ Check if node matches any object name or key path. */ function isNodeMatches(node, nameOrPaths) { return nameOrPaths.some((nameOrPath) => - isNodeMatchesNameOrPath(node, nameOrPath) + isNodeMatchesNameOrPath(node, nameOrPath), ); } diff --git a/src/language-json/parser-json.js b/src/language-json/parser-json.js index 5533a9518..b49d5cf61 100644 --- a/src/language-json/parser-json.js +++ b/src/language-json/parser-json.js @@ -46,7 +46,7 @@ function createJsonError(node, description) { ({ line, column }) => ({ line, column: column + 1, - }) + }), ); return createError(`${description} is not allowed in JSON.`, { loc: { start, end }, @@ -101,7 +101,7 @@ function assertJsonNode(node) { throw createJsonError( argument, - `Operator '${operator}' before '${argument.type}'` + `Operator '${operator}' before '${argument.type}'`, ); } case "Identifier": @@ -120,7 +120,7 @@ function assertJsonNode(node) { if (isNonEmptyArray(node.expressions)) { throw createJsonError( node.expressions[0], - "'TemplateLiteral' with expression" + "'TemplateLiteral' with expression", ); } diff --git a/src/language-json/printer-estree-json.js b/src/language-json/printer-estree-json.js index cf139dce0..e16e962b0 100644 --- a/src/language-json/printer-estree-json.js +++ b/src/language-json/printer-estree-json.js @@ -13,7 +13,7 @@ function genericPrint(path, options, print) { const printed = path.map( () => (path.node === null ? "null" : print()), - "elements" + "elements", ); return [ diff --git a/src/language-markdown/constants.evaluate.js b/src/language-markdown/constants.evaluate.js index bdab8280e..0a35fc728 100644 --- a/src/language-markdown/constants.evaluate.js +++ b/src/language-markdown/constants.evaluate.js @@ -14,7 +14,7 @@ const cjkPattern = `(?:${cjkRegex() "Modifier_Symbol", "Nonspacing_Mark", ], - }) + }), ) .toString()})(?:${unicodeRegex({ Block: ["Variation_Selectors", "Variation_Selectors_Supplement"], diff --git a/src/language-markdown/embed.js b/src/language-markdown/embed.js index 763fa629f..2c4147639 100644 --- a/src/language-markdown/embed.js +++ b/src/language-markdown/embed.js @@ -14,7 +14,7 @@ function embed(path, options) { return async (textToDoc) => { const styleUnit = options.__inJsTemplate ? "~" : "`"; const style = styleUnit.repeat( - Math.max(3, getMaxContinuousCount(node.value, styleUnit) + 1) + Math.max(3, getMaxContinuousCount(node.value, styleUnit) + 1), ); const newOptions = { parser }; if (node.lang === "tsx") { @@ -23,7 +23,7 @@ function embed(path, options) { const doc = await textToDoc( getFencedCodeBlockValue(node, options.originalText), - newOptions + newOptions, ); return markAsRoot([ diff --git a/src/language-markdown/pragma.js b/src/language-markdown/pragma.js index 3cf26dde5..0a5c48c82 100644 --- a/src/language-markdown/pragma.js +++ b/src/language-markdown/pragma.js @@ -11,7 +11,7 @@ function startWithPragma(text) { `{\\s*\\/\\*\\s*${pragma}\\s*\\*\\/\\s*}`, ``, ].join("|"), - "m" + "m", ); const matched = text.match(regex); return matched?.index === 0; diff --git a/src/language-markdown/print-preprocess.js b/src/language-markdown/print-preprocess.js index 4446a2a80..ff30c460a 100644 --- a/src/language-markdown/print-preprocess.js +++ b/src/language-markdown/print-preprocess.js @@ -24,9 +24,9 @@ function restoreUnescapedCharacter(ast, options) { ...node, value: options.originalText.slice( node.position.start.offset, - node.position.end.offset + node.position.end.offset, ), - } + }, ); } @@ -59,7 +59,7 @@ function mergeContinuousTexts(ast) { start: prevNode.position.start, end: node.position.end, }, - }) + }), ); } @@ -95,8 +95,8 @@ function transformIndentedCodeblockAndMarkItsParentList(ast, options) { const isIndented = /^\n?(?: {4,}|\t)/.test( options.originalText.slice( node.position.start.offset, - node.position.end.offset - ) + node.position.end.offset, + ), ); node.isIndented = isIndented; diff --git a/src/language-markdown/print-whitespace.js b/src/language-markdown/print-whitespace.js index 00172b689..cfe799f5b 100644 --- a/src/language-markdown/print-whitespace.js +++ b/src/language-markdown/print-whitespace.js @@ -34,7 +34,7 @@ const SINGLE_LINE_NODE_TYPES = new Set([ * `"檜原村(ひ\nのはらむら)"` */ const noBreakAfter = new Set( - "$(£¥·'\"〈《「『【〔〖〝﹙﹛$([{£¥[{‵︴︵︷︹︻︽︿﹁﹃﹏〘⦅«" + "$(£¥·'\"〈《「『【〔〖〝﹙﹛$([{£¥[{‵︴︵︷︹︻︽︿﹁﹃﹏〘⦅«", ); /** @@ -47,7 +47,7 @@ const noBreakAfter = new Set( * `"檜原村(ひのはらむら)\n以外には、"` */ const noBreakBefore = new Set( - "!%),.:;?]}¢°·'\"†‡›℃∶、。〃〆〕〗〞﹚﹜!"%'),.:;?]}~–—•〉》」︰︱︲︳﹐﹑﹒﹓﹔﹕﹖﹘︶︸︺︼︾﹀﹂﹗|、』】〙〟⦆»ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻‐゠〜~‼⁇⁈⁉・" + "!%),.:;?]}¢°·'\"†‡›℃∶、。〃〆〕〗〞﹚﹜!"%'),.:;?]}~–—•〉》」︰︱︲︳﹐﹑﹒﹓﹔﹕﹖﹘︶︸︺︼︾﹀﹂﹗|、』】〙〟⦆»ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻‐゠〜~‼⁇⁈⁉・", ); /** @@ -55,7 +55,7 @@ const noBreakBefore = new Set( * space. Includes only ASCII punctuation marks for now. */ const lineBreakBetweenTheseAndCJConvertsToSpace = new Set( - "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" + "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", ); /** diff --git a/src/language-markdown/printer-markdown.js b/src/language-markdown/printer-markdown.js index 42c0032db..d9d646229 100644 --- a/src/language-markdown/printer-markdown.js +++ b/src/language-markdown/printer-markdown.js @@ -55,12 +55,12 @@ function genericPrint(path, options, print) { return splitText( options.originalText.slice( node.position.start.offset, - node.position.end.offset - ) + node.position.end.offset, + ), ).map((node) => node.type === "word" ? node.value - : printWhitespace(path, node.value, options.proseWrap, true) + : printWhitespace(path, node.value, options.proseWrap, true), ); } @@ -68,7 +68,7 @@ function genericPrint(path, options, print) { case "front-matter": return options.originalText.slice( node.position.start.offset, - node.position.end.offset + node.position.end.offset, ); case "root": /* c8 ignore next 3 */ @@ -91,13 +91,13 @@ function genericPrint(path, options, print) { `(^|${punctuationPattern})(_+)`, `(_+)(${punctuationPattern}|$)`, ].join("|"), - "g" + "g", ), (_, text1, underscore1, underscore2, text2) => (underscore1 ? `${text1}${underscore1}` : `${underscore2}${text2}` - ).replaceAll("_", "\\_") + ).replaceAll("_", "\\_"), ); // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis const isFirstSentence = (node, name, index) => @@ -112,12 +112,12 @@ function genericPrint(path, options, print) { undefined, isFirstSentence, (node, name, index) => node.type === "emphasis" && index === 0, - isLastChildAutolink + isLastChildAutolink, )) ) { // backslash is parsed as part of autolinks, so we need to remove it escapedValue = escapedValue.replace(/^(\\?[*_])+/, (prefix) => - prefix.replaceAll("\\", "") + prefix.replaceAll("\\", ""), ); } @@ -193,7 +193,7 @@ function genericPrint(path, options, print) { node.url.startsWith(mailto) && options.originalText.slice( node.position.start.offset + 1, - node.position.start.offset + 1 + mailto.length + node.position.start.offset + 1 + mailto.length, ) !== mailto ? node.url.slice(mailto.length) : node.url; @@ -211,7 +211,7 @@ function genericPrint(path, options, print) { default: return options.originalText.slice( node.position.start.offset, - node.position.end.offset + node.position.end.offset, ); } case "image": @@ -243,7 +243,7 @@ function genericPrint(path, options, print) { // fenced code block const styleUnit = options.__inJsTemplate ? "~" : "`"; const style = styleUnit.repeat( - Math.max(3, getMaxContinuousCount(node.value, styleUnit) + 1) + Math.max(3, getMaxContinuousCount(node.value, styleUnit) + 1), ); return [ style, @@ -252,7 +252,7 @@ function genericPrint(path, options, print) { hardline, replaceEndOfLine( getFencedCodeBlockValue(node, options.originalText), - hardline + hardline, ), hardline, style, @@ -267,7 +267,7 @@ function genericPrint(path, options, print) { return replaceEndOfLine( value, // @ts-expect-error - isHtmlComment ? hardline : markAsRoot(literalline) + isHtmlComment ? hardline : markAsRoot(literalline), ); } case "list": { @@ -275,7 +275,7 @@ function genericPrint(path, options, print) { const isGitDiffFriendlyOrderedList = hasGitDiffFriendlyOrderedList( node, - options + options, ); return printChildren(path, options, print, { @@ -296,7 +296,7 @@ function genericPrint(path, options, print) { prefix, align( " ".repeat(prefix.length), - printListItem(childPath, options, print, prefix) + printListItem(childPath, options, print, prefix), ), ]; @@ -328,7 +328,7 @@ function genericPrint(path, options, print) { } const nthSiblingIndex = getNthListSiblingIndex( ancestors[counter], - ancestors[counter + 1] + ancestors[counter + 1], ); return nthSiblingIndex % 2 === 0 ? "***" : "---"; } @@ -395,7 +395,7 @@ function genericPrint(path, options, print) { printChildren(path, options, print, { processor: ({ isFirst }) => isFirst ? group([softline, print()]) : print(), - }) + }), ), path.next?.type === "footnoteDefinition" ? softline : "", ]), @@ -453,7 +453,7 @@ function printListItem(path, options, print, listPrefix) { } const alignment = " ".repeat( - clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block + clamp(options.tabWidth - listPrefix.length, 0, 3), // 4+ will cause indented code block ); return [alignment, align(alignment, print())]; }, @@ -466,7 +466,7 @@ function alignListPrefix(prefix, options) { return ( prefix + " ".repeat( - additionalSpaces >= 4 ? 0 : additionalSpaces // 4+ will cause indented code block + additionalSpaces >= 4 ? 0 : additionalSpaces, // 4+ will cause indented code block ) ); @@ -480,7 +480,7 @@ function getNthListSiblingIndex(node, parentNode) { return getNthSiblingIndex( node, parentNode, - (siblingNode) => siblingNode.ordered === node.ordered + (siblingNode) => siblingNode.ordered === node.ordered, ); } @@ -512,11 +512,11 @@ function printTable(path, options, print) { const width = getStringWidth(text); columnMaxWidths[columnIndex] = Math.max( columnMaxWidths[columnIndex] || 3, // minimum width = 3 (---, :--, :-:, --:) - width + width, ); return { text, width }; }, "children"), - "children" + "children", ); const alignedTable = printTableContents(/* isCompact */ false); @@ -537,8 +537,8 @@ function printTable(path, options, print) { hardlineWithoutBreakParent, contents .slice(1) - .map((rowContents) => printRow(rowContents, isCompact)) - ) + .map((rowContents) => printRow(rowContents, isCompact)), + ), ); } return join(hardlineWithoutBreakParent, parts); @@ -618,7 +618,7 @@ function printRoot(path, options, print) { printIgnoreComment(children[ignoreRange.start.index]), options.originalText.slice( ignoreRange.start.offset, - ignoreRange.end.offset + ignoreRange.end.offset, ), printIgnoreComment(children[ignoreRange.end.index]), ]; @@ -771,7 +771,7 @@ function shouldPrePrintTripleHardline({ node, previous }) { function shouldRemainTheSameContent(path) { const node = path.findAncestor( - (node) => node.type === "linkReference" || node.type === "imageReference" + (node) => node.type === "linkReference" || node.type === "imageReference", ); return ( node && (node.type !== "linkReference" || node.referenceType !== "full") diff --git a/src/language-markdown/utils.js b/src/language-markdown/utils.js index 495d073a2..a65400da2 100644 --- a/src/language-markdown/utils.js +++ b/src/language-markdown/utils.js @@ -125,7 +125,7 @@ function splitText(text) { kind: kRegex.test(innerToken) ? KIND_K_LETTER : KIND_CJ_LETTER, hasLeadingPunctuation: false, hasTrailingPunctuation: false, - } + }, ); } } @@ -135,7 +135,7 @@ function splitText(text) { for (let i = 1; i < nodes.length; i++) { assert( !(nodes[i - 1].type === "whitespace" && nodes[i].type === "whitespace"), - "splitText should not create consecutive whitespace nodes" + "splitText should not create consecutive whitespace nodes", ); } } @@ -167,7 +167,7 @@ function getOrderedListItemInfo(orderListItem, originalText) { const [, numberText, marker, leadingSpaces] = originalText .slice( orderListItem.position.start.offset, - orderListItem.position.end.offset + orderListItem.position.end.offset, ) .match(/^\s*(\d+)(\.|\))(\s*)/); @@ -184,16 +184,16 @@ function hasGitDiffFriendlyOrderedList(node, options) { } const firstNumber = Number( - getOrderedListItemInfo(node.children[0], options.originalText).numberText + getOrderedListItemInfo(node.children[0], options.originalText).numberText, ); const secondNumber = Number( - getOrderedListItemInfo(node.children[1], options.originalText).numberText + getOrderedListItemInfo(node.children[1], options.originalText).numberText, ); if (firstNumber === 0 && node.children.length > 2) { const thirdNumber = Number( - getOrderedListItemInfo(node.children[2], options.originalText).numberText + getOrderedListItemInfo(node.children[2], options.originalText).numberText, ); return secondNumber === 1 && thirdNumber === 1; @@ -222,7 +222,7 @@ function mapAst(ast, handler) { const newNode = { ...handler(node, index, parentStack) }; if (newNode.children) { newNode.children = newNode.children.map((child, index) => - preorder(child, index, [newNode, ...parentStack]) + preorder(child, index, [newNode, ...parentStack]), ); } diff --git a/src/language-yaml/print/block.js b/src/language-yaml/print/block.js index 056d4752d..55ad31b4f 100644 --- a/src/language-yaml/print/block.js +++ b/src/language-yaml/print/block.js @@ -20,7 +20,7 @@ import { alignWithSpaces } from "./misc.js"; function printBlock(path, print, options) { const { node } = path; const parentIndent = path.ancestors.filter( - (node) => node.type === "sequence" || node.type === "mapping" + (node) => node.type === "sequence" || node.type === "mapping", ).length; const isLastDescendant = isLastDescendantNode(path); /** @type {Doc[]} */ @@ -51,11 +51,11 @@ function printBlock(path, print, options) { contentsParts.push(fill(join(line, lineWords))); if (index !== lineContents.length - 1) { contentsParts.push( - lineWords.length === 0 ? hardline : markAsRoot(literalline) + lineWords.length === 0 ? hardline : markAsRoot(literalline), ); } else if (node.chomping === "keep" && isLastDescendant) { contentsParts.push( - dedentToRoot(lineWords.length === 0 ? hardline : literalline) + dedentToRoot(lineWords.length === 0 ? hardline : literalline), ); } } @@ -64,8 +64,8 @@ function printBlock(path, print, options) { } else { parts.push( dedentToRoot( - alignWithSpaces(node.indent - 1 + parentIndent, contentsParts) - ) + alignWithSpaces(node.indent - 1 + parentIndent, contentsParts), + ), ); } diff --git a/src/language-yaml/print/flow-mapping-sequence.js b/src/language-yaml/print/flow-mapping-sequence.js index 591f85b59..a2b215824 100644 --- a/src/language-yaml/print/flow-mapping-sequence.js +++ b/src/language-yaml/print/flow-mapping-sequence.js @@ -54,7 +54,7 @@ function printChildren(path, print, options) { : "", ], ], - "children" + "children", ); } diff --git a/src/language-yaml/print/mapping-item.js b/src/language-yaml/print/mapping-item.js index 687a0aac5..f3858702c 100644 --- a/src/language-yaml/print/mapping-item.js +++ b/src/language-yaml/print/mapping-item.js @@ -116,7 +116,7 @@ function printMappingItem(path, print, options) { implicitMappingValueParts.push(printedValue); const implicitMappingValue = alignWithSpaces( options.tabWidth, - implicitMappingValueParts + implicitMappingValueParts, ); // If a key is definitely single-line, forcibly use implicit style to avoid edge cases (very long @@ -166,8 +166,8 @@ function isAbsolutelyPrintedAsSingleLineNode(node, options) { /\\$/m.test( options.originalText.slice( node.position.start.offset, - node.position.end.offset - ) + node.position.end.offset, + ), ) ) { return false; diff --git a/src/language-yaml/printer-yaml.js b/src/language-yaml/printer-yaml.js index 0168c26ac..2bbf5717f 100644 --- a/src/language-yaml/printer-yaml.js +++ b/src/language-yaml/printer-yaml.js @@ -100,8 +100,8 @@ function genericPrint(path, options, print) { replaceEndOfLine( options.originalText .slice(node.position.start.offset, node.position.end.offset) - .trimEnd() - ) + .trimEnd(), + ), ); } else { parts.push(group(printNode(path, options, print))); @@ -117,7 +117,7 @@ function genericPrint(path, options, print) { ? "" : breakParent, print("trailingComment"), - ]) + ]), ); } @@ -134,10 +134,10 @@ function genericPrint(path, options, print) { : "", print(), ], - "endComments" - ) + "endComments", + ), ), - ]) + ]), ); } parts.push(nextEmptyLine); @@ -230,7 +230,7 @@ function printNode(path, options, print) { case "tag": return options.originalText.slice( node.position.start.offset, - node.position.end.offset + node.position.end.offset, ); case "anchor": return ["&", node.value]; @@ -239,9 +239,9 @@ function printNode(path, options, print) { node.type, options.originalText.slice( node.position.start.offset, - node.position.end.offset + node.position.end.offset, ), - options + options, ); case "quoteDouble": case "quoteSingle": { @@ -250,7 +250,7 @@ function printNode(path, options, print) { const raw = options.originalText.slice( node.position.start.offset + 1, - node.position.end.offset - 1 + node.position.end.offset - 1, ); if ( @@ -279,7 +279,7 @@ function printNode(path, options, print) { .replaceAll('\\"', doubleQuote) .replaceAll("'", singleQuote.repeat(2)) : raw, - options + options, ), singleQuote, ]; @@ -294,7 +294,7 @@ function printNode(path, options, print) { ? // single quote needs to be escaped by 2 single quotes in quoteSingle raw.replaceAll("''", singleQuote) : raw, - options + options, ), doubleQuote, ]; @@ -366,7 +366,7 @@ function shouldPrintDocumentHeadEndMarker(path, options) { */ (path.isFirst && /---(?:\s|$)/.test( - options.originalText.slice(locStart(document), locStart(document) + 4) + options.originalText.slice(locStart(document), locStart(document) + 4), )) || /** * %DIRECTIVE @@ -398,7 +398,7 @@ function printFlowScalarContent(nodeType, content, options) { const lineContents = getFlowScalarLineContents(nodeType, content, options); return join( hardline, - lineContents.map((lineContentWords) => fill(join(line, lineContentWords))) + lineContents.map((lineContentWords) => fill(join(line, lineContentWords))), ); } diff --git a/src/language-yaml/utils.js b/src/language-yaml/utils.js index 7706b5657..c2f8c1e49 100644 --- a/src/language-yaml/utils.js +++ b/src/language-yaml/utils.js @@ -16,11 +16,11 @@ function mapNode(node, callback, parent) { ? { ...node, children: node.children.map((childNode) => - mapNode(childNode, callback, node) + mapNode(childNode, callback, node), ), } : node, - parent + parent, ); } @@ -185,18 +185,18 @@ function getFlowScalarLineContents(nodeType, content, options) { ? lineContent.trim() : index === 0 ? lineContent.trimEnd() - : lineContent.trimStart() + : lineContent.trimStart(), ); if (options.proseWrap === "preserve") { return rawLineContents.map((lineContent) => - lineContent.length === 0 ? [] : [lineContent] + lineContent.length === 0 ? [] : [lineContent], ); } return rawLineContents .map((lineContent) => - lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent) + lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent), ) .reduce( (reduced, lineContentWords, index) => @@ -209,18 +209,18 @@ function getFlowScalarLineContents(nodeType, content, options) { ) ? [...reduced.slice(0, -1), [...reduced.at(-1), ...lineContentWords]] : [...reduced, lineContentWords], - [] + [], ) .map((lineContentWords) => options.proseWrap === "never" ? [lineContentWords.join(" ")] - : lineContentWords + : lineContentWords, ); } function getBlockValueLineContents( node, - { parentIndent, isLastDescendant, options } + { parentIndent, isLastDescendant, options }, ) { const content = node.position.start.line === node.position.end.line @@ -247,15 +247,15 @@ function getBlockValueLineContents( if (options.proseWrap === "preserve" || node.type === "blockLiteral") { return removeUnnecessaryTrailingNewlines( rawLineContents.map((lineContent) => - lineContent.length === 0 ? [] : [lineContent] - ) + lineContent.length === 0 ? [] : [lineContent], + ), ); } return removeUnnecessaryTrailingNewlines( rawLineContents .map((lineContent) => - lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent) + lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent), ) .reduce( (reduced, lineContentWords, index) => @@ -269,7 +269,7 @@ function getBlockValueLineContents( [...reduced.at(-1), ...lineContentWords], ] : [...reduced, lineContentWords], - [] + [], ) .map((lineContentWords) => lineContentWords.reduce( @@ -278,14 +278,14 @@ function getBlockValueLineContents( reduced.length > 0 && /\s$/.test(reduced.at(-1)) ? [...reduced.slice(0, -1), reduced.at(-1) + " " + word] : [...reduced, word], - [] - ) + [], + ), ) .map((lineContentWords) => options.proseWrap === "never" ? [lineContentWords.join(" ")] - : lineContentWords - ) + : lineContentWords, + ), ); function removeUnnecessaryTrailingNewlines(lineContents) { diff --git a/src/language-yaml/visitor-keys.js b/src/language-yaml/visitor-keys.js index 2778e66dd..d30a060e3 100644 --- a/src/language-yaml/visitor-keys.js +++ b/src/language-yaml/visitor-keys.js @@ -36,7 +36,7 @@ const visitorKeys = Object.fromEntries( "trailingComment", "endComments", ], - ]) + ]), ); export default visitorKeys; diff --git a/src/main/ast-to-doc.js b/src/main/ast-to-doc.js index ab6a1eeca..90973496c 100644 --- a/src/main/ast-to-doc.js +++ b/src/main/ast-to-doc.js @@ -46,7 +46,7 @@ async function printAstToDoc(ast, options) { options, mainPrint, undefined, - embeds + embeds, ); ensureAllCommentsPrinted(options); diff --git a/src/main/comments/attach.js b/src/main/comments/attach.js index bea073e7e..6e22482c8 100644 --- a/src/main/comments/attach.js +++ b/src/main/comments/attach.js @@ -40,12 +40,12 @@ function getSortedChildNodes(node, options) { }), ] ).flatMap((node) => - canAttachComment(node) ? [node] : getSortedChildNodes(node, options) + canAttachComment(node) ? [node] : getSortedChildNodes(node, options), ); // Sort by `start` location first, then `end` location childNodes.sort( (nodeA, nodeB) => - locStart(nodeA) - locStart(nodeB) || locEnd(nodeA) - locEnd(nodeB) + locStart(nodeA) - locStart(nodeB) || locEnd(nodeA) - locEnd(nodeB), ); childNodesCache.set(node, childNodes); @@ -109,7 +109,7 @@ function decorateComment(node, comment, options, enclosingNode) { const commentIndex = findExpressionIndexForComment( quasis, comment, - options + options, ); if ( diff --git a/src/main/comments/print.js b/src/main/comments/print.js index 65f598dc4..f3a8324cf 100644 --- a/src/main/comments/print.js +++ b/src/main/comments/print.js @@ -51,7 +51,7 @@ function printLeadingComment(path, options) { const index = skipNewline( originalText, - skipSpaces(originalText, locEnd(comment)) + skipSpaces(originalText, locEnd(comment)), ); if (index !== false && hasNewline(originalText, index)) { @@ -86,7 +86,7 @@ function printTrailingComment(path, options, previousComment) { const isLineBeforeEmpty = isPreviousLineEmpty( originalText, - locStart(comment) + locStart(comment), ); return { @@ -119,7 +119,7 @@ function printTrailingComment(path, options, previousComment) { function printDanglingComments( path, options, - danglingCommentsPrintOptions = {} + danglingCommentsPrintOptions = {}, ) { const { node } = path; @@ -163,7 +163,7 @@ function printCommentsSeparately(path, options) { const ignored = options[Symbol.for("printedComments")]; const comments = (value.comments || []).filter( - (comment) => !ignored.has(comment) + (comment) => !ignored.has(comment), ); if (comments.length === 0) { @@ -186,7 +186,7 @@ function printCommentsSeparately(path, options) { printedTrailingComment = printTrailingComment( path, options, - printedTrailingComment + printedTrailingComment, ); trailingParts.push(printedTrailingComment.doc); } @@ -214,7 +214,7 @@ function ensureAllCommentsPrinted(options) { throw new Error( 'Comment "' + comment.value.trim() + - '" was not printed. Please report this error!' + '" was not printed. Please report this error!', ); } delete comment.printed; diff --git a/src/main/comments/utils.js b/src/main/comments/utils.js index db3b4d9eb..45f264471 100644 --- a/src/main/comments/utils.js +++ b/src/main/comments/utils.js @@ -7,7 +7,7 @@ function describeNodeForDebugging(node) { (node.value && (typeof node.value === "object" ? "" : String(node.value))) || node.operator || - "" + "", ); if (nodeName.length > 20) { nodeName = nodeName.slice(0, 19) + "…"; diff --git a/src/main/core.js b/src/main/core.js index 49a5e8cab..c3fc80350 100644 --- a/src/main/core.js +++ b/src/main/core.js @@ -68,7 +68,7 @@ async function coreFormat(originalText, opts, addAlignmentSize = 0) { oldCursorNodeStart = opts.locStart(opts.cursorNode); oldCursorNodeText = text.slice( oldCursorNodeStart, - opts.locEnd(opts.cursorNode) + opts.locEnd(opts.cursorNode), ); cursorOffsetRelativeToOldCursorNode = @@ -102,7 +102,7 @@ async function coreFormat(originalText, opts, addAlignmentSize = 0) { oldCursorNodeCharArray.splice( cursorOffsetRelativeToOldCursorNode, 0, - CURSOR + CURSOR, ); // eslint-disable-next-line unicorn/prefer-spread @@ -110,7 +110,7 @@ async function coreFormat(originalText, opts, addAlignmentSize = 0) { const cursorNodeDiff = diffArrays( oldCursorNodeCharArray, - newCursorNodeCharArray + newCursorNodeCharArray, ); let cursorOffset = newCursorNodeStart; @@ -140,7 +140,7 @@ async function formatRange(originalText, opts) { // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0 const rangeStart2 = Math.min( rangeStart, - text.lastIndexOf("\n", rangeStart) + 1 + text.lastIndexOf("\n", rangeStart) + 1, ); const indentString = text.slice(rangeStart2, rangeStart).match(/^\s*/)[0]; @@ -160,7 +160,7 @@ async function formatRange(originalText, opts) { // Always use `lf` to format, we'll replace it later endOfLine: "lf", }, - alignmentSize + alignmentSize, ); // Since the range contracts to avoid trailing whitespace, @@ -184,7 +184,7 @@ async function formatRange(originalText, opts) { if (cursorOffset >= 0 && eol === "\r\n") { cursorOffset += countEndOfLineChars( formatted.slice(0, cursorOffset), - "\n" + "\n", ); } @@ -219,7 +219,7 @@ function normalizeIndexes(text, options) { function normalizeInputAndOptions(text, options) { let { cursorOffset, rangeStart, rangeEnd, endOfLine } = normalizeIndexes( text, - options + options, ); const hasBOM = text.charAt(0) === BOM; @@ -268,7 +268,7 @@ async function hasPragma(text, options) { async function formatWithCursor(originalText, originalOptions) { let { hasBOM, text, options } = normalizeInputAndOptions( originalText, - await normalizeFormatOptions(originalOptions) + await normalizeFormatOptions(originalOptions), ); if ( @@ -312,7 +312,7 @@ async function formatWithCursor(originalText, originalOptions) { async function parse(originalText, originalOptions, devOptions) { const { text, options } = normalizeInputAndOptions( originalText, - await normalizeFormatOptions(originalOptions) + await normalizeFormatOptions(originalOptions), ); const parsed = await parseText(text, options); if (devOptions) { @@ -352,7 +352,7 @@ async function printToDoc(originalText, options) { async function printDocToString(doc, options) { return printDocToStringWithoutNormalizeOptions( doc, - await normalizeFormatOptions(options) + await normalizeFormatOptions(options), ); } diff --git a/src/main/create-print-pre-check-function.js b/src/main/create-print-pre-check-function.js index 2a51ffa88..6e18b1b20 100644 --- a/src/main/create-print-pre-check-function.js +++ b/src/main/create-print-pre-check-function.js @@ -8,7 +8,7 @@ function createPrintPreCheckFunction(options) { // All core plugins have full list of keys for possible child nodes // Ensure we only pass node to `print` const getVisitorKeys = createGetVisitorKeysFunction( - options.printer.getVisitorKeys + options.printer.getVisitorKeys, ); return function (path) { diff --git a/src/main/get-cursor-node.js b/src/main/get-cursor-node.js index 3abe4ed1b..66220b0c7 100644 --- a/src/main/get-cursor-node.js +++ b/src/main/get-cursor-node.js @@ -4,7 +4,7 @@ import createGetVisitorKeysFunction from "./create-get-visitor-keys-function.js" function getCursorNode(ast, options) { const { cursorOffset, locStart, locEnd } = options; const getVisitorKeys = createGetVisitorKeysFunction( - options.printer.getVisitorKeys + options.printer.getVisitorKeys, ); const nodeContainsCursor = (node) => locStart(node) <= cursorOffset && locEnd(node) >= cursorOffset; diff --git a/src/main/multiparser.js b/src/main/multiparser.js index 35ba6ed25..11f8831fe 100644 --- a/src/main/multiparser.js +++ b/src/main/multiparser.js @@ -8,7 +8,7 @@ async function printEmbeddedLanguages( genericPrint, options, printAstToDoc, - embeds + embeds, ) { const { embeddedLanguageFormatting, @@ -25,12 +25,12 @@ async function printEmbeddedLanguages( if (embed.length > 2) { throw new Error( - "printer.embed has too many parameters. The API changed in Prettier v3. Please update your plugin. See https://prettier.io/docs/en/plugins.html#optional-embed" + "printer.embed has too many parameters. The API changed in Prettier v3. Please update your plugin. See https://prettier.io/docs/en/plugins.html#optional-embed", ); } const getVisitorKeys = createGetVisitorKeysFunction( - embed.getVisitorKeys ?? printerGetVisitorKeys + embed.getVisitorKeys ?? printerGetVisitorKeys, ); const embedCallResults = []; @@ -94,7 +94,7 @@ async function printEmbeddedLanguages( typeof result.then === "function" ) { throw new Error( - "`embed` should return an async function instead of Promise." + "`embed` should return an async function instead of Promise.", ); } @@ -106,7 +106,7 @@ async function textToDoc( text, partialNextOptions, parentOptions, - printAstToDoc + printAstToDoc, ) { const options = await normalizeFormatOptions( { @@ -115,7 +115,7 @@ async function textToDoc( parentParser: parentOptions.parser, originalText: text, }, - { passThrough: true } + { passThrough: true }, ); const { ast } = await parse(text, options); diff --git a/src/main/normalize-format-options.js b/src/main/normalize-format-options.js index 94ee6a433..c2524bd4c 100644 --- a/src/main/normalize-format-options.js +++ b/src/main/normalize-format-options.js @@ -24,7 +24,7 @@ async function normalizeFormatOptions(options, opts = {}) { if (!rawOptions.parser) { if (!rawOptions.filepath) { throw new UndefinedParserError( - "No parser and no file path given, couldn't infer a parser." + "No parser and no file path given, couldn't infer a parser.", ); } else { rawOptions.parser = inferParser(rawOptions, { @@ -32,7 +32,7 @@ async function normalizeFormatOptions(options, opts = {}) { }); if (!rawOptions.parser) { throw new UndefinedParserError( - `No parser could be inferred for file "${rawOptions.filepath}".` + `No parser could be inferred for file "${rawOptions.filepath}".`, ); } } @@ -48,13 +48,13 @@ async function normalizeFormatOptions(options, opts = {}) { ...Object.fromEntries( supportOptions .filter((optionInfo) => optionInfo.default !== undefined) - .map((option) => [option.name, option.default]) + .map((option) => [option.name, option.default]), ), }; const parserPlugin = getParserPluginByParserName( rawOptions.plugins, - rawOptions.parser + rawOptions.parser, ); const parser = await initParser(parserPlugin, rawOptions.parser); @@ -72,8 +72,8 @@ async function normalizeFormatOptions(options, opts = {}) { const pluginDefaults = printerPlugin.defaultOptions ? Object.fromEntries( Object.entries(printerPlugin.defaultOptions).filter( - ([, value]) => value !== undefined - ) + ([, value]) => value !== undefined, + ), ) : {}; diff --git a/src/main/normalize-options.js b/src/main/normalize-options.js index a006c39b2..c4e7e8048 100644 --- a/src/main/normalize-options.js +++ b/src/main/normalize-options.js @@ -20,7 +20,7 @@ function normalizeOptions( passThrough = false, FlagSchema, descriptor, - } = {} + } = {}, ) { // TODO: Move CLI related part into `/src/cli` if (isCLI) { @@ -88,7 +88,7 @@ function optionInfosToSchemas(optionInfos, { isCLI, FlagSchema }) { isCLI, optionInfos, FlagSchema, - }) + }), ); if (optionInfo.alias && isCLI) { @@ -97,7 +97,7 @@ function optionInfosToSchemas(optionInfos, { isCLI, FlagSchema }) { // @ts-expect-error name: optionInfo.alias, sourceName: optionInfo.name, - }) + }), ); } } @@ -137,7 +137,7 @@ function optionInfoToSchema(optionInfo, { isCLI, optionInfos, FlagSchema }) { to: { key: optionInfo.name, value: choiceInfo.redirect }, }, } - : choiceInfo + : choiceInfo, ); break; case "boolean": @@ -151,7 +151,7 @@ function optionInfoToSchema(optionInfo, { isCLI, optionInfos, FlagSchema }) { optionInfo.alias, optionInfo.description && optionInfo.name, optionInfo.oppositeDescription && `no-${optionInfo.name}`, - ].filter(Boolean) + ].filter(Boolean), ); break; case "path": @@ -195,7 +195,7 @@ function optionInfoToSchema(optionInfo, { isCLI, optionInfos, FlagSchema }) { parameters.preprocess = (value, schema, utils) => schema.preprocess( originalPreprocess(Array.isArray(value) ? value.at(-1) : value), - utils + utils, ); } diff --git a/src/main/parse.js b/src/main/parse.js index f3127bafb..faef62ebf 100644 --- a/src/main/parse.js +++ b/src/main/parse.js @@ -15,7 +15,7 @@ async function parse(originalText, options) { options, // TODO: remove the third argument in v4 // The duplicated argument is passed as intended, see #10156 - options + options, ); } catch (error) { handleParseError(error, originalText); diff --git a/src/main/plugins/load-plugin.js b/src/main/plugins/load-plugin.js index 80e603c01..057fb0d3e 100644 --- a/src/main/plugins/load-plugin.js +++ b/src/main/plugins/load-plugin.js @@ -12,7 +12,7 @@ function normalizePlugin(pluginInstanceOfPluginModule, name) { const loadPluginFromDirectory = mem( async (name, directory) => normalizePlugin(await importFromDirectory(name, directory), name), - { cacheKey: JSON.stringify } + { cacheKey: JSON.stringify }, ); const importPlugin = mem(async (name) => { diff --git a/src/main/range-util.js b/src/main/range-util.js index 604645bec..10a2e5e20 100644 --- a/src/main/range-util.js +++ b/src/main/range-util.js @@ -14,7 +14,8 @@ function findCommonAncestor(startNodeAndParents, endNodeAndParents) { ...endNodeAndParents.parentNodes, ]); return startNodeAndAncestors.find( - (node) => jsonSourceElements.has(node.type) && endNodeAndAncestors.has(node) + (node) => + jsonSourceElements.has(node.type) && endNodeAndAncestors.has(node), ); } @@ -34,7 +35,7 @@ function dropRootParents(parents) { function findSiblingAncestors( startNodeAndParents, endNodeAndParents, - { locStart, locEnd } + { locStart, locEnd }, ) { let resultStartNode = startNodeAndParents.node; let resultEndNode = endNodeAndParents.node; @@ -79,7 +80,7 @@ function findNodeAtOffset( options, predicate, parentNodes = [], - type + type, ) { const { locStart, locEnd } = options; const start = locStart(node); @@ -101,7 +102,7 @@ function findNodeAtOffset( options, predicate, [node, ...parentNodes], - type + type, ); if (childResult) { return childResult; @@ -210,7 +211,7 @@ function calculateRange(text, opts, ast) { opts, (node, parentNode) => isSourceElement(opts, node, parentNode), [], - "rangeStart" + "rangeStart", ); const endNodeAndParents = // No need find Node at `end`, it will be the same as `startNodeAndParents` @@ -222,7 +223,7 @@ function calculateRange(text, opts, ast) { opts, (node) => isSourceElement(opts, node), [], - "rangeEnd" + "rangeEnd", ); if (!startNodeAndParents || !endNodeAndParents) { return { @@ -236,7 +237,7 @@ function calculateRange(text, opts, ast) { if (isJsonParser(opts)) { const commonAncestor = findCommonAncestor( startNodeAndParents, - endNodeAndParents + endNodeAndParents, ); startNode = commonAncestor; endNode = commonAncestor; @@ -244,7 +245,7 @@ function calculateRange(text, opts, ast) { ({ startNode, endNode } = findSiblingAncestors( startNodeAndParents, endNodeAndParents, - opts + opts, )); } diff --git a/src/main/support.js b/src/main/support.js index a35ec7582..9e1b54ded 100644 --- a/src/main/support.js +++ b/src/main/support.js @@ -18,7 +18,7 @@ function getSupportInfo({ plugins = [], showDeprecated = false } = {}) { const options = []; for (const option of normalizeOptionSettings( - Object.assign({}, ...plugins.map(({ options }) => options), coreOptions) + Object.assign({}, ...plugins.map(({ options }) => options), coreOptions), )) { if (!showDeprecated && option.deprecated) { continue; @@ -40,7 +40,7 @@ function getSupportInfo({ plugins = [], showDeprecated = false } = {}) { option.pluginDefaults = Object.fromEntries( plugins .filter((plugin) => plugin.defaultOptions?.[option.name] !== undefined) - .map((plugin) => [plugin.name, plugin.defaultOptions[option.name]]) + .map((plugin) => [plugin.name, plugin.defaultOptions[option.name]]), ); options.push(option); @@ -59,7 +59,7 @@ function* collectParsersFromLanguages(parserChoices, languages, plugins) { existingParsers.add(parserName); const plugin = plugins.find( (plugin) => - plugin.parsers && Object.hasOwn(plugin.parsers, parserName) + plugin.parsers && Object.hasOwn(plugin.parsers, parserName), ); let description = language.name; diff --git a/src/standalone.d.ts b/src/standalone.d.ts index 5dbb70e91..b77367bb7 100644 --- a/src/standalone.d.ts +++ b/src/standalone.d.ts @@ -13,7 +13,7 @@ import { CursorOptions, CursorResult, Options, SupportInfo } from "./index.js"; */ export function formatWithCursor( source: string, - options: CursorOptions + options: CursorOptions, ): Promise; /** diff --git a/src/standalone.js b/src/standalone.js index 7a8b4d16c..a4c9888ae 100644 --- a/src/standalone.js +++ b/src/standalone.js @@ -3,7 +3,7 @@ import { getSupportInfo as getSupportInfoWithoutPlugins } from "./main/support.j function withPlugins( fn, - optionsArgumentIndex = 1 // Usually `options` is the 2nd argument + optionsArgumentIndex = 1, // Usually `options` is the 2nd argument ) { // Returns Promises to consistent with functions in `index.js` // eslint-disable-next-line require-await diff --git a/src/utils/create-get-visitor-keys.js b/src/utils/create-get-visitor-keys.js index 83de28e69..de6920a2d 100644 --- a/src/utils/create-get-visitor-keys.js +++ b/src/utils/create-get-visitor-keys.js @@ -9,7 +9,7 @@ function createGetVisitorKeys(visitorKeys, typeProperty = "type") { /* c8 ignore next 5 */ if (process.env.NODE_ENV !== "production" && type === undefined) { throw new Error( - `Can't get node type, you must pass the wrong typeProperty '${typeProperty}'` + `Can't get node type, you must pass the wrong typeProperty '${typeProperty}'`, ); } diff --git a/src/utils/front-matter/parse.js b/src/utils/front-matter/parse.js index 518cc9134..cf940800f 100644 --- a/src/utils/front-matter/parse.js +++ b/src/utils/front-matter/parse.js @@ -8,7 +8,7 @@ const frontMatterRegex = new RegExp( // Adding `\.{3}` make the regex matches `+++\n...`, but we'll exclude it later "(?\\k|\\.{3})" + "[^\\S\\n]*(?:\\n|$)", - "s" + "s", ); function parse(text) { diff --git a/src/utils/get-indent-size.js b/src/utils/get-indent-size.js index 6d3067f13..f615f56d9 100644 --- a/src/utils/get-indent-size.js +++ b/src/utils/get-indent-size.js @@ -15,7 +15,7 @@ function getIndentSize(value, tabWidth) { return getAlignmentSize( // All the leading whitespaces value.slice(lastNewlineIndex + 1).match(/^[\t ]*/)[0], - tabWidth + tabWidth, ); } diff --git a/src/utils/get-max-continuous-count.js b/src/utils/get-max-continuous-count.js index efe27a4f8..dec932878 100644 --- a/src/utils/get-max-continuous-count.js +++ b/src/utils/get-max-continuous-count.js @@ -7,7 +7,7 @@ import escapeStringRegexp from "escape-string-regexp"; */ function getMaxContinuousCount(text, searchString) { const results = text.match( - new RegExp(`(${escapeStringRegexp(searchString)})+`, "g") + new RegExp(`(${escapeStringRegexp(searchString)})+`, "g"), ); if (results === null) { @@ -17,7 +17,7 @@ function getMaxContinuousCount(text, searchString) { return results.reduce( (maxCount, result) => Math.max(maxCount, result.length / searchString.length), - 0 + 0, ); } diff --git a/src/utils/get-min-not-present-continuous-count.js b/src/utils/get-min-not-present-continuous-count.js index c0d278201..0803f728d 100644 --- a/src/utils/get-min-not-present-continuous-count.js +++ b/src/utils/get-min-not-present-continuous-count.js @@ -7,7 +7,7 @@ import escapeStringRegexp from "escape-string-regexp"; */ function getMinNotPresentContinuousCount(text, searchString) { const matches = text.match( - new RegExp(`(${escapeStringRegexp(searchString)})+`, "g") + new RegExp(`(${escapeStringRegexp(searchString)})+`, "g"), ); if (matches === null) { diff --git a/src/utils/has-newline.js b/src/utils/has-newline.js index 2340fb444..3e503d4e9 100644 --- a/src/utils/has-newline.js +++ b/src/utils/has-newline.js @@ -13,7 +13,7 @@ function hasNewline(text, startIndex, options = {}) { const idx = skipSpaces( text, options.backwards ? startIndex - 1 : startIndex, - options + options, ); const idx2 = skipNewline(text, idx, options); return idx !== idx2; diff --git a/src/utils/has-spaces.js b/src/utils/has-spaces.js index 6eef55abc..73d2c7da5 100644 --- a/src/utils/has-spaces.js +++ b/src/utils/has-spaces.js @@ -14,7 +14,7 @@ function hasSpaces(text, startIndex, options = {}) { const idx = skipSpaces( text, options.backwards ? startIndex - 1 : startIndex, - options + options, ); return idx !== startIndex; } diff --git a/src/utils/ignore.js b/src/utils/ignore.js index c17556186..67e89d0b2 100644 --- a/src/utils/ignore.js +++ b/src/utils/ignore.js @@ -57,8 +57,8 @@ async function createIsIgnoredFunction(ignoreFilePaths, withNodeModules) { const isIgnoredFunctions = ( await Promise.all( ignoreFilePaths.map((ignoreFilePath) => - createSingleIsIgnoredFunction(ignoreFilePath, withNodeModules) - ) + createSingleIsIgnoredFunction(ignoreFilePath, withNodeModules), + ), ) ).filter(Boolean); diff --git a/src/utils/infer-parser.js b/src/utils/infer-parser.js index e018766ab..2002360aa 100644 --- a/src/utils/infer-parser.js +++ b/src/utils/infer-parser.js @@ -13,7 +13,7 @@ function getLanguageByFilename(languages, filename) { return languages.find( (language) => language.extensions?.some((extension) => basename.endsWith(extension)) || - language.filenames?.some((name) => name.toLowerCase() === basename) + language.filenames?.some((name) => name.toLowerCase() === basename), ); } @@ -44,8 +44,8 @@ function getLanguageByInterpreter(languages, file) { return; } - return languages.find((language) => - language.interpreters?.includes(interpreter) + return languages.find( + (language) => language.interpreters?.includes(interpreter), ); } @@ -58,7 +58,7 @@ function inferParser(options, fileInfo) { const languages = options.plugins.flatMap( (plugin) => // @ts-expect-error -- Safe - plugin.languages ?? [] + plugin.languages ?? [], ); // If the file has no extension, we can try to infer the language from the diff --git a/src/utils/object-omit.js b/src/utils/object-omit.js index feec68b94..e731f6bc3 100644 --- a/src/utils/object-omit.js +++ b/src/utils/object-omit.js @@ -1,7 +1,7 @@ function omit(object, keys) { keys = new Set(keys); return Object.fromEntries( - Object.entries(object).filter(([key]) => !keys.has(key)) + Object.entries(object).filter(([key]) => !keys.has(key)), ); } diff --git a/src/utils/print-string.js b/src/utils/print-string.js index c2955277e..8cbe60001 100644 --- a/src/utils/print-string.js +++ b/src/utils/print-string.js @@ -31,7 +31,7 @@ function printString(raw, options) { options.parser === "less" || options.parser === "scss" || options.__embeddedInHtml - ) + ), ); } diff --git a/src/utils/public.js b/src/utils/public.js index 01558ce09..62d9bd99d 100644 --- a/src/utils/public.js +++ b/src/utils/public.js @@ -13,7 +13,7 @@ import isNextLineEmptyAfterIndex from "./is-next-line-empty.js"; function legacyGetNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) { return getNextNonSpaceNonCommentCharacterIndexWithStartIndex( text, - locEnd(node) + locEnd(node), ); } diff --git a/src/utils/unexpected-node-error.js b/src/utils/unexpected-node-error.js index 5a15e9187..4181cfff5 100644 --- a/src/utils/unexpected-node-error.js +++ b/src/utils/unexpected-node-error.js @@ -4,8 +4,8 @@ class UnexpectedNodeError extends Error { constructor(node, language, typeProperty = "type") { super( `Unexpected ${language} node ${typeProperty}: ${JSON.stringify( - node[typeProperty] - )}.` + node[typeProperty], + )}.`, ); this.node = node; } diff --git a/src/utils/whitespace-utils.js b/src/utils/whitespace-utils.js index 781467326..e281977fe 100644 --- a/src/utils/whitespace-utils.js +++ b/src/utils/whitespace-utils.js @@ -11,11 +11,11 @@ class WhitespaceUtils { (this.#whitespaceCharacters.size === 0 || Array.prototype.some.call( whitespaceCharacters, - (character) => !/^\s$/.test(character) + (character) => !/^\s$/.test(character), )) ) { throw new TypeError( - `Invalid characters: ${JSON.stringify(whitespaceCharacters)}` + `Invalid characters: ${JSON.stringify(whitespaceCharacters)}`, ); } } @@ -84,7 +84,7 @@ class WhitespaceUtils { split(text, captureWhitespace = false) { const pattern = `[${escapeStringRegexp( - [...this.#whitespaceCharacters].join("") + [...this.#whitespaceCharacters].join(""), )}]+`; const regexp = new RegExp(captureWhitespace ? `(${pattern})` : pattern); return text.split(regexp); @@ -93,7 +93,7 @@ class WhitespaceUtils { hasWhitespaceCharacter(text) { const whitespaceCharacters = this.#whitespaceCharacters; return Array.prototype.some.call(text, (character) => - whitespaceCharacters.has(character) + whitespaceCharacters.has(character), ); } @@ -101,14 +101,14 @@ class WhitespaceUtils { const whitespaceCharacters = this.#whitespaceCharacters; return Array.prototype.some.call( text, - (character) => !whitespaceCharacters.has(character) + (character) => !whitespaceCharacters.has(character), ); } isWhitespaceOnly(text) { const whitespaceCharacters = this.#whitespaceCharacters; return Array.prototype.every.call(text, (character) => - whitespaceCharacters.has(character) + whitespaceCharacters.has(character), ); } } diff --git a/tests/config/format-test.js b/tests/config/format-test.js index 584a17671..98558a117 100644 --- a/tests/config/format-test.js +++ b/tests/config/format-test.js @@ -49,7 +49,7 @@ const unstableTests = new Map( ? fixture : [fixture]; return [path.join(__dirname, "../format/", file), isUnstable]; - }) + }), ); const unstableAstTests = new Map(); @@ -58,7 +58,7 @@ const espreeDisabledTests = new Set( [ // These tests only work for `babel` "comments-closure-typecast", - ].map((directory) => path.join(__dirname, "../format/js", directory)) + ].map((directory) => path.join(__dirname, "../format/js", directory)), ); const acornDisabledTests = espreeDisabledTests; const meriyahDisabledTests = new Set([ @@ -86,8 +86,8 @@ const meriyahDisabledTests = new Set([ ]); const babelTsDisabledTest = new Set( ["conformance/types/moduleDeclaration/kind-detection.ts"].map((file) => - path.join(__dirname, "../format/typescript", file) - ) + path.join(__dirname, "../format/typescript", file), + ), ); const isUnstable = (filename, options) => { @@ -127,7 +127,7 @@ const shouldThrowOnFormat = (filename, options) => { const isTestDirectory = (dirname, name) => (dirname + path.sep).startsWith( - path.join(__dirname, "../format", name) + path.sep + path.join(__dirname, "../format", name) + path.sep, ); const ensurePromise = (value) => { @@ -152,7 +152,7 @@ function runSpec(fixtures, parsers, options) { // `IS_PARSER_INFERENCE_TESTS` mean to test `inferParser` on `standalone` const IS_PARSER_INFERENCE_TESTS = isTestDirectory( dirname, - "misc/parser-inference" + "misc/parser-inference", ); // `IS_ERROR_TESTS` mean to watch errors like: @@ -165,7 +165,7 @@ function runSpec(fixtures, parsers, options) { const IS_TYPESCRIPT_ONLY_TEST = isTestDirectory( dirname, - "misc/typescript-only" + "misc/typescript-only", ); if (IS_PARSER_INFERENCE_TESTS) { @@ -271,7 +271,7 @@ function runSpec(fixtures, parsers, options) { }; const shouldThrowOnMainParserFormat = shouldThrowOnFormat( name, - formatOptions + formatOptions, ); let mainParserFormatResult; @@ -349,13 +349,13 @@ async function runTest({ // Make sure output has consistent EOL expect(formatResult.eolVisualizedOutput).toEqual( - visualizeEndOfLine(consistentEndOfLine(formatResult.outputWithCursor)) + visualizeEndOfLine(consistentEndOfLine(formatResult.outputWithCursor)), ); // The result is assert to equals to `output` if (typeof output === "string") { expect(formatResult.eolVisualizedOutput).toEqual( - visualizeEndOfLine(output) + visualizeEndOfLine(output), ); return; } @@ -366,7 +366,7 @@ async function runTest({ parsers, formatOptions, CURSOR_PLACEHOLDER, - }) + }), ).toMatchSnapshot(); if (!FULL_TEST) { @@ -382,7 +382,7 @@ async function runTest({ const { eolVisualizedOutput: firstOutput, output } = formatResult; const { eolVisualizedOutput: secondOutput } = await format( output, - formatOptions + formatOptions, ); if (isUnstableTest) { // To keep eye on failed tests, this assert never supposed to pass, @@ -410,14 +410,14 @@ async function runTest({ for (const eol of ["\r\n", "\r"]) { const { eolVisualizedOutput: output } = await format( code.replace(/\n/g, eol), - formatOptions + formatOptions, ); // Only if `endOfLine: "auto"` the result will be different const expected = formatOptions.endOfLine === "auto" ? visualizeEndOfLine( // All `code` use `LF`, so the `eol` of result is always `LF` - formatResult.outputWithCursor.replace(/\n/g, eol) + formatResult.outputWithCursor.replace(/\n/g, eol), ) : formatResult.eolVisualizedOutput; expect(output).toEqual(expected); @@ -427,7 +427,7 @@ async function runTest({ if (code.charAt(0) !== BOM) { const { eolVisualizedOutput: output } = await format( BOM + code, - formatOptions + formatOptions, ); const expected = BOM + formatResult.eolVisualizedOutput; expect(output).toEqual(expected); @@ -504,13 +504,13 @@ const insertCursor = (text, cursorOffset) => async function format(originalText, originalOptions) { const { text: input, options } = replacePlaceholders( originalText, - originalOptions + originalOptions, ); const inputWithCursor = insertCursor(input, options.cursorOffset); const prettier = await getPrettier(); const { formatted: output, cursorOffset } = await ensurePromise( - prettier.formatWithCursor(input, options) + prettier.formatWithCursor(input, options), ); const outputWithCursor = insertCursor(output, cursorOffset); const eolVisualizedOutput = visualizeEndOfLine(outputWithCursor); diff --git a/tests/config/get-prettier.js b/tests/config/get-prettier.js index f9a4a17e9..461f0c9a2 100644 --- a/tests/config/get-prettier.js +++ b/tests/config/get-prettier.js @@ -18,8 +18,8 @@ function getPrettierInternal() { const entry = pathToFileURL( path.join( process.env.PRETTIER_DIR, - process.env.NODE_ENV === "production" ? "index.mjs" : "index.js" - ) + process.env.NODE_ENV === "production" ? "index.mjs" : "index.js", + ), ); return import(entry); } diff --git a/tests/config/install-prettier.js b/tests/config/install-prettier.js index 65cb1b37a..f78eaa9f3 100644 --- a/tests/config/install-prettier.js +++ b/tests/config/install-prettier.js @@ -79,13 +79,13 @@ function installPrettier(packageDirectory) { at ${chalk.inverse(temporaryDirectory)} from ${chalk.inverse(packageDirectory)} with ${chalk.inverse(client)}. - ` - ) + `, + ), ); fs.writeFileSync( path.join(temporaryDirectory, "index-proxy.mjs"), - "export * from 'prettier';" + "export * from 'prettier';", ); return temporaryDirectory; diff --git a/tests/config/prettier-plugins/prettier-plugin-async-printer/index.cjs b/tests/config/prettier-plugins/prettier-plugin-async-printer/index.cjs index 305002491..7030218e4 100644 --- a/tests/config/prettier-plugins/prettier-plugin-async-printer/index.cjs +++ b/tests/config/prettier-plugins/prettier-plugin-async-printer/index.cjs @@ -32,7 +32,7 @@ module.exports = { JSON.stringify({ ...ast, print: ast.print?.replace(/\s+/g, " ") ?? "", - }) + }), ); }, massageAstNode() { diff --git a/tests/config/require-standalone.cjs b/tests/config/require-standalone.cjs index ab0e66069..c02c30979 100644 --- a/tests/config/require-standalone.cjs +++ b/tests/config/require-standalone.cjs @@ -25,7 +25,7 @@ module.exports = { }; prettier.formatWithCursor($$$input, options); `, - { $$$input: input, $$$options: options, ...sandbox } + { $$$input: input, $$$options: options, ...sandbox }, ); }, @@ -41,7 +41,7 @@ module.exports = { }; prettier.getSupportInfo(options); `, - { $$$options: options, ...sandbox } + { $$$options: options, ...sandbox }, ); }, @@ -63,7 +63,7 @@ module.exports = { $$$options: options, $$$devOptions: devOptions, ...sandbox, - } + }, ); }, }, diff --git a/tests/config/utils/check-parsers.js b/tests/config/utils/check-parsers.js index a8def844d..259dd1ccf 100644 --- a/tests/config/utils/check-parsers.js +++ b/tests/config/utils/check-parsers.js @@ -171,8 +171,8 @@ const checkParser = ({ dirname, files }, parsers = []) => { if (verifyParsers.includes(parser)) { throw new Error( `verifyParsers ${JSON.stringify( - verifyParsers - )} should not include parser "${parser}".` + verifyParsers, + )} should not include parser "${parser}".`, ); } @@ -194,7 +194,7 @@ const checkParser = ({ dirname, files }, parsers = []) => { throw new Error( `Parser "${parser}" should not used in "${dirname}".${ suggestion ? `\n\n${suggestion}` : "" - }` + }`, ); } @@ -205,7 +205,7 @@ const checkParser = ({ dirname, files }, parsers = []) => { outdent` Parser "${verifyParser}" should not used to verify in "${dirname}". Please remove it or config to allow use this parser in "${__filename}". - ` + `, ); } } @@ -219,7 +219,7 @@ const checkParser = ({ dirname, files }, parsers = []) => { File "${name}" should not tested in "${dirname}". Allowed extensions: ${extensions.join(",")}. Please rename it or config to allow test "${ext}" file in "${__filename}". - ` + `, ); } } diff --git a/tests/config/utils/create-snapshot.js b/tests/config/utils/create-snapshot.js index c0d9003c4..d404999ea 100644 --- a/tests/config/utils/create-snapshot.js +++ b/tests/config/utils/create-snapshot.js @@ -48,7 +48,7 @@ function printWidthIndicator(printWidth, offset) { function createSnapshot( formatResult, - { parsers, formatOptions, CURSOR_PLACEHOLDER } + { parsers, formatOptions, CURSOR_PLACEHOLDER }, ) { let { inputWithCursor: input, @@ -89,7 +89,7 @@ function createSnapshot( printSeparator("output"), output, printSeparator(), - ].join("\n") + ].join("\n"), ); } diff --git a/tests/config/utils/stringify-options-for-title.js b/tests/config/utils/stringify-options-for-title.js index 7591265a8..11e92ee29 100644 --- a/tests/config/utils/stringify-options-for-title.js +++ b/tests/config/utils/stringify-options-for-title.js @@ -4,7 +4,7 @@ function stringifyOptions(options) { ? undefined : value === Number.POSITIVE_INFINITY ? "Infinity" - : value + : value, ); return string === "{}" ? "" : string; diff --git a/tests/config/utils/visualize-range.js b/tests/config/utils/visualize-range.js index 6d3762f7f..eb7232dc1 100644 --- a/tests/config/utils/visualize-range.js +++ b/tests/config/utils/visualize-range.js @@ -32,7 +32,7 @@ const visualizeRange = (text, { rangeStart = 0, rangeEnd = text.length }) => locationForRange(text, rangeStart, rangeEnd), rangeStart > rangeEnd ? { ...codeFrameColumnsOptions, message: "[Reversed range]" } - : codeFrameColumnsOptions + : codeFrameColumnsOptions, ); export default visualizeRange; diff --git a/tests/dts/unit/cases/print.ts b/tests/dts/unit/cases/print.ts index 444cab186..25679963e 100644 --- a/tests/dts/unit/cases/print.ts +++ b/tests/dts/unit/cases/print.ts @@ -34,7 +34,7 @@ function print( // functions. path: prettier.AstPath, options: prettier.ParserOptions, - print: (path: prettier.AstPath) => prettier.doc.builders.Doc + print: (path: prettier.AstPath) => prettier.doc.builders.Doc, ): prettier.doc.builders.Doc { path.call((child) => { expectType>(child); @@ -49,7 +49,7 @@ function print( expectType>(child); }, "item2", - "item3" + "item3", ); path.call( @@ -58,7 +58,7 @@ function print( }, "item2", "item3", - "item1" + "item1", ); path.call( @@ -68,7 +68,7 @@ function print( "item2", "item3", "item1", - "item2" + "item2", ); path.call( @@ -79,7 +79,7 @@ function print( "item3", "item1", "item2", - "item3" + "item3", ); path.each((child) => { @@ -96,7 +96,7 @@ function print( }, "list2", 0, - "list3" + "list3", ); path.each( @@ -107,7 +107,7 @@ function print( 0, "list3", 0, - "list1" + "list1", ); path.map((child) => { @@ -124,7 +124,7 @@ function print( }, "list2", 0, - "list3" + "list3", ); path.map( @@ -135,7 +135,7 @@ function print( 0, "list3", 0, - "list1" + "list1", ); // @ts-expect-error diff --git a/tests/dts/unit/run.js b/tests/dts/unit/run.js index 31ca0d8e2..94431b3a6 100644 --- a/tests/dts/unit/run.js +++ b/tests/dts/unit/run.js @@ -8,7 +8,7 @@ import { default as ts } from "typescript"; describe("Unit tests for dts files", () => { test("no errors", () => { const testCasesDirPath = url.fileURLToPath( - new URL("cases", import.meta.url) + new URL("cases", import.meta.url), ); const testCaseFiles = fs .readdirSync(testCasesDirPath) diff --git a/tests/format/handlebars/element-node/jsfmt.spec.js b/tests/format/handlebars/element-node/jsfmt.spec.js index e50558fcf..d1c3a58d0 100644 --- a/tests/format/handlebars/element-node/jsfmt.spec.js +++ b/tests/format/handlebars/element-node/jsfmt.spec.js @@ -18,5 +18,5 @@ run_spec( "nextid", ].map((tag) => ({ name: tag, code: `<${tag}> text ` })), }, - ["glimmer"] + ["glimmer"], ); diff --git a/tests/format/handlebars/html-whitespace-sensitivity/jsfmt.spec.js b/tests/format/handlebars/html-whitespace-sensitivity/jsfmt.spec.js index cb1897587..3eaf1bc93 100644 --- a/tests/format/handlebars/html-whitespace-sensitivity/jsfmt.spec.js +++ b/tests/format/handlebars/html-whitespace-sensitivity/jsfmt.spec.js @@ -81,5 +81,5 @@ run_spec( { htmlWhitespaceSensitivity: "strict", printWidth: 40, - } + }, ); diff --git a/tests/format/html/whitespace/jsfmt.spec.js b/tests/format/html/whitespace/jsfmt.spec.js index 458c46e1b..6c8235e51 100644 --- a/tests/format/html/whitespace/jsfmt.spec.js +++ b/tests/format/html/whitespace/jsfmt.spec.js @@ -126,5 +126,5 @@ run_spec( }, ], }, - ["html"] + ["html"], ); diff --git a/tests/format/js/bom/jsfmt.spec.js b/tests/format/js/bom/jsfmt.spec.js index f5d6114d7..78c4cfeda 100644 --- a/tests/format/js/bom/jsfmt.spec.js +++ b/tests/format/js/bom/jsfmt.spec.js @@ -4,7 +4,7 @@ const fixtureDirectory = new URL("../eol/", import.meta.url); const snippets = fs .readdirSync(fixtureDirectory) .filter( - (fileName) => fileName !== "__snapshots__" && fileName !== "jsfmt.spec.js" + (fileName) => fileName !== "__snapshots__" && fileName !== "jsfmt.spec.js", ) .map((fileName) => { const file = new URL(fileName, fixtureDirectory); diff --git a/tests/format/js/cursor/jsfmt.spec.js b/tests/format/js/cursor/jsfmt.spec.js index e529618e5..ef0080c5d 100644 --- a/tests/format/js/cursor/jsfmt.spec.js +++ b/tests/format/js/cursor/jsfmt.spec.js @@ -10,7 +10,7 @@ beforeAll(async () => { test("translates cursor correctly in basic case", async () => { expect( - await prettier.formatWithCursor(" 1", { parser: "babel", cursorOffset: 2 }) + await prettier.formatWithCursor(" 1", { parser: "babel", cursorOffset: 2 }), ).toMatchObject({ formatted: "1;\n", cursorOffset: 1, @@ -20,7 +20,10 @@ test("translates cursor correctly in basic case", async () => { test("positions cursor relative to closest node, not SourceElement", async () => { const code = "return 15"; expect( - await prettier.formatWithCursor(code, { parser: "babel", cursorOffset: 15 }) + await prettier.formatWithCursor(code, { + parser: "babel", + cursorOffset: 15, + }), ).toMatchObject({ formatted: "return 15;\n", cursorOffset: 7, @@ -30,7 +33,10 @@ test("positions cursor relative to closest node, not SourceElement", async () => test("keeps cursor inside formatted node", async () => { const code = "return 15"; expect( - await prettier.formatWithCursor(code, { parser: "babel", cursorOffset: 14 }) + await prettier.formatWithCursor(code, { + parser: "babel", + cursorOffset: 14, + }), ).toMatchObject({ formatted: "return 15;\n", cursorOffset: 7, @@ -46,7 +52,10 @@ test("doesn't insert second placeholder for nonexistent TypeAnnotation", async ( }) `; expect( - await prettier.formatWithCursor(code, { parser: "babel", cursorOffset: 24 }) + await prettier.formatWithCursor(code, { + parser: "babel", + cursorOffset: 24, + }), ).toMatchObject({ formatted: outdent` @@ -67,7 +76,7 @@ test("cursorOffset === rangeStart", async () => { cursorOffset: 7, rangeStart: 7, rangeEnd: 8, - }) + }), ).toMatchObject({ formatted: "1.0000\n2.0;\n3.0000", cursorOffset: 7, diff --git a/tests/format/js/directives/comments/jsfmt.spec.js b/tests/format/js/directives/comments/jsfmt.spec.js index dc5f5e64d..b908dd1b4 100644 --- a/tests/format/js/directives/comments/jsfmt.spec.js +++ b/tests/format/js/directives/comments/jsfmt.spec.js @@ -54,5 +54,5 @@ run_spec( ["babel", "flow", "typescript"], { semi: false, - } + }, ); diff --git a/tests/format/js/directives/jsfmt.spec.js b/tests/format/js/directives/jsfmt.spec.js index 45b56d7a5..8d9c71af6 100644 --- a/tests/format/js/directives/jsfmt.spec.js +++ b/tests/format/js/directives/jsfmt.spec.js @@ -44,5 +44,5 @@ run_spec( }, ], }, - ["babel", "flow", "typescript"] + ["babel", "flow", "typescript"], ); diff --git a/tests/format/js/empty/jsfmt.spec.js b/tests/format/js/empty/jsfmt.spec.js index ed12e62f7..e78bce58f 100644 --- a/tests/format/js/empty/jsfmt.spec.js +++ b/tests/format/js/empty/jsfmt.spec.js @@ -27,5 +27,5 @@ run_spec( "\n;/* comment */\n", ], }, - ["babel", "flow", "typescript"] + ["babel", "flow", "typescript"], ); diff --git a/tests/format/js/identifier/parentheses/jsfmt.spec.js b/tests/format/js/identifier/parentheses/jsfmt.spec.js index 202ed2340..30650ca0b 100644 --- a/tests/format/js/identifier/parentheses/jsfmt.spec.js +++ b/tests/format/js/identifier/parentheses/jsfmt.spec.js @@ -10,5 +10,5 @@ run_spec( // "flow", "typescript", ], - { semi: false } + { semi: false }, ); diff --git a/tests/format/js/shebang/jsfmt.spec.js b/tests/format/js/shebang/jsfmt.spec.js index 08da7daba..3c9ab6268 100644 --- a/tests/format/js/shebang/jsfmt.spec.js +++ b/tests/format/js/shebang/jsfmt.spec.js @@ -12,5 +12,5 @@ run_spec( }, ], }, - ["babel", "flow", "typescript"] + ["babel", "flow", "typescript"], ); diff --git a/tests/format/js/trailing-whitespace/jsfmt.spec.js b/tests/format/js/trailing-whitespace/jsfmt.spec.js index 8820e4be7..1c9d46f0c 100644 --- a/tests/format/js/trailing-whitespace/jsfmt.spec.js +++ b/tests/format/js/trailing-whitespace/jsfmt.spec.js @@ -3,5 +3,5 @@ run_spec( importMeta: import.meta, snippets: ["`\n \n \n` + `\n \n \n`;"], }, - ["babel", "flow", "typescript"] + ["babel", "flow", "typescript"], ); diff --git a/tests/format/json/json-superset/jsfmt.spec.js b/tests/format/json/json-superset/jsfmt.spec.js index e484e191f..368c152c0 100644 --- a/tests/format/json/json-superset/jsfmt.spec.js +++ b/tests/format/json/json-superset/jsfmt.spec.js @@ -41,7 +41,7 @@ run_spec( })), ], }, - ["json", "json5"] + ["json", "json5"], ); run_spec( @@ -74,5 +74,5 @@ run_spec( })), ], }, - ["json-stringify"] + ["json-stringify"], ); diff --git a/tests/format/jsx/whitespace/jsfmt.spec.js b/tests/format/jsx/whitespace/jsfmt.spec.js index cb8db431b..ba2bc3ecd 100644 --- a/tests/format/jsx/whitespace/jsfmt.spec.js +++ b/tests/format/jsx/whitespace/jsfmt.spec.js @@ -84,5 +84,5 @@ run_spec( }, ].map((test) => ({ ...test, output: test.output + "\n" })), }, - ["flow", "typescript"] + ["flow", "typescript"], ); diff --git a/tests/format/markdown/auto-link/jsfmt.spec.js b/tests/format/markdown/auto-link/jsfmt.spec.js index 0864b1b5b..8d1d2db89 100644 --- a/tests/format/markdown/auto-link/jsfmt.spec.js +++ b/tests/format/markdown/auto-link/jsfmt.spec.js @@ -73,5 +73,5 @@ run_spec( importMeta: import.meta, snippets: cases.map((code) => ({ code, name: code })), }, - ["markdown"] + ["markdown"], ); diff --git a/tests/format/markdown/fenced-code-block/jsfmt.spec.js b/tests/format/markdown/fenced-code-block/jsfmt.spec.js index 3ad78010f..1c192298c 100644 --- a/tests/format/markdown/fenced-code-block/jsfmt.spec.js +++ b/tests/format/markdown/fenced-code-block/jsfmt.spec.js @@ -3,5 +3,5 @@ run_spec( importMeta: import.meta, snippets: ["```\na", "```\na\n", "```\na\n\n", "```\na" + "\n".repeat(10)], }, - ["markdown"] + ["markdown"], ); diff --git a/tests/format/markdown/list/jsfmt.spec.js b/tests/format/markdown/list/jsfmt.spec.js index ac6652ed2..612e156d2 100644 --- a/tests/format/markdown/list/jsfmt.spec.js +++ b/tests/format/markdown/list/jsfmt.spec.js @@ -9,7 +9,7 @@ const emptyListItemSnippets = [ run_spec( { importMeta: import.meta, snippets: emptyListItemSnippets }, ["markdown"], - { proseWrap: "always" } + { proseWrap: "always" }, ); run_spec(import.meta, ["markdown"], { proseWrap: "always", tabWidth: 4 }); run_spec(import.meta, ["markdown"], { proseWrap: "always", tabWidth: 999 }); diff --git a/tests/format/markdown/splitCjkText/jsfmt.spec.js b/tests/format/markdown/splitCjkText/jsfmt.spec.js index eb4f5df98..e834740ec 100644 --- a/tests/format/markdown/splitCjkText/jsfmt.spec.js +++ b/tests/format/markdown/splitCjkText/jsfmt.spec.js @@ -7,7 +7,7 @@ const code = Array.from({ length: 6 }) ...previousInputLines, `${base}${space}\n`, ], - [] + [], ) .join(""); // (39 + 40 + 41) * 2 === 40 * 3 * 2 === 40 * 6 @@ -26,5 +26,5 @@ run_spec( ], }, ["markdown"], - { proseWrap: "always" } + { proseWrap: "always" }, ); diff --git a/tests/format/misc/empty/jsfmt.spec.js b/tests/format/misc/empty/jsfmt.spec.js index ef4d6fd04..3ded4b0ec 100644 --- a/tests/format/misc/empty/jsfmt.spec.js +++ b/tests/format/misc/empty/jsfmt.spec.js @@ -39,5 +39,5 @@ run_spec( " \r \r\n \n ", ].map((code) => ({ code, output: "" })), }, - parsers + parsers, ); diff --git a/tests/format/misc/errors/broken-plugin/jsfmt.spec.js b/tests/format/misc/errors/broken-plugin/jsfmt.spec.js index 679409919..89b8d65a1 100644 --- a/tests/format/misc/errors/broken-plugin/jsfmt.spec.js +++ b/tests/format/misc/errors/broken-plugin/jsfmt.spec.js @@ -11,5 +11,5 @@ run_spec( ["missing-comments"], { plugins, - } + }, ); diff --git a/tests/format/misc/errors/flow/interface/jsfmt.spec.js b/tests/format/misc/errors/flow/interface/jsfmt.spec.js index 787aab314..16ebacac6 100644 --- a/tests/format/misc/errors/flow/interface/jsfmt.spec.js +++ b/tests/format/misc/errors/flow/interface/jsfmt.spec.js @@ -12,5 +12,5 @@ run_spec( "declare interface A implements B {}", ], }, - ["flow", "babel-flow"] + ["flow", "babel-flow"], ); diff --git a/tests/format/misc/errors/handlebars/jsfmt.spec.js b/tests/format/misc/errors/handlebars/jsfmt.spec.js index a0f13bd6f..67df7bec7 100644 --- a/tests/format/misc/errors/handlebars/jsfmt.spec.js +++ b/tests/format/misc/errors/handlebars/jsfmt.spec.js @@ -45,5 +45,5 @@ run_spec( ].map((tag) => ({ name: tag, code: `<${tag}>` })), ], }, - ["glimmer"] + ["glimmer"], ); diff --git a/tests/format/misc/errors/invalid/jsfmt.spec.js b/tests/format/misc/errors/invalid/jsfmt.spec.js index a9067b781..3274bf0c2 100644 --- a/tests/format/misc/errors/invalid/jsfmt.spec.js +++ b/tests/format/misc/errors/invalid/jsfmt.spec.js @@ -18,7 +18,7 @@ run_spec( "acorn", "espree", "meriyah", - ] + ], ); run_spec( @@ -41,5 +41,5 @@ run_spec( // https://github.com/eslint/espree/issues/470 // "espree", "meriyah", - ] + ], ); diff --git a/tests/format/misc/errors/js/assignment/jsfmt.spec.js b/tests/format/misc/errors/js/assignment/jsfmt.spec.js index b8c223d56..81a9246bf 100644 --- a/tests/format/misc/errors/js/assignment/jsfmt.spec.js +++ b/tests/format/misc/errors/js/assignment/jsfmt.spec.js @@ -3,7 +3,7 @@ run_spec( importMeta: import.meta, snippets: ["({}) = x;", "let?.[a] = 1"], }, - ["babel", "babel-ts", "acorn", "espree", "meriyah"] + ["babel", "babel-ts", "acorn", "espree", "meriyah"], ); run_spec( @@ -11,7 +11,7 @@ run_spec( importMeta: import.meta, snippets: ["let?.()[a] =1"], }, - ["babel", "babel-ts", "acorn", "espree"] + ["babel", "babel-ts", "acorn", "espree"], ); run_spec( @@ -19,7 +19,7 @@ run_spec( importMeta: import.meta, snippets: ["class Foo extends ((let)[0] = 1) {}"], }, - ["acorn", "espree", "meriyah"] + ["acorn", "espree", "meriyah"], ); run_spec( @@ -27,5 +27,5 @@ run_spec( importMeta: import.meta, snippets: ["export default ((let)[0] = 1);"], }, - ["espree", "meriyah"] + ["espree", "meriyah"], ); diff --git a/tests/format/misc/errors/js/async-await/jsfmt.spec.js b/tests/format/misc/errors/js/async-await/jsfmt.spec.js index ec4737488..4bc563305 100644 --- a/tests/format/misc/errors/js/async-await/jsfmt.spec.js +++ b/tests/format/misc/errors/js/async-await/jsfmt.spec.js @@ -19,7 +19,7 @@ run_spec( "async({ foo33 = 1 });", ], }, - ["babel", "acorn", "espree", "meriyah", "flow"] + ["babel", "acorn", "espree", "meriyah", "flow"], ); run_spec( @@ -30,5 +30,5 @@ run_spec( "async (x = await (2)) => {};", ], }, - ["babel", "acorn", "espree", "flow"] + ["babel", "acorn", "espree", "flow"], ); diff --git a/tests/format/misc/errors/js/decorators/jsfmt.spec.js b/tests/format/misc/errors/js/decorators/jsfmt.spec.js index eeb0b6627..d505b8fab 100644 --- a/tests/format/misc/errors/js/decorators/jsfmt.spec.js +++ b/tests/format/misc/errors/js/decorators/jsfmt.spec.js @@ -17,5 +17,5 @@ run_spec( "export @decorator2 default class A {}", ], }, - ["babel"] + ["babel"], ); diff --git a/tests/format/misc/errors/js/export-default-from/jsfmt.spec.js b/tests/format/misc/errors/js/export-default-from/jsfmt.spec.js index 87ab9dcab..536e921d8 100644 --- a/tests/format/misc/errors/js/export-default-from/jsfmt.spec.js +++ b/tests/format/misc/errors/js/export-default-from/jsfmt.spec.js @@ -8,5 +8,5 @@ run_spec( 'export * as foo, {bar} from "foo";', ], }, - ["babel"] + ["babel"], ); diff --git a/tests/format/misc/errors/js/for-of/jsfmt.spec.js b/tests/format/misc/errors/js/for-of/jsfmt.spec.js index d41ee263f..ca86051f8 100644 --- a/tests/format/misc/errors/js/for-of/jsfmt.spec.js +++ b/tests/format/misc/errors/js/for-of/jsfmt.spec.js @@ -7,7 +7,15 @@ run_spec( "for (let``.bar of []);", ], }, - ["babel", "espree", "meriyah", "flow", "typescript", "babel-flow", "babel-ts"] + [ + "babel", + "espree", + "meriyah", + "flow", + "typescript", + "babel-flow", + "babel-ts", + ], ); run_spec( @@ -26,5 +34,5 @@ run_spec( // "typescript", "babel-flow", "babel-ts", - ] + ], ); diff --git a/tests/format/misc/errors/js/hack-pipeline/jsfmt.spec.js b/tests/format/misc/errors/js/hack-pipeline/jsfmt.spec.js index 86caad2af..37540d343 100644 --- a/tests/format/misc/errors/js/hack-pipeline/jsfmt.spec.js +++ b/tests/format/misc/errors/js/hack-pipeline/jsfmt.spec.js @@ -14,5 +14,5 @@ run_spec( "yield", ].map((code) => `async function * a() { a |> foo(%) |> ${code}}`), }, - ["babel"] + ["babel"], ); diff --git a/tests/format/misc/errors/js/import/jsfmt.spec.js b/tests/format/misc/errors/js/import/jsfmt.spec.js index e3a854030..10b9443a5 100644 --- a/tests/format/misc/errors/js/import/jsfmt.spec.js +++ b/tests/format/misc/errors/js/import/jsfmt.spec.js @@ -8,5 +8,5 @@ run_spec( "new import();", ], }, - ["babel", "meriyah", "flow", "typescript", "babel-flow", "babel-ts"] + ["babel", "meriyah", "flow", "typescript", "babel-flow", "babel-ts"], ); diff --git a/tests/format/misc/errors/js/jsfmt.spec.js b/tests/format/misc/errors/js/jsfmt.spec.js index d0616fcdb..a92fe125d 100644 --- a/tests/format/misc/errors/js/jsfmt.spec.js +++ b/tests/format/misc/errors/js/jsfmt.spec.js @@ -46,5 +46,5 @@ run_spec( "0o16432m;", ], }, - ["babel"] + ["babel"], ); diff --git a/tests/format/misc/errors/js/known-source-type/jsfmt.spec.js b/tests/format/misc/errors/js/known-source-type/jsfmt.spec.js index 732019d1f..b449e11ff 100644 --- a/tests/format/misc/errors/js/known-source-type/jsfmt.spec.js +++ b/tests/format/misc/errors/js/known-source-type/jsfmt.spec.js @@ -16,5 +16,5 @@ run_spec( }, ], }, - ["acorn", "espree", "meriyah"] + ["acorn", "espree", "meriyah"], ); diff --git a/tests/format/misc/errors/js/optional-chaining/jsfmt.spec.js b/tests/format/misc/errors/js/optional-chaining/jsfmt.spec.js index 6cfa6ce92..54340eeb7 100644 --- a/tests/format/misc/errors/js/optional-chaining/jsfmt.spec.js +++ b/tests/format/misc/errors/js/optional-chaining/jsfmt.spec.js @@ -17,5 +17,5 @@ run_spec( "new exists?.(); // undefined", ], }, - ["babel", "acorn", "espree", "meriyah"] + ["babel", "acorn", "espree", "meriyah"], ); diff --git a/tests/format/misc/errors/js/record/jsfmt.spec.js b/tests/format/misc/errors/js/record/jsfmt.spec.js index 58d6a15af..f8b2699ee 100644 --- a/tests/format/misc/errors/js/record/jsfmt.spec.js +++ b/tests/format/misc/errors/js/record/jsfmt.spec.js @@ -9,5 +9,5 @@ run_spec( "#{*e() {}}", ], }, - ["babel", "acorn", "espree", "meriyah"] + ["babel", "acorn", "espree", "meriyah"], ); diff --git a/tests/format/misc/errors/js/reserved-word/jsfmt.spec.js b/tests/format/misc/errors/js/reserved-word/jsfmt.spec.js index 935ece489..7fc2bf0b0 100644 --- a/tests/format/misc/errors/js/reserved-word/jsfmt.spec.js +++ b/tests/format/misc/errors/js/reserved-word/jsfmt.spec.js @@ -3,5 +3,5 @@ run_spec( importMeta: import.meta, snippets: ["class interface {}", 'import interface from "foo";'], }, - ["espree", "meriyah"] + ["espree", "meriyah"], ); diff --git a/tests/format/misc/errors/json/jsfmt.spec.js b/tests/format/misc/errors/json/jsfmt.spec.js index 3a9390d5f..f2b604463 100644 --- a/tests/format/misc/errors/json/jsfmt.spec.js +++ b/tests/format/misc/errors/json/jsfmt.spec.js @@ -40,7 +40,7 @@ run_spec( "----123", ], }, - ["json", "json5", "json-stringify"] + ["json", "json5", "json-stringify"], ); run_spec( @@ -99,5 +99,5 @@ run_spec( "[]", ], }, - ["json"] + ["json"], ); diff --git a/tests/format/misc/errors/json/json-stringify/jsfmt.spec.js b/tests/format/misc/errors/json/json-stringify/jsfmt.spec.js index 5f7a5886a..bebbcba78 100644 --- a/tests/format/misc/errors/json/json-stringify/jsfmt.spec.js +++ b/tests/format/misc/errors/json/json-stringify/jsfmt.spec.js @@ -7,5 +7,5 @@ run_spec( '{"foo": /* comment */ 1}', ], }, - ["json-stringify"] + ["json-stringify"], ); diff --git a/tests/format/misc/errors/typescript/babel-ts/jsfmt.spec.js b/tests/format/misc/errors/typescript/babel-ts/jsfmt.spec.js index c4dcd3b77..afd94f4a8 100644 --- a/tests/format/misc/errors/typescript/babel-ts/jsfmt.spec.js +++ b/tests/format/misc/errors/typescript/babel-ts/jsfmt.spec.js @@ -7,5 +7,5 @@ run_spec( "foo = '100';", ], }, - ["babel-ts"] + ["babel-ts"], ); diff --git a/tests/format/misc/errors/typescript/interface/jsfmt.spec.js b/tests/format/misc/errors/typescript/interface/jsfmt.spec.js index 71ebb8528..738b863fe 100644 --- a/tests/format/misc/errors/typescript/interface/jsfmt.spec.js +++ b/tests/format/misc/errors/typescript/interface/jsfmt.spec.js @@ -9,5 +9,5 @@ run_spec( "interface A implements B {}", ], }, - ["babel-ts", "typescript"] + ["babel-ts", "typescript"], ); diff --git a/tests/format/misc/errors/typescript/jsfmt.spec.js b/tests/format/misc/errors/typescript/jsfmt.spec.js index 8cfd9c7b4..37c8399a1 100644 --- a/tests/format/misc/errors/typescript/jsfmt.spec.js +++ b/tests/format/misc/errors/typescript/jsfmt.spec.js @@ -10,5 +10,5 @@ run_spec( 'let x6 =
>{"foo"}
;', ], }, - ["typescript"] + ["typescript"], ); diff --git a/tests/format/misc/errors/typescript/modifiers/jsfmt.spec.js b/tests/format/misc/errors/typescript/modifiers/jsfmt.spec.js index 237b30b75..99834a963 100644 --- a/tests/format/misc/errors/typescript/modifiers/jsfmt.spec.js +++ b/tests/format/misc/errors/typescript/modifiers/jsfmt.spec.js @@ -7,7 +7,7 @@ run_spec( snippets: [ // Only `readonly` allowed in some places ...POSSIBLE_MODIFIERS.filter( - (modifier) => modifier !== "readonly" + (modifier) => modifier !== "readonly", ).flatMap((modifier) => [ outdent` interface Foo { @@ -39,18 +39,18 @@ run_spec( // `TSInterfaceDeclaration`, only `declare` and `export` allowed ...POSSIBLE_MODIFIERS.filter( - (modifier) => modifier !== "declare" && modifier !== "export" + (modifier) => modifier !== "declare" && modifier !== "export", ).map( (modifier) => outdent` ${modifier} interface Foo {} - ` + `, ), // `TSTypeParameter`, only `in`, `out`, and `const` allowed in type parameter ...POSSIBLE_MODIFIERS.filter( (modifier) => - modifier !== "in" && modifier !== "out" && modifier !== "const" + modifier !== "in" && modifier !== "out" && modifier !== "const", ).map((modifier) => `interface Foo<${modifier} T> {}`), ...["declare", "readonly"].map( @@ -59,7 +59,7 @@ run_spec( class Foo { ${modifier} method() {} } - ` + `, ), outdent` class Foo { @@ -74,7 +74,7 @@ run_spec( // `TSModuleDeclaration` ...POSSIBLE_MODIFIERS.filter( - (modifier) => modifier !== "declare" && modifier !== "export" + (modifier) => modifier !== "declare" && modifier !== "export", ).flatMap((modifier) => [ `${modifier} module Foo {}`, `${modifier} namespace Foo {}`, @@ -85,7 +85,7 @@ run_spec( (modifier) => modifier !== "declare" && modifier !== "const" && - modifier !== "export" + modifier !== "export", ).map((modifier) => `${modifier} enum Foo {}`), // `TSParameterProperty` @@ -99,9 +99,9 @@ run_spec( modifier !== "private" && modifier !== "protected" && modifier !== "public" && - modifier !== "readonly" + modifier !== "readonly", ).map( - (modifier) => `class Foo { constructor(${modifier} parameter) {} }` + (modifier) => `class Foo { constructor(${modifier} parameter) {} }`, ), 'class Foo {["constructor"](private parameter) {}}', "class Foo {['constructor'](private parameter) {}}", @@ -111,7 +111,7 @@ run_spec( // `TSPropertySignature` ...POSSIBLE_MODIFIERS.filter((modifier) => modifier !== "readonly").map( - (modifier) => `type Foo = {${modifier} bar};` + (modifier) => `type Foo = {${modifier} bar};`, ), // `TSIndexSignature` @@ -122,5 +122,5 @@ run_spec( `, ], }, - ["babel-ts", "typescript"] + ["babel-ts", "typescript"], ); diff --git a/tests/format/misc/errors/typescript/module-declaration/jsfmt.spec.js b/tests/format/misc/errors/typescript/module-declaration/jsfmt.spec.js index 815a2e251..70171c096 100644 --- a/tests/format/misc/errors/typescript/module-declaration/jsfmt.spec.js +++ b/tests/format/misc/errors/typescript/module-declaration/jsfmt.spec.js @@ -3,5 +3,5 @@ run_spec( importMeta: import.meta, snippets: ['namespace "a" {}', 'namespace "a";', "namespace a;"], }, - ["babel-ts", "typescript"] + ["babel-ts", "typescript"], ); diff --git a/tests/format/misc/errors/typescript/tuple/jsfmt.spec.js b/tests/format/misc/errors/typescript/tuple/jsfmt.spec.js index c46685eff..4ef2f010d 100644 --- a/tests/format/misc/errors/typescript/tuple/jsfmt.spec.js +++ b/tests/format/misc/errors/typescript/tuple/jsfmt.spec.js @@ -8,5 +8,5 @@ run_spec( "type T = [x: A];", ], }, - ["babel-ts", "typescript"] + ["babel-ts", "typescript"], ); diff --git a/tests/format/misc/plugins/embed-async-printer/jsfmt.spec.js b/tests/format/misc/plugins/embed-async-printer/jsfmt.spec.js index 149bb3b47..8428b522f 100644 --- a/tests/format/misc/plugins/embed-async-printer/jsfmt.spec.js +++ b/tests/format/misc/plugins/embed-async-printer/jsfmt.spec.js @@ -2,7 +2,7 @@ const plugins = await Promise.all( [ "../../../../config/prettier-plugins/prettier-plugin-async-printer/index.cjs", "../../../../config/prettier-plugins/prettier-plugin-uppercase-rocks/index.js", - ].map(async (plugin) => (await import(plugin)).default) + ].map(async (plugin) => (await import(plugin)).default), ); run_spec(import.meta, ["markdown"], { plugins }); diff --git a/tests/format/misc/require-pragma/js/jsfmt.spec.js b/tests/format/misc/require-pragma/js/jsfmt.spec.js index 9c647ddef..5665ec307 100644 --- a/tests/format/misc/require-pragma/js/jsfmt.spec.js +++ b/tests/format/misc/require-pragma/js/jsfmt.spec.js @@ -4,5 +4,5 @@ run_spec( snippets: ["\uFEFF#!/usr/bin/env node\n/** @format */\nprettier"], }, ["flow", "babel", "typescript"], - { requirePragma: true } + { requirePragma: true }, ); diff --git a/tests/format/typescript/tsx/comma/jsfmt.spec.js b/tests/format/typescript/tsx/comma/jsfmt.spec.js index 8e6ac1416..7d2f2b5f6 100644 --- a/tests/format/typescript/tsx/comma/jsfmt.spec.js +++ b/tests/format/typescript/tsx/comma/jsfmt.spec.js @@ -16,5 +16,5 @@ run_spec( undefined, ].map((filename) => ({ code, filename, name: filename ?? "unnamed" })), }, - ["typescript"] + ["typescript"], ); diff --git a/tests/format/typescript/typeparams/empty-parameters-with-arrow-function/jsfmt.spec.js b/tests/format/typescript/typeparams/empty-parameters-with-arrow-function/jsfmt.spec.js index f25b63fe9..a1f36b8ad 100644 --- a/tests/format/typescript/typeparams/empty-parameters-with-arrow-function/jsfmt.spec.js +++ b/tests/format/typescript/typeparams/empty-parameters-with-arrow-function/jsfmt.spec.js @@ -2,5 +2,5 @@ run_spec( import.meta, ["typescript", "flow"], // #13817 require those options to reproduce - { arrowParens: "avoid", trailingComma: "all" } + { arrowParens: "avoid", trailingComma: "all" }, ); diff --git a/tests/format/vue/multiparser/jsfmt.spec.js b/tests/format/vue/multiparser/jsfmt.spec.js index d09b997b4..17d8733c4 100644 --- a/tests/format/vue/multiparser/jsfmt.spec.js +++ b/tests/format/vue/multiparser/jsfmt.spec.js @@ -20,5 +20,5 @@ run_spec( }, ], }, - ["vue"] + ["vue"], ); diff --git a/tests/format/vue/with-plugins/jsfmt.spec.js b/tests/format/vue/with-plugins/jsfmt.spec.js index ba301bed7..c16b2a286 100644 --- a/tests/format/vue/with-plugins/jsfmt.spec.js +++ b/tests/format/vue/with-plugins/jsfmt.spec.js @@ -1,7 +1,7 @@ const plugins = await Promise.all( [ "../../../config/prettier-plugins/prettier-plugin-uppercase-rocks/index.js", - ].map(async (plugin) => (await import(plugin)).default) + ].map(async (plugin) => (await import(plugin)).default), ); run_spec(import.meta, ["vue"], { plugins }); diff --git a/tests/integration/__tests__/arg-parsing.js b/tests/integration/__tests__/arg-parsing.js index 845c0b430..fa5a0c72a 100644 --- a/tests/integration/__tests__/arg-parsing.js +++ b/tests/integration/__tests__/arg-parsing.js @@ -53,7 +53,7 @@ describe("allow overriding flags", () => { runCli( "cli/arg-parsing", ["--tab-width=1", "--tab-width=3", "--parser=babel"], - { input: "function a() { b }" } + { input: "function a() { b }" }, ).test({ stdout: "function a() {\n b;\n}", status: 0, diff --git a/tests/integration/__tests__/bundle.js b/tests/integration/__tests__/bundle.js index 50675ddc0..7c1f7255a 100644 --- a/tests/integration/__tests__/bundle.js +++ b/tests/integration/__tests__/bundle.js @@ -38,7 +38,7 @@ describe("standalone", () => { let esmPlugins; beforeAll(async () => { esmStandalone = await importModule( - path.join(distDirectory, "standalone.mjs") + path.join(distDirectory, "standalone.mjs"), ); esmPlugins = await Promise.all( fastGlob @@ -46,7 +46,7 @@ describe("standalone", () => { .map(async (file) => { const plugin = await importModule(file); return plugin.default ?? plugin; - }) + }), ); }); @@ -83,8 +83,8 @@ test("global objects", async () => { const sandbox = createSandBox({ files: [file] }); return Object.fromEntries( Object.entries(sandbox).filter( - ([property]) => !allowedGlobalObjects.has(property) - ) + ([property]) => !allowedGlobalObjects.has(property), + ), ); }; @@ -98,28 +98,28 @@ test("global objects", async () => { test("Commonjs version", () => { const prettierCommonjsVersion = require(path.join( distDirectory, - "index.cjs" + "index.cjs", )); expect(Object.keys(prettierCommonjsVersion).sort()).toEqual( Object.keys(prettier) .filter((key) => key !== "default" && key !== "__internal") - .sort() + .sort(), ); expect(typeof prettierCommonjsVersion.format).toBe("function"); expect(Object.keys(prettierCommonjsVersion.doc)).toEqual( - Object.keys(prettier.doc).filter((key) => key !== "default") + Object.keys(prettier.doc).filter((key) => key !== "default"), ); expect(typeof prettierCommonjsVersion.doc.builders.fill).toBe("function"); expect(Object.keys(prettierCommonjsVersion.util)).toEqual( - Object.keys(prettier.util) + Object.keys(prettier.util), ); expect(typeof prettierCommonjsVersion.util.getStringWidth).toBe("function"); expect(Object.keys(prettierCommonjsVersion.__debug).sort()).toEqual( - Object.keys(prettier.__debug).sort() + Object.keys(prettier.__debug).sort(), ); expect(typeof prettierCommonjsVersion.__debug.parse).toBe("function"); diff --git a/tests/integration/__tests__/cache.js b/tests/integration/__tests__/cache.js index 3fe016210..1a9103f55 100644 --- a/tests/integration/__tests__/cache.js +++ b/tests/integration/__tests__/cache.js @@ -13,7 +13,7 @@ describe("--cache option", () => { const dir = resolveDir("cli/cache"); const defaultCacheFile = path.join( dir, - "node_modules/.cache/prettier/.prettier-cache" + "node_modules/.cache/prettier/.prettier-cache", ); const nonDefaultCacheFileName = ".non-default-cache-file"; @@ -65,7 +65,7 @@ describe("--cache option", () => { "*.js", ]); expect(stderr.trim()).toBe( - '[error] Invalid --cache-strategy value. Expected "content" or "metadata", but received "invalid".' + '[error] Invalid --cache-strategy value. Expected "content" or "metadata", but received "invalid".', ); }); @@ -73,7 +73,7 @@ describe("--cache option", () => { const { stderr } = await runCliWithoutGitignore( dir, ["--cache", "--stdin-filepath", "foo.js"], - { input: "const a = a;" } + { input: "const a = a;" }, ); expect(stderr.trim()).toBe("[error] `--cache` cannot be used with stdin."); }); @@ -84,10 +84,10 @@ describe("--cache option", () => { ["foo.js", "--cache-strategy", "content"], { input: "const a = a;", - } + }, ); expect(stderr.trim()).toBe( - "[error] `--cache-strategy` cannot be used without `--cache`." + "[error] `--cache-strategy` cannot be used without `--cache`.", ); }); @@ -100,8 +100,8 @@ describe("--cache option", () => { ]); expect(stderr.trim()).toEqual( expect.stringMatching( - /\[error] Resolved --cache-location '.+' is a directory/ - ) + /\[error] Resolved --cache-location '.+' is a directory/, + ), ); }); @@ -109,7 +109,7 @@ describe("--cache option", () => { it("creates default cache file named `node_modules/.cache/prettier/.prettier-cache`", async () => { await expect(fs.stat(defaultCacheFile)).rejects.toHaveProperty( "code", - "ENOENT" + "ENOENT", ); await runCliWithoutGitignore(dir, [ "--cache", @@ -132,7 +132,7 @@ describe("--cache option", () => { expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms$/), - ]) + ]), ); const { stdout: secondStdout } = await runCliWithoutGitignore(dir, [ @@ -146,7 +146,7 @@ describe("--cache option", () => { expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms \(cached\)$/), expect.stringMatching(/^b\.js .+ms \(cached\)$/), - ]) + ]), ); }); @@ -160,13 +160,13 @@ describe("--cache option", () => { ]; const { stdout: firstStdout } = await runCliWithoutGitignore( dir, - cliArguments + cliArguments, ); expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms$/), - ]) + ]), ); // Update `a.js` @@ -174,14 +174,14 @@ describe("--cache option", () => { const { stdout: secondStdout } = await runCliWithoutGitignore( dir, - cliArguments + cliArguments, ); expect(secondStdout.split("\n")).toEqual( // the cache of `b.js` is only available. expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms \(cached\)$/), - ]) + ]), ); }); @@ -195,13 +195,13 @@ describe("--cache option", () => { ]; const { stdout: firstStdout } = await runCliWithoutGitignore( dir, - cliArguments + cliArguments, ); expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms$/), - ]) + ]), ); // update timestamp @@ -210,14 +210,14 @@ describe("--cache option", () => { const { stdout: secondStdout } = await runCliWithoutGitignore( dir, - cliArguments + cliArguments, ); expect(secondStdout.split("\n")).toEqual( // the cache of `b.js` is only available. expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms \(cached\)$/), - ]) + ]), ); }); @@ -233,7 +233,7 @@ describe("--cache option", () => { expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms$/), - ]) + ]), ); const { stdout: secondStdout } = await runCliWithoutGitignore(dir, [ @@ -249,7 +249,7 @@ describe("--cache option", () => { expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms$/), - ]) + ]), ); }); @@ -272,7 +272,7 @@ describe("--cache option", () => { expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms \(cached\)$/), - ]) + ]), ); }); @@ -302,13 +302,13 @@ describe("--cache option", () => { const { stdout: thirdStdout } = await runCliWithoutGitignore( dir, - cliArguments + cliArguments, ); expect(thirdStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms \(cached\)$/), - ]) + ]), ); }); @@ -324,18 +324,18 @@ describe("--cache option", () => { mockWriteFileErrors: { "a.js": "EACCES: permission denied.", }, - } + }, ); expect(firstStatus).toBe(2); expect(firstStderr).toBe( '[error] Unable to write file "a.js":\n' + - "[error] EACCES: permission denied. (mocked error)" + "[error] EACCES: permission denied. (mocked error)", ); expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms$/), - ]) + ]), ); const { stdout: secondStdout } = await runCliWithoutGitignore(dir, [ @@ -366,7 +366,7 @@ describe("--cache option", () => { it("creates default cache file named `node_modules/.cache/prettier/.prettier-cache`", async () => { await expect(fs.stat(defaultCacheFile)).rejects.toHaveProperty( "code", - "ENOENT" + "ENOENT", ); await runCliWithoutGitignore(dir, [ "--cache", @@ -387,24 +387,24 @@ describe("--cache option", () => { ]; const { stdout: firstStdout } = await runCliWithoutGitignore( dir, - cliArguments + cliArguments, ); expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms$/), - ]) + ]), ); const { stdout: secondStdout } = await runCliWithoutGitignore( dir, - cliArguments + cliArguments, ); expect(secondStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms \(cached\)$/), expect.stringMatching(/^b\.js .+ms \(cached\)$/), - ]) + ]), ); }); @@ -418,13 +418,13 @@ describe("--cache option", () => { ]; const { stdout: firstStdout } = await runCliWithoutGitignore( dir, - cliArguments + cliArguments, ); expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms$/), - ]) + ]), ); // Update `a.js` @@ -432,14 +432,14 @@ describe("--cache option", () => { const { stdout: secondStdout } = await runCliWithoutGitignore( dir, - cliArguments + cliArguments, ); expect(secondStdout.split("\n")).toEqual( // the cache of `b.js` is only available. expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms \(cached\)$/), - ]) + ]), ); }); @@ -453,13 +453,13 @@ describe("--cache option", () => { ]; const { stdout: firstStdout } = await runCliWithoutGitignore( dir, - cliArguments + cliArguments, ); expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms$/), - ]) + ]), ); // update timestamp @@ -468,13 +468,13 @@ describe("--cache option", () => { const { stdout: secondStdout } = await runCliWithoutGitignore( dir, - cliArguments + cliArguments, ); expect(secondStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms \(cached\)$/), expect.stringMatching(/^b\.js .+ms \(cached\)$/), - ]) + ]), ); }); @@ -490,7 +490,7 @@ describe("--cache option", () => { expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms$/), - ]) + ]), ); const { stdout: secondStdout } = await runCliWithoutGitignore(dir, [ @@ -506,7 +506,7 @@ describe("--cache option", () => { expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms$/), - ]) + ]), ); }); @@ -529,7 +529,7 @@ describe("--cache option", () => { expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms \(cached\)$/), - ]) + ]), ); }); @@ -559,13 +559,13 @@ describe("--cache option", () => { const { stdout: thirdStdout } = await runCliWithoutGitignore( dir, - cliArguments + cliArguments, ); expect(thirdStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms \(cached\)$/), - ]) + ]), ); }); @@ -581,18 +581,18 @@ describe("--cache option", () => { mockWriteFileErrors: { "a.js": "EACCES: permission denied.", }, - } + }, ); expect(firstStatus).toBe(2); expect(firstStderr).toBe( '[error] Unable to write file "a.js":\n' + - "[error] EACCES: permission denied. (mocked error)" + "[error] EACCES: permission denied. (mocked error)", ); expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms$/), - ]) + ]), ); const { stdout: secondStdout } = await runCliWithoutGitignore(dir, [ @@ -617,7 +617,7 @@ describe("--cache option", () => { it("doesn't create default cache file when `--cache-location` exists", async () => { await expect(fs.stat(defaultCacheFile)).rejects.toHaveProperty( "code", - "ENOENT" + "ENOENT", ); await runCliWithoutGitignore(dir, [ "--cache", @@ -627,7 +627,7 @@ describe("--cache option", () => { ]); await expect(fs.stat(defaultCacheFile)).rejects.toHaveProperty( "code", - "ENOENT" + "ENOENT", ); }); @@ -639,7 +639,7 @@ describe("--cache option", () => { "*.js", ]); expect(stderr.trim()).toEqual( - expect.stringMatching(/\[error] '.+' isn't a valid JSON file/) + expect.stringMatching(/\[error] '.+' isn't a valid JSON file/), ); }); @@ -647,7 +647,7 @@ describe("--cache option", () => { it("creates the cache file at location specified by `--cache-location`", async () => { await expect(fs.stat(nonDefaultCacheFilePath)).rejects.toHaveProperty( "code", - "ENOENT" + "ENOENT", ); await runCliWithoutGitignore(dir, [ "--cache", @@ -656,7 +656,7 @@ describe("--cache option", () => { "*.js", ]); await expect( - fs.stat(nonDefaultCacheFilePath) + fs.stat(nonDefaultCacheFilePath), ).resolves.not.toThrowError(); }); @@ -670,24 +670,24 @@ describe("--cache option", () => { ]; const { stdout: firstStdout } = await runCliWithoutGitignore( dir, - cliArguments + cliArguments, ); expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), expect.stringMatching(/^b\.js .+ms$/), - ]) + ]), ); const { stdout: secondStdout } = await runCliWithoutGitignore( dir, - cliArguments + cliArguments, ); expect(secondStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms \(cached\)$/), expect.stringMatching(/^b\.js .+ms \(cached\)$/), - ]) + ]), ); }); }); diff --git a/tests/integration/__tests__/check.js b/tests/integration/__tests__/check.js index 62a3b110f..f84e39579 100644 --- a/tests/integration/__tests__/check.js +++ b/tests/integration/__tests__/check.js @@ -25,7 +25,7 @@ describe("--checks works in CI just as in a non-TTY mode", () => { { stdoutIsTTY: true, ci: true, - } + }, ).test({ status: 1, }); @@ -35,7 +35,7 @@ describe("--checks works in CI just as in a non-TTY mode", () => { ["--check", "formatted.js", "unformatted.js"], { stdoutIsTTY: false, - } + }, ).test({ status: 1, }); diff --git a/tests/integration/__tests__/config-invalid.js b/tests/integration/__tests__/config-invalid.js index e67cc95a2..89515ce82 100644 --- a/tests/integration/__tests__/config-invalid.js +++ b/tests/integration/__tests__/config-invalid.js @@ -23,7 +23,7 @@ describe("throw error with invalid config format", () => { runCli("cli/config/invalid", ["--config", "type-error/.prettierrc"]).test({ status: "non-zero", stderr: expect.stringContaining( - "Config is only allowed to be an object, but received number in" + "Config is only allowed to be an object, but received number in", ), }); }); @@ -107,7 +107,7 @@ describe("Invalid json file", () => { ` .split("\n") .map((line) => `[error] ${line}`) - .join("\n") + .join("\n"), ), }); }); @@ -132,7 +132,7 @@ describe("Invalid toml file", () => { ` .split("\n") .map((line) => `[error] ${line}`) - .join("\n") + .join("\n"), /* cSpell:enable */ ), }); diff --git a/tests/integration/__tests__/config-resolution.js b/tests/integration/__tests__/config-resolution.js index 5829f238c..2885bad8b 100644 --- a/tests/integration/__tests__/config-resolution.js +++ b/tests/integration/__tests__/config-resolution.js @@ -7,13 +7,13 @@ const { __dirname } = createEsmUtils(import.meta); test("resolves configuration from external files and overrides by extname", async () => { await expect( prettier.resolveConfig( - path.join(__dirname, "../cli/config/external-overrides/file.js") - ) + path.join(__dirname, "../cli/config/external-overrides/file.js"), + ), ).resolves.toEqual({ tabWidth: 3, semi: false }); await expect( prettier.resolveConfig( - path.join(__dirname, "../cli/config/external-overrides/file.ts") - ) + path.join(__dirname, "../cli/config/external-overrides/file.ts"), + ), ).resolves.toEqual({ tabWidth: 3, semi: true }); }); @@ -96,7 +96,7 @@ test("API resolveConfig with file arg", async () => { test("API resolveConfig with file arg and extension override", async () => { const file = path.resolve( - path.join(__dirname, "../cli/config/no-config/file.ts") + path.join(__dirname, "../cli/config/no-config/file.ts"), ); await expect(prettier.resolveConfig(file)).resolves.toMatchObject({ semi: true, @@ -105,7 +105,7 @@ test("API resolveConfig with file arg and extension override", async () => { test("API resolveConfig with file arg and .editorconfig", async () => { const file = path.resolve( - path.join(__dirname, "../cli/config/editorconfig/file.js") + path.join(__dirname, "../cli/config/editorconfig/file.js"), ); await expect(prettier.resolveConfig(file)).resolves.toMatchObject({ @@ -113,7 +113,7 @@ test("API resolveConfig with file arg and .editorconfig", async () => { }); await expect( - prettier.resolveConfig(file, { editorconfig: true }) + prettier.resolveConfig(file, { editorconfig: true }), ).resolves.toMatchObject({ useTabs: true, tabWidth: 8, @@ -123,17 +123,17 @@ test("API resolveConfig with file arg and .editorconfig", async () => { test("API resolveConfig with file arg and .editorconfig (key = unset)", async () => { const file = path.resolve( - path.join(__dirname, "../cli/config/editorconfig/tab_width=unset.js") + path.join(__dirname, "../cli/config/editorconfig/tab_width=unset.js"), ); await expect( - prettier.resolveConfig(file, { editorconfig: true }) + prettier.resolveConfig(file, { editorconfig: true }), ).resolves.not.toMatchObject({ tabWidth: "unset" }); }); test("API resolveConfig with nested file arg and .editorconfig", async () => { const file = path.resolve( - path.join(__dirname, "../cli/config/editorconfig/lib/file.js") + path.join(__dirname, "../cli/config/editorconfig/lib/file.js"), ); await expect(prettier.resolveConfig(file)).resolves.toMatchObject({ @@ -141,7 +141,7 @@ test("API resolveConfig with nested file arg and .editorconfig", async () => { }); await expect( - prettier.resolveConfig(file, { editorconfig: true }) + prettier.resolveConfig(file, { editorconfig: true }), ).resolves.toMatchObject({ useTabs: false, tabWidth: 2, @@ -151,7 +151,7 @@ test("API resolveConfig with nested file arg and .editorconfig", async () => { test("API resolveConfig with nested file arg and .editorconfig and indent_size = tab", async () => { const file = path.resolve( - path.join(__dirname, "../cli/config/editorconfig/lib/indent_size=tab.js") + path.join(__dirname, "../cli/config/editorconfig/lib/indent_size=tab.js"), ); await expect(prettier.resolveConfig(file)).resolves.toMatchObject({ @@ -159,7 +159,7 @@ test("API resolveConfig with nested file arg and .editorconfig and indent_size = }); await expect( - prettier.resolveConfig(file, { editorconfig: true }) + prettier.resolveConfig(file, { editorconfig: true }), ).resolves.toMatchObject({ useTabs: false, tabWidth: 8, @@ -174,7 +174,7 @@ test("API clearConfigCache", () => { test("API resolveConfig overrides work with dotfiles", async () => { const folder = path.join(__dirname, "../cli/config/dot-overrides"); await expect( - prettier.resolveConfig(path.join(folder, ".foo.json")) + prettier.resolveConfig(path.join(folder, ".foo.json")), ).resolves.toMatchObject({ tabWidth: 4, }); @@ -191,7 +191,7 @@ test("API resolveConfig overrides work with absolute paths", async () => { test("API resolveConfig overrides excludeFiles", async () => { const notOverride = path.join( __dirname, - "../cli/config/overrides-exclude-files/foo" + "../cli/config/overrides-exclude-files/foo", ); await expect(prettier.resolveConfig(notOverride)).resolves.toMatchObject({ singleQuote: true, @@ -200,7 +200,7 @@ test("API resolveConfig overrides excludeFiles", async () => { const singleQuote = path.join( __dirname, - "../cli/config/overrides-exclude-files/single-quote.js" + "../cli/config/overrides-exclude-files/single-quote.js", ); await expect(prettier.resolveConfig(singleQuote)).resolves.toMatchObject({ singleQuote: true, @@ -209,7 +209,7 @@ test("API resolveConfig overrides excludeFiles", async () => { const doubleQuote = path.join( __dirname, - "../cli/config/overrides-exclude-files/double-quote.js" + "../cli/config/overrides-exclude-files/double-quote.js", ); await expect(prettier.resolveConfig(doubleQuote)).resolves.toMatchObject({ singleQuote: false, @@ -219,7 +219,7 @@ test("API resolveConfig overrides excludeFiles", async () => { test("API resolveConfig removes $schema option", async () => { const file = path.resolve( - path.join(__dirname, "../cli/config/$schema/index.js") + path.join(__dirname, "../cli/config/$schema/index.js"), ); await expect(prettier.resolveConfig(file)).resolves.toEqual({ tabWidth: 42, @@ -230,7 +230,7 @@ test("API resolveConfig resolves relative path values based on config filepath", const currentDir = path.join(__dirname, "../cli/config/resolve-relative"); const parentDir = path.resolve(currentDir, ".."); await expect( - prettier.resolveConfig(`${currentDir}/index.js`) + prettier.resolveConfig(`${currentDir}/index.js`), ).resolves.toMatchObject({ plugins: [path.join(parentDir, "path-to-plugin")], }); @@ -240,18 +240,24 @@ test("API resolveConfig de-references to an external module", async () => { const config = { printWidth: 77, semi: false }; await expect( prettier.resolveConfig( - path.join(__dirname, "../cli/config/external-config/cjs-package/index.js") - ) + path.join( + __dirname, + "../cli/config/external-config/cjs-package/index.js", + ), + ), ).resolves.toEqual(config); await expect( prettier.resolveConfig( - path.join(__dirname, "../cli/config/external-config/esm-package/index.js") - ) + path.join( + __dirname, + "../cli/config/external-config/esm-package/index.js", + ), + ), ).resolves.toEqual(config); await expect( prettier.resolveConfig( - path.join(__dirname, "../cli/config/external-config/esm-file/index.js") - ) + path.join(__dirname, "../cli/config/external-config/esm-file/index.js"), + ), ).resolves.toEqual(config); }); diff --git a/tests/integration/__tests__/debug-api.js b/tests/integration/__tests__/debug-api.js index 5ec0493c4..5431f3b09 100644 --- a/tests/integration/__tests__/debug-api.js +++ b/tests/integration/__tests__/debug-api.js @@ -40,7 +40,7 @@ describe("API", () => { const doc2 = new Function( `{ ${Object.keys(builders)} }`, - `return ${formatResultFromDoc}` + `return ${formatResultFromDoc}`, )(builders); const { formatted: stringFromDoc2 } = await printDocToString(doc2, options); @@ -64,11 +64,11 @@ describe("API", () => { } = builders; expect(await formatDoc([indent(hardline), indent(literalline)])).toBe( - "[indent(hardline), indent(literalline)]" + "[indent(hardline), indent(literalline)]", ); expect( - await formatDoc(fill(["foo", hardline, "bar", literalline, "baz"])) + await formatDoc(fill(["foo", hardline, "bar", literalline, "baz"])), ).toBe('fill(["foo", hardline, "bar", literalline, "baz"])'); /* @@ -79,20 +79,20 @@ describe("API", () => { expect( await formatDoc( // The argument of fill must not be passed to cleanDoc because it's not a doc - fill(cleanDoc(["foo", literalline, "bar"])) // invalid fill - ) + fill(cleanDoc(["foo", literalline, "bar"])), // invalid fill + ), ).toBe('fill(["foo", literallineWithoutBreakParent, breakParent, "bar"])'); expect( - await formatDoc(indentIfBreak(group(["1", line, "2"]), { groupId: "Q" })) + await formatDoc(indentIfBreak(group(["1", line, "2"]), { groupId: "Q" })), ).toBe('indentIfBreak(group(["1", line, "2"]), { groupId: "Q" })'); expect(await formatDoc(label("foo", group(["1", line, "2"])))).toBe( - 'label("foo", group(["1", line, "2"]))' + 'label("foo", group(["1", line, "2"]))', ); expect( - await formatDoc([ifBreak("a", "b"), ifBreak("a"), ifBreak("", "b")]) + await formatDoc([ifBreak("a", "b"), ifBreak("a"), ifBreak("", "b")]), ).toBe('[ifBreak("a", "b"), ifBreak("a"), ifBreak("", "b")]'); }); }); diff --git a/tests/integration/__tests__/debug-check.js b/tests/integration/__tests__/debug-check.js index f67783bc0..d0f9a58b9 100644 --- a/tests/integration/__tests__/debug-check.js +++ b/tests/integration/__tests__/debug-check.js @@ -33,7 +33,7 @@ describe("should not exit non-zero for already prettified code with --debug-chec runCli("cli/debug-check", ["issue-4599.js", "--debug-check", "--check"]).test( { status: 0, - } + }, ); }); diff --git a/tests/integration/__tests__/doc-printer.js b/tests/integration/__tests__/doc-printer.js index f66385097..84d3a0834 100644 --- a/tests/integration/__tests__/doc-printer.js +++ b/tests/integration/__tests__/doc-printer.js @@ -20,6 +20,6 @@ test("`ifBreak` inside `group`", () => { ]; expect( - docs.map((doc) => docToString(doc, { printWidth: FLAT_TEXT.length })) + docs.map((doc) => docToString(doc, { printWidth: FLAT_TEXT.length })), ).toStrictEqual(Array.from({ length: docs.length }, () => FLAT_TEXT)); }); diff --git a/tests/integration/__tests__/file-info.js b/tests/integration/__tests__/file-info.js index 1031fa42d..3cf7face4 100644 --- a/tests/integration/__tests__/file-info.js +++ b/tests/integration/__tests__/file-info.js @@ -118,7 +118,7 @@ describe("extracts file-info with inferredParser=foo when a plugin is hand-picke test("API getFileInfo with no args", async () => { await expect(prettier.getFileInfo()).rejects.toThrow( - new TypeError("expect `filePath` to be a string, got `undefined`") + new TypeError("expect `filePath` to be a string, got `undefined`"), ); }); @@ -134,9 +134,9 @@ describe("API getFileInfo resolveConfig", () => { ["foo", "js", "bar", "css"].map((ext) => [ ext, path.resolve( - path.join(__dirname, `../cli/with-resolve-config/file.${ext}`) + path.join(__dirname, `../cli/with-resolve-config/file.${ext}`), ), - ]) + ]), ); test("{resolveConfig: undefined}", async () => { await expect(prettier.getFileInfo(files.foo)).resolves.toMatchObject({ @@ -158,25 +158,25 @@ describe("API getFileInfo resolveConfig", () => { }); test("{resolveConfig: true}", async () => { await expect( - prettier.getFileInfo(files.foo, { resolveConfig: true }) + prettier.getFileInfo(files.foo, { resolveConfig: true }), ).resolves.toMatchObject({ ignored: false, inferredParser: "foo-parser", }); await expect( - prettier.getFileInfo(files.js, { resolveConfig: true }) + prettier.getFileInfo(files.js, { resolveConfig: true }), ).resolves.toMatchObject({ ignored: false, inferredParser: "override-js-parser", }); await expect( - prettier.getFileInfo(files.bar, { resolveConfig: true }) + prettier.getFileInfo(files.bar, { resolveConfig: true }), ).resolves.toMatchObject({ ignored: false, inferredParser: null, }); await expect( - prettier.getFileInfo(files.css, { resolveConfig: true }) + prettier.getFileInfo(files.css, { resolveConfig: true }), ).resolves.toMatchObject({ ignored: false, inferredParser: "css", @@ -189,7 +189,7 @@ describe("API getFileInfo resolveConfig when no config is present", () => { ["foo", "js"].map((ext) => [ ext, path.resolve(path.join(__dirname, `../cli/non-exists-dir/file.${ext}`)), - ]) + ]), ); test("{resolveConfig: undefined}", async () => { await expect(prettier.getFileInfo(files.foo)).resolves.toMatchObject({ @@ -203,13 +203,13 @@ describe("API getFileInfo resolveConfig when no config is present", () => { }); test("{resolveConfig: true}", async () => { await expect( - prettier.getFileInfo(files.foo, { resolveConfig: true }) + prettier.getFileInfo(files.foo, { resolveConfig: true }), ).resolves.toMatchObject({ ignored: false, inferredParser: null, }); await expect( - prettier.getFileInfo(files.js, { resolveConfig: true }) + prettier.getFileInfo(files.js, { resolveConfig: true }), ).resolves.toMatchObject({ ignored: false, inferredParser: "babel", @@ -221,11 +221,11 @@ test("API getFileInfo with ignorePath", async () => { const file = path.resolve( path.join( __dirname, - "../cli/ignore-path/file-info-test/ignored-by-customignore.js" - ) + "../cli/ignore-path/file-info-test/ignored-by-customignore.js", + ), ); const ignorePath = path.resolve( - path.join(__dirname, "../cli/ignore-path/file-info-test/.customignore") + path.join(__dirname, "../cli/ignore-path/file-info-test/.customignore"), ); await expect(prettier.getFileInfo(file)).resolves.toMatchObject({ @@ -234,7 +234,7 @@ test("API getFileInfo with ignorePath", async () => { }); await expect( - prettier.getFileInfo(file, { ignorePath }) + prettier.getFileInfo(file, { ignorePath }), ).resolves.toMatchObject({ ignored: true, inferredParser: null, @@ -245,11 +245,11 @@ test("API getFileInfo with ignorePath containing relative paths", async () => { const file = path.resolve( path.join( __dirname, - "../cli/ignore-relative-path/level1-glob/level2-glob/level3-glob/shouldNotBeFormat.js" - ) + "../cli/ignore-relative-path/level1-glob/level2-glob/level3-glob/shouldNotBeFormat.js", + ), ); const ignorePath = path.resolve( - path.join(__dirname, "../cli/ignore-relative-path/.prettierignore") + path.join(__dirname, "../cli/ignore-relative-path/.prettierignore"), ); await expect(prettier.getFileInfo(file)).resolves.toMatchObject({ @@ -258,7 +258,7 @@ test("API getFileInfo with ignorePath containing relative paths", async () => { }); await expect( - prettier.getFileInfo(file, { ignorePath }) + prettier.getFileInfo(file, { ignorePath }), ).resolves.toMatchObject({ ignored: true, inferredParser: null, @@ -293,7 +293,7 @@ describe("API getFileInfo with ignorePath", () => { test("with absolute filePath", async () => { const { ignored } = await prettier.getFileInfo( path.resolve(filePath), - options + options, ); expect(ignored).toBe(true); }); @@ -301,7 +301,7 @@ describe("API getFileInfo with ignorePath", () => { test("API getFileInfo with withNodeModules", async () => { const file = path.resolve( - path.join(__dirname, "../cli/with-node-modules/node_modules/file.js") + path.join(__dirname, "../cli/with-node-modules/node_modules/file.js"), ); await expect(prettier.getFileInfo(file)).resolves.toMatchObject({ ignored: true, @@ -310,7 +310,7 @@ test("API getFileInfo with withNodeModules", async () => { await expect( prettier.getFileInfo(file, { withNodeModules: true, - }) + }), ).resolves.toMatchObject({ ignored: false, inferredParser: "babel", @@ -319,7 +319,7 @@ test("API getFileInfo with withNodeModules", async () => { test("extracts file-info for a JS file with no extension but a standard shebang", async () => { await expect( - prettier.getFileInfo("tests/integration/cli/shebang/node-shebang") + prettier.getFileInfo("tests/integration/cli/shebang/node-shebang"), ).resolves.toMatchObject({ ignored: false, inferredParser: "babel", @@ -328,7 +328,7 @@ test("extracts file-info for a JS file with no extension but a standard shebang" test("extracts file-info for a JS file with no extension but an env-based shebang", async () => { await expect( - prettier.getFileInfo("tests/integration/cli/shebang/env-node-shebang") + prettier.getFileInfo("tests/integration/cli/shebang/env-node-shebang"), ).resolves.toMatchObject({ ignored: false, inferredParser: "babel", @@ -337,7 +337,7 @@ test("extracts file-info for a JS file with no extension but an env-based sheban test("returns null parser for unknown shebang", async () => { await expect( - prettier.getFileInfo("tests/integration/cli/shebang/nonsense-shebang") + prettier.getFileInfo("tests/integration/cli/shebang/nonsense-shebang"), ).resolves.toMatchObject({ ignored: false, inferredParser: null, @@ -349,8 +349,8 @@ test("API getFileInfo with hand-picked plugins", async () => { const pluginPath = path.resolve( path.join( __dirname, - "../plugins/automatic/node_modules/@prettier/plugin-foo/index.js" - ) + "../plugins/automatic/node_modules/@prettier/plugin-foo/index.js", + ), ); await expect(prettier.getFileInfo(file)).resolves.toMatchObject({ ignored: false, @@ -359,7 +359,7 @@ test("API getFileInfo with hand-picked plugins", async () => { await expect( prettier.getFileInfo(file, { plugins: [pluginPath], - }) + }), ).resolves.toMatchObject({ ignored: false, inferredParser: "foo", diff --git a/tests/integration/__tests__/format-ast.js b/tests/integration/__tests__/format-ast.js index 604a581c9..6b905c082 100644 --- a/tests/integration/__tests__/format-ast.js +++ b/tests/integration/__tests__/format-ast.js @@ -13,7 +13,7 @@ describe("formatAST", () => { }, ], }, - { parser: "meriyah" } + { parser: "meriyah" }, ); return formatted; @@ -31,7 +31,7 @@ describe("formatAST", () => { type: "Identifier", name: "specifier2", }, - }) + }), ).toMatchSnapshot(); }); @@ -49,7 +49,7 @@ describe("formatAST", () => { name: "specifier2", range: [0, 0], }, - }) + }), ).toMatchSnapshot(); }); @@ -68,7 +68,7 @@ describe("formatAST", () => { name: "specifier", range: [0, 0], }, - }) + }), ).toMatchSnapshot(); }); @@ -88,7 +88,7 @@ describe("formatAST", () => { raw: "'specifier'", range: [0, 0], }, - }) + }), ).toMatchSnapshot(); }); }); diff --git a/tests/integration/__tests__/format.js b/tests/integration/__tests__/format.js index 80342eb0b..a9792d826 100644 --- a/tests/integration/__tests__/format.js +++ b/tests/integration/__tests__/format.js @@ -7,8 +7,8 @@ test("yaml parser should handle CRLF correctly", async () => { expect( // use JSON.stringify to observe CRLF JSON.stringify( - await prettier.format(input, { parser: "yaml", endOfLine: "auto" }) - ) + await prettier.format(input, { parser: "yaml", endOfLine: "auto" }), + ), ).toMatchSnapshot(); }); @@ -24,7 +24,7 @@ test("typescript parser should throw the first error when both JSX and non-JSX m label: `; await expect( - prettier.format(input, { parser: "typescript", filepath: "foo.unknown" }) + prettier.format(input, { parser: "typescript", filepath: "foo.unknown" }), ).rejects.toThrowErrorMatchingSnapshot(); }); @@ -33,8 +33,8 @@ test("html parser should handle CRLF correctly", async () => { expect( // use JSON.stringify to observe CRLF JSON.stringify( - await prettier.format(input, { parser: "html", endOfLine: "auto" }) - ) + await prettier.format(input, { parser: "html", endOfLine: "auto" }), + ), ).toMatchSnapshot(); }); @@ -43,8 +43,8 @@ test("markdown parser should handle CRLF correctly", async () => { expect( // use JSON.stringify to observe CRLF JSON.stringify( - await prettier.format(input, { parser: "markdown", endOfLine: "auto" }) - ) + await prettier.format(input, { parser: "markdown", endOfLine: "auto" }), + ), ).toMatchSnapshot(); }); @@ -55,14 +55,14 @@ test("should work with foo plugin instance", async () => { await prettier.format(input, { parser: "foo-parser", plugins: [fooPlugin], - }) - ) + }), + ), ).toMatchInlineSnapshot('""{\\"tabWidth\\":8,\\"bracketSpacing\\":false}""'); }); test("'Adjacent JSX' error should not be swallowed by Babel's error recovery", async () => { const input = "\n"; await expect( - prettier.format(input, { parser: "babel" }) + prettier.format(input, { parser: "babel" }), ).rejects.toThrowErrorMatchingSnapshot(); }); diff --git a/tests/integration/__tests__/ignore-in-subdirectories.js b/tests/integration/__tests__/ignore-in-subdirectories.js index 6ac0425d1..626962ee9 100644 --- a/tests/integration/__tests__/ignore-in-subdirectories.js +++ b/tests/integration/__tests__/ignore-in-subdirectories.js @@ -49,7 +49,7 @@ describe("ignore files when executing in a subdirectory and using stdin", () => ], { input: "hello_world( );", - } + }, ).test({ stdout: "hello_world( );", status: 0, @@ -62,7 +62,7 @@ describe("formats files when executing in a subdirectory and using stdin", () => ["--ignore-path", "../.prettierignore", "--stdin-filepath", "example.js"], { input: "hello_world( );", - } + }, ).test({ stdout: "hello_world();", status: 0, diff --git a/tests/integration/__tests__/ignore-path.js b/tests/integration/__tests__/ignore-path.js index 89546a97f..50ef8186f 100644 --- a/tests/integration/__tests__/ignore-path.js +++ b/tests/integration/__tests__/ignore-path.js @@ -7,7 +7,7 @@ const files = [ "ignored-by-prettierignore.js", ].map( (file) => - new URL(`../cli/ignore-path/ignore-path-test/${file}`, import.meta.url) + new URL(`../cli/ignore-path/ignore-path-test/${file}`, import.meta.url), ); const clean = () => Promise.all(files.map((file) => fs.rm(file, { force: true }))); @@ -31,13 +31,13 @@ const getUnformattedFiles = async (args) => { test("custom ignore path", async () => { expect(await getUnformattedFiles(["--ignore-path", ".customignore"])).toEqual( - ["ignored-by-gitignore.js", "ignored-by-prettierignore.js"] + ["ignored-by-gitignore.js", "ignored-by-prettierignore.js"], ); }); test("ignore files by .prettierignore and .gitignore by default", async () => { expect( - await getUnformattedFiles(["--ignore-path", ".non-exists-ignore-file"]) + await getUnformattedFiles(["--ignore-path", ".non-exists-ignore-file"]), ).toEqual([ "ignored-by-customignore.js", "ignored-by-gitignore.js", @@ -56,7 +56,7 @@ describe("ignore file when using --debug-check", () => { status: 0, stderr: "", stdout: ["ignored-by-customignore.js", "ignored-by-gitignore.js"].join( - "\n" + "\n", ), write: [], }); @@ -71,6 +71,6 @@ test("multiple `--ignore-path`", async () => { ".prettierignore", "--ignore-path", ".non-exists-ignore-file", - ]) + ]), ).toEqual(["ignored-by-gitignore.js"]); }); diff --git a/tests/integration/__tests__/infer-parser.js b/tests/integration/__tests__/infer-parser.js index b6eb41ec4..f27cd2fee 100644 --- a/tests/integration/__tests__/infer-parser.js +++ b/tests/integration/__tests__/infer-parser.js @@ -58,7 +58,7 @@ describe("stdin with unknown path and no parser", () => { runCli( "cli/infer-parser/", ["--list-different", "--stdin-filepath", "foo"], - { input: "foo" } + { input: "foo" }, ).test({ status: 0, stdout: "", @@ -168,13 +168,13 @@ describe("--write and --list-different with unknown path and no parser", () => { describe("API with no path and no parser", () => { test("prettier.format", async () => { await expect(prettier.format(" foo ( )")).rejects.toThrow( - /No parser and no file path given, couldn't infer a parser\./ + /No parser and no file path given, couldn't infer a parser\./, ); }); test("prettier.check", async () => { await expect(prettier.check(" foo ( )")).rejects.toThrow( - /No parser and no file path given, couldn't infer a parser\./ + /No parser and no file path given, couldn't infer a parser\./, ); }); }); diff --git a/tests/integration/__tests__/invalid-ignore.js b/tests/integration/__tests__/invalid-ignore.js index c70bf8829..c7caa4a03 100644 --- a/tests/integration/__tests__/invalid-ignore.js +++ b/tests/integration/__tests__/invalid-ignore.js @@ -14,9 +14,9 @@ describe("throw error with invalid ignore", () => { prettier.getFileInfo("something.js", { ignorePath: path.join( __dirname, - "../cli/invalid-ignore/.prettierignore" + "../cli/invalid-ignore/.prettierignore", ), - }) + }), ).rejects.toThrow(/EISDIR: illegal operation on a directory/); }); }); diff --git a/tests/integration/__tests__/list-different.js b/tests/integration/__tests__/list-different.js index 6117dc962..6576770da 100644 --- a/tests/integration/__tests__/list-different.js +++ b/tests/integration/__tests__/list-different.js @@ -25,7 +25,7 @@ describe("--list-different works in CI just as in a non-TTY mode", () => { { stdoutIsTTY: true, ci: true, - } + }, ).test({ status: 1, }); @@ -35,7 +35,7 @@ describe("--list-different works in CI just as in a non-TTY mode", () => { ["--list-different", "formatted.js", "unformatted.js"], { stdoutIsTTY: false, - } + }, ).test({ status: 1, }); diff --git a/tests/integration/__tests__/log-level.js b/tests/integration/__tests__/log-level.js index 90bc54d48..2bc539305 100644 --- a/tests/integration/__tests__/log-level.js +++ b/tests/integration/__tests__/log-level.js @@ -18,7 +18,7 @@ describe("--write with --log-level=silent doesn't log filenames", () => { runCli("cli/write", ["--write", "unformatted.js", "--log-level=silent"]).test( { status: 0, - } + }, ); }); diff --git a/tests/integration/__tests__/mockable.js b/tests/integration/__tests__/mockable.js index 1cc04b1e8..42b9c3a98 100644 --- a/tests/integration/__tests__/mockable.js +++ b/tests/integration/__tests__/mockable.js @@ -46,7 +46,7 @@ describe("cosmiconfig", () => { for (const { title, dirname, file, value } of configs) { test(`async version ${title}`, async () => { const { config, filepath } = await cosmiconfig("prettier").search( - dirname + dirname, ); expect(config).toEqual(value); expect(filepath).toBe(file); diff --git a/tests/integration/__tests__/parser-api.js b/tests/integration/__tests__/parser-api.js index 65b192d3d..5e0d78774 100644 --- a/tests/integration/__tests__/parser-api.js +++ b/tests/integration/__tests__/parser-api.js @@ -34,14 +34,14 @@ test("parsers should allow omit optional arguments", async () => { name, parser, ]) - : [] + : [], ) // Private parser should not be used by users .filter(([name]) => !name.startsWith("__")) .map(async ([name, parser]) => [ name, typeof parser === "function" ? await parser() : parser, - ]) + ]), ); expect(typeof parsers[0][1].parse).toBe("function"); @@ -51,7 +51,7 @@ test("parsers should allow omit optional arguments", async () => { for (const [name, { parse }] of parsers) { await expect( // eslint-disable-next-line require-await - (async () => parse(code[name] ?? "{}"))() + (async () => parse(code[name] ?? "{}"))(), ).resolves.not.toThrow(); } }); diff --git a/tests/integration/__tests__/patterns-dirs.js b/tests/integration/__tests__/patterns-dirs.js index 28f8c533c..dde819c7a 100644 --- a/tests/integration/__tests__/patterns-dirs.js +++ b/tests/integration/__tests__/patterns-dirs.js @@ -58,25 +58,25 @@ describe("Trailing slash", () => { "run in sub dir 1", [".."], { status: 1, stderr: "" }, - "cli/patterns-dirs/dir2" + "cli/patterns-dirs/dir2", ); testPatterns( "run in sub dir 2", ["../"], { status: 1, stderr: "" }, - "cli/patterns-dirs/dir2" + "cli/patterns-dirs/dir2", ); testPatterns( "run in sub dir 3", ["../dir1"], { status: 1, stderr: "" }, - "cli/patterns-dirs/dir2" + "cli/patterns-dirs/dir2", ); testPatterns( "run in sub dir 4", ["../dir1/"], { status: 1, stderr: "" }, - "cli/patterns-dirs/dir2" + "cli/patterns-dirs/dir2", ); }); @@ -97,7 +97,7 @@ testPatterns("Exclude yarn.lock when expanding directories", ["."], { const uppercaseRocksPlugin = path.join( projectRoot, - "tests/config/prettier-plugins/prettier-plugin-uppercase-rocks/index.js" + "tests/config/prettier-plugins/prettier-plugin-uppercase-rocks/index.js", ); describe("plugins `.`", () => { runCliWithoutGitignore("cli/dirs/plugins", [ @@ -162,7 +162,7 @@ function isSymlinkSupported() { const target = path.join( __dirname, - "../cli/patterns-symlinks/test-symlink-feature-detect" + "../cli/patterns-symlinks/test-symlink-feature-detect", ); fs.rmSync(target, { force: true, recursive: true }); fs.mkdirSync(target); @@ -193,11 +193,11 @@ function isSymlinkSupported() { fs.symlinkSync(directoryB, path.join(directoryA, "symlink-to-directory-b")); fs.symlinkSync( path.join(directoryA, "a.js"), - path.join(directoryA, "symlink-to-file-a") + path.join(directoryA, "symlink-to-file-a"), ); fs.symlinkSync( path.join(directoryB, "b.js"), - path.join(directoryA, "symlink-to-file-b") + path.join(directoryA, "symlink-to-file-b"), ); }); afterAll(clean); @@ -255,7 +255,7 @@ function isSymlinkSupported() { stderr: '[error] Explicitly specified pattern "test-a/symlink-to-directory-a" is a symbolic link.', }, - base + base, ); testPatterns( "", @@ -266,7 +266,7 @@ function isSymlinkSupported() { stderr: '[error] Explicitly specified pattern "test-a/symlink-to-directory-b" is a symbolic link.', }, - base + base, ); testPatterns( "", @@ -277,7 +277,7 @@ function isSymlinkSupported() { stderr: '[error] Explicitly specified pattern "test-a/symlink-to-file-a" is a symbolic link.', }, - base + base, ); testPatterns( "", @@ -288,7 +288,7 @@ function isSymlinkSupported() { stderr: '[error] Explicitly specified pattern "test-a/symlink-to-file-b" is a symbolic link.', }, - base + base, ); testPatterns( "", @@ -299,7 +299,7 @@ function isSymlinkSupported() { stderr: '[error] No files matching the pattern were found: "test-a/symlink-*".', }, - base + base, ); testPatterns( "", @@ -310,13 +310,13 @@ function isSymlinkSupported() { stderr: '[error] Explicitly specified pattern "test-a/symlink-to-file-b" is a symbolic link.', }, - base + base, ); testPatterns( "", ["test-a/symlink-to-directory-b/*"], { stdout: "test-a/symlink-to-directory-b/b.js" }, - base + base, ); }); @@ -324,7 +324,7 @@ function testPatterns( namePrefix, cliArgs, expected = {}, - cwd = "cli/patterns-dirs" + cwd = "cli/patterns-dirs", ) { const testName = (namePrefix ? namePrefix + ": " : "") + diff --git a/tests/integration/__tests__/performance-flags.js b/tests/integration/__tests__/performance-flags.js index 3ddf0e337..c5de6772c 100644 --- a/tests/integration/__tests__/performance-flags.js +++ b/tests/integration/__tests__/performance-flags.js @@ -2,8 +2,8 @@ describe("should not write file or print code when `--debug-benchmark` or `--deb const assertStderr = (message) => { expect( message.includes( - "'--debug-repeat' found, running formatWithCursor 2 times" - ) + "'--debug-repeat' found, running formatWithCursor 2 times", + ), ).toBe(true); }; @@ -11,7 +11,7 @@ describe("should not write file or print code when `--debug-benchmark` or `--deb runCli( "cli/performance-flags", ["--debug-repeat", "2", "--parser", "babel"], - { input: "foo( bar )" } + { input: "foo( bar )" }, ).test({ stderr: assertStderr, status: 0, @@ -24,7 +24,7 @@ describe("should not write file or print code when `--debug-benchmark` or `--deb runCli( "cli/performance-flags", ["--debug-repeat", "2", "--parser", "babel", "--log-level", logLevel], - { input: "foo( bar )" } + { input: "foo( bar )" }, ).test({ stderr: assertStderr, status: 0, diff --git a/tests/integration/__tests__/piped-output.js b/tests/integration/__tests__/piped-output.js index 767406801..5edeba26b 100644 --- a/tests/integration/__tests__/piped-output.js +++ b/tests/integration/__tests__/piped-output.js @@ -2,7 +2,7 @@ describe("output with --check + unformatted differs when piped", () => { const cli0 = runCli( "cli/write", ["--write", "--check", "--no-color", "unformatted.js"], - { stdoutIsTTY: true } + { stdoutIsTTY: true }, ).test({ status: 0, }); @@ -10,7 +10,7 @@ describe("output with --check + unformatted differs when piped", () => { const cli1 = runCli( "cli/write", ["--write", "--check", "--no-color", "unformatted.js"], - { stdoutIsTTY: false } + { stdoutIsTTY: false }, ).test({ status: 0, }); @@ -28,7 +28,7 @@ describe("no file diffs with --check + formatted file", () => { const cli0 = runCli( "cli/write", ["--write", "--check", "--no-color", "formatted.js"], - { stdoutIsTTY: true } + { stdoutIsTTY: true }, ).test({ status: 0, }); @@ -36,7 +36,7 @@ describe("no file diffs with --check + formatted file", () => { const cli1 = runCli( "cli/write", ["--write", "--check", "--no-color", "formatted.js"], - { stdoutIsTTY: false } + { stdoutIsTTY: false }, ).test({ status: 0, }); @@ -55,7 +55,7 @@ describe("output with --list-different + unformatted differs when piped", () => const cli0 = runCli( "cli/write", ["--write", "--list-different", "--no-color", "unformatted.js"], - { stdoutIsTTY: true } + { stdoutIsTTY: true }, ).test({ status: 0, }); @@ -63,7 +63,7 @@ describe("output with --list-different + unformatted differs when piped", () => const cli1 = runCli( "cli/write", ["--write", "--list-different", "--no-color", "unformatted.js"], - { stdoutIsTTY: false } + { stdoutIsTTY: false }, ).test({ status: 0, }); @@ -81,7 +81,7 @@ describe("no file diffs with --list-different + formatted file", () => { const cli0 = runCli( "cli/write", ["--write", "--list-different", "--no-color", "formatted.js"], - { stdoutIsTTY: true } + { stdoutIsTTY: true }, ).test({ status: 0, }); @@ -89,7 +89,7 @@ describe("no file diffs with --list-different + formatted file", () => { const cli1 = runCli( "cli/write", ["--write", "--list-different", "--no-color", "formatted.js"], - { stdoutIsTTY: false } + { stdoutIsTTY: false }, ).test({ status: 0, }); diff --git a/tests/integration/__tests__/plugin-api-embed.js b/tests/integration/__tests__/plugin-api-embed.js index 2d8b0836e..ad8510bb6 100644 --- a/tests/integration/__tests__/plugin-api-embed.js +++ b/tests/integration/__tests__/plugin-api-embed.js @@ -77,7 +77,7 @@ describe("embed API in plugins", () => { await format(input, { plugins: [makePlugin()], parser: "baz-parser", - }) + }), ).toMatchSnapshot(); }); @@ -86,7 +86,7 @@ describe("embed API in plugins", () => { format(input, { plugins: [makePlugin(true)], parser: "baz-parser-outdated", - }) + }), ).rejects.toThrowErrorMatchingSnapshot(); }); }); diff --git a/tests/integration/__tests__/plugin-default-options.js b/tests/integration/__tests__/plugin-default-options.js index 5c80a76ab..eca10383c 100644 --- a/tests/integration/__tests__/plugin-default-options.js +++ b/tests/integration/__tests__/plugin-default-options.js @@ -7,7 +7,7 @@ describe("plugin default options should work", () => { "--plugin=./plugin.cjs", "--no-editorconfig", ], - { input: "hello-world" } + { input: "hello-world" }, ).test({ stdout: JSON.stringify({ tabWidth: 8, @@ -28,7 +28,7 @@ describe("overriding plugin default options should work", () => { "--plugin=./plugin.cjs", "--tab-width=4", ], - { input: "hello-world" } + { input: "hello-world" }, ).test({ stdout: JSON.stringify({ tabWidth: 4, diff --git a/tests/integration/__tests__/plugin-options-string.js b/tests/integration/__tests__/plugin-options-string.js index d09d77fee..ec3b64557 100644 --- a/tests/integration/__tests__/plugin-options-string.js +++ b/tests/integration/__tests__/plugin-options-string.js @@ -29,7 +29,7 @@ describe("external options from CLI should work", () => { "--foo-string", "baz", ], - { input: "hello-world" } + { input: "hello-world" }, ).test({ stdout: "foo:baz", stderr: "", @@ -42,7 +42,7 @@ describe("external options from config file should work", () => { runCli( "plugins/options-string", ["--config=./config.json", "--stdin-filepath", "example.foo"], - { input: "hello-world" } + { input: "hello-world" }, ).test({ stdout: "foo:baz", stderr: "", @@ -55,7 +55,7 @@ describe("Non exists plugin", () => { runCli( "plugins/options-string", ["--plugin=--invalid--", "--stdin-filepath", "example.foo"], - { input: "hello-world" } + { input: "hello-world" }, ).test({ stdout: "", stderr: expect.stringMatching(/Cannot find package '--invalid--'/), diff --git a/tests/integration/__tests__/plugin-options.js b/tests/integration/__tests__/plugin-options.js index 2e90bf79c..9f7b1b0fb 100644 --- a/tests/integration/__tests__/plugin-options.js +++ b/tests/integration/__tests__/plugin-options.js @@ -23,7 +23,7 @@ describe("include plugin's parsers to the values of the `parser` option`", () => runCli("plugins/options", ["--plugin=./plugin.cjs", "--help", "parser"]).test( { status: 0, - } + }, ); }); @@ -37,7 +37,7 @@ describe("external options from CLI should work", () => { "--foo-option", "baz", ], - { input: "hello-world" } + { input: "hello-world" }, ).test({ stdout: "foo:baz", stderr: "", @@ -50,7 +50,7 @@ describe("external options from config file should work", () => { runCli( "plugins/options", ["--config=./config.json", "--stdin-filepath", "example.foo"], - { input: "hello-world" } + { input: "hello-world" }, ).test({ stdout: "foo:baz", stderr: "", diff --git a/tests/integration/__tests__/print-doc-to-string.js b/tests/integration/__tests__/print-doc-to-string.js index 59fd5366f..076dd9046 100644 --- a/tests/integration/__tests__/print-doc-to-string.js +++ b/tests/integration/__tests__/print-doc-to-string.js @@ -29,10 +29,10 @@ test("Throw error on invalid doc", () => { { "without-type": true }, ]) { expect(() => - printDocToString(doc, printDocToStringOptions) + printDocToString(doc, printDocToStringOptions), ).toThrowErrorMatchingSnapshot(); expect(() => - printDocToString([doc], printDocToStringOptions) + printDocToString([doc], printDocToStringOptions), ).toThrowErrorMatchingSnapshot(); } }); diff --git a/tests/integration/__tests__/printer-and-parser.js b/tests/integration/__tests__/printer-and-parser.js index ab14c4330..811ab0ecf 100644 --- a/tests/integration/__tests__/printer-and-parser.js +++ b/tests/integration/__tests__/printer-and-parser.js @@ -21,7 +21,7 @@ test("Should use printer and parser from the same plugin", async () => { const pluginB = createPlugin("plugin B"); const result = JSON.parse( - await prettier.format("_", { plugins: [pluginA, pluginB], parser: "foo" }) + await prettier.format("_", { plugins: [pluginA, pluginB], parser: "foo" }), ); expect(result).toEqual({ parsedBy: "plugin B", printedBy: "plugin B" }); }); @@ -39,7 +39,7 @@ test("Should not apply default options from unused plugin", async () => { }; const result = JSON.parse( - await prettier.format("_", { plugins: [pluginA, pluginB], parser: "foo" }) + await prettier.format("_", { plugins: [pluginA, pluginB], parser: "foo" }), ); expect(result).toEqual({ tabWidth: 2 }); }); diff --git a/tests/integration/__tests__/stdin-filepath.js b/tests/integration/__tests__/stdin-filepath.js index bee1d0ac7..5da676648 100644 --- a/tests/integration/__tests__/stdin-filepath.js +++ b/tests/integration/__tests__/stdin-filepath.js @@ -4,7 +4,7 @@ describe("format correctly if stdin content compatible with stdin-filepath", () runCli( "cli", ["--stdin-filepath", "abc.css"], - { input: ".name { display: none; }" } // css + { input: ".name { display: none; }" }, // css ).test({ status: 0, }); @@ -14,7 +14,7 @@ describe("throw error if stdin content incompatible with stdin-filepath", () => runCli( "cli", ["--stdin-filepath", "abc.js"], - { input: ".name { display: none; }" } // css + { input: ".name { display: none; }" }, // css ).test({ status: "non-zero", }); @@ -24,7 +24,7 @@ describe("gracefully handle stdin-filepath with nonexistent directory", () => { runCli( "cli", ["--stdin-filepath", "definitely/nonexistent/path.css"], - { input: ".name { display: none; }" } // css + { input: ".name { display: none; }" }, // css ).test({ status: 0, }); @@ -52,7 +52,7 @@ describe("apply editorconfig for stdin-filepath with nonexistent directory", () console.log("should be indented with a tab"); } `, // js - } + }, ).test({ status: 0, }); @@ -68,7 +68,7 @@ describe("apply editorconfig for stdin-filepath with a deep path", () => { console.log("should be indented with a tab"); } `, // js - } + }, ).test({ status: 0, }); @@ -102,7 +102,7 @@ describe("apply editorconfig for stdin-filepath with a deep path", () => { console.log("should be indented with a tab"); } `, // js - } + }, ).test({ status: 0, }); @@ -121,7 +121,7 @@ describe("don’t apply editorconfig outside project for stdin-filepath with non console.log("should be indented with 2 spaces"); } `, // js - } + }, ).test({ status: 0, }); diff --git a/tests/integration/__tests__/support-info.js b/tests/integration/__tests__/support-info.js index ca48375af..849c9192b 100644 --- a/tests/integration/__tests__/support-info.js +++ b/tests/integration/__tests__/support-info.js @@ -11,7 +11,7 @@ describe("CLI --support-info", () => { async function getCoreInfo() { const supportInfo = await prettier.getSupportInfo(); const languages = Object.fromEntries( - supportInfo.languages.map(({ name, parsers }) => [name, parsers]) + supportInfo.languages.map(({ name, parsers }) => [name, parsers]), ); const options = Object.fromEntries( @@ -26,7 +26,7 @@ async function getCoreInfo() { ? { choices: option.choices.map((choice) => choice.value) } : null), }, - ]) + ]), ); return { languages, options }; diff --git a/tests/integration/__tests__/util-shared.js b/tests/integration/__tests__/util-shared.js index 31239ee87..16d1eb272 100644 --- a/tests/integration/__tests__/util-shared.js +++ b/tests/integration/__tests__/util-shared.js @@ -23,7 +23,7 @@ test("shared util has correct structure", () => { expect(typeof sharedUtil.isPreviousLineEmpty).toBe("function"); expect(typeof sharedUtil.getNextNonSpaceNonCommentCharacter).toBe("function"); expect(typeof sharedUtil.getNextNonSpaceNonCommentCharacterIndex).toBe( - "function" + "function", ); expect(typeof sharedUtil.makeString).toBe("function"); }); @@ -95,7 +95,7 @@ test("sharedUtil.getAlignmentSize", () => { expect(getAlignmentSize("\t\t", /* tabWidth */ 2)).toBe(4); expect(getAlignmentSize("\t\t", /* tabWidth */ 3)).toBe(6); expect(getAlignmentSize("\t\t", /* tabWidth */ 3, /* startIndex */ 1)).toBe( - 3 + 3, ); }); @@ -124,13 +124,13 @@ test("sharedUtil.getNextNonSpaceNonCommentCharacter and sharedUtil.getNextNonSpa const locEnd = () => endOfIdentifierA; expect(getNextNonSpaceNonCommentCharacter(text, endOfIdentifierA)).toBe( - "b" + "b", ); expect( - getNextNonSpaceNonCommentCharacterIndex(text, endOfIdentifierA) + getNextNonSpaceNonCommentCharacterIndex(text, endOfIdentifierA), ).toBe(indexOfIdentifierB); expect( - getNextNonSpaceNonCommentCharacterIndex(text, FAKE_NODE, locEnd) + getNextNonSpaceNonCommentCharacterIndex(text, FAKE_NODE, locEnd), ).toBe(indexOfIdentifierB); } @@ -141,10 +141,10 @@ test("sharedUtil.getNextNonSpaceNonCommentCharacter and sharedUtil.getNextNonSpa expect(getNextNonSpaceNonCommentCharacter(text, endOfIdentifierA)).toBe(""); expect( - getNextNonSpaceNonCommentCharacterIndex(text, endOfIdentifierA) + getNextNonSpaceNonCommentCharacterIndex(text, endOfIdentifierA), ).toBe(text.length); expect( - getNextNonSpaceNonCommentCharacterIndex(text, FAKE_NODE, locEnd) + getNextNonSpaceNonCommentCharacterIndex(text, FAKE_NODE, locEnd), ).toBe(text.length); } @@ -155,10 +155,10 @@ test("sharedUtil.getNextNonSpaceNonCommentCharacter and sharedUtil.getNextNonSpa expect(getNextNonSpaceNonCommentCharacter(text, startIndex)).toBe(""); expect(getNextNonSpaceNonCommentCharacterIndex(text, startIndex)).toBe( - false + false, ); expect( - getNextNonSpaceNonCommentCharacterIndex(text, FAKE_NODE, locEnd) + getNextNonSpaceNonCommentCharacterIndex(text, FAKE_NODE, locEnd), ).toBe(false); } }); @@ -176,12 +176,12 @@ test("sharedUtil.isPreviousLineEmpty, sharedUtil.isNextLineEmpty and sharedUtil. expect(isPreviousLineEmpty(text, startOfIdentifierB)).toBe(true); expect( - isPreviousLineEmpty(text, FAKE_NODE_B, () => startOfIdentifierB) + isPreviousLineEmpty(text, FAKE_NODE_B, () => startOfIdentifierB), ).toBe(true); expect(isNextLineEmpty(text, endOfIdentifierA)).toBe(true); expect(isNextLineEmptyAfterIndex(text, endOfIdentifierA)).toBe(true); expect(isNextLineEmpty(text, FAKE_NODE_A, () => endOfIdentifierA)).toBe( - true + true, ); } @@ -192,12 +192,12 @@ test("sharedUtil.isPreviousLineEmpty, sharedUtil.isNextLineEmpty and sharedUtil. expect(isPreviousLineEmpty(text, startOfIdentifierB)).toBe(false); expect( - isPreviousLineEmpty(text, FAKE_NODE_B, () => startOfIdentifierB) + isPreviousLineEmpty(text, FAKE_NODE_B, () => startOfIdentifierB), ).toBe(false); expect(isNextLineEmpty(text, endOfIdentifierA)).toBe(false); expect(isNextLineEmptyAfterIndex(text, endOfIdentifierA)).toBe(false); expect(isNextLineEmpty(text, FAKE_NODE_A, () => endOfIdentifierA)).toBe( - false + false, ); } @@ -216,12 +216,12 @@ test("sharedUtil.makeString", () => { expect(makeString("a", DOUBLE_QUOTE)).toBe(`${DOUBLE_QUOTE}a${DOUBLE_QUOTE}`); expect(makeString("a", SINGLE_QUOTE)).toBe(`${SINGLE_QUOTE}a${SINGLE_QUOTE}`); expect(makeString(`a${DOUBLE_QUOTE}`, DOUBLE_QUOTE)).toBe( - `${DOUBLE_QUOTE}a\\${DOUBLE_QUOTE}${DOUBLE_QUOTE}` + `${DOUBLE_QUOTE}a\\${DOUBLE_QUOTE}${DOUBLE_QUOTE}`, ); expect(makeString(`a${DOUBLE_QUOTE}`, SINGLE_QUOTE)).toBe( - `${SINGLE_QUOTE}a${DOUBLE_QUOTE}${SINGLE_QUOTE}` + `${SINGLE_QUOTE}a${DOUBLE_QUOTE}${SINGLE_QUOTE}`, ); expect( - makeString("\\a", SINGLE_QUOTE, /* unescapeUnnecessaryEscapes */ true) + makeString("\\a", SINGLE_QUOTE, /* unescapeUnnecessaryEscapes */ true), ).toBe(`${SINGLE_QUOTE}a${SINGLE_QUOTE}`); }); diff --git a/tests/integration/__tests__/with-config-precedence.js b/tests/integration/__tests__/with-config-precedence.js index eac92e8d8..03af01648 100644 --- a/tests/integration/__tests__/with-config-precedence.js +++ b/tests/integration/__tests__/with-config-precedence.js @@ -138,7 +138,7 @@ describe("CLI --stdin-filepath works with --config-precedence prefer-file", () = runCli( "cli/config-precedence/overrides", ["--stdin-filepath=abc.ts", "--no-semi", "--config-precedence=prefer-file"], - { input: "let x: keyof Y = foo()" } // typescript + { input: "let x: keyof Y = foo()" }, // typescript ).test({ stderr: "", status: 0, @@ -153,7 +153,7 @@ describe("CLI --stdin-filepath works with --config-precedence file-override", () "--no-semi", "--config-precedence=file-override", ], - { input: "let x: keyof Y = foo()" } // typescript + { input: "let x: keyof Y = foo()" }, // typescript ).test({ stderr: "", status: 0, @@ -168,7 +168,7 @@ describe("CLI --stdin-filepath works with --config-precedence cli-override", () "--no-semi", "--config-precedence=cli-override", ], - { input: "let x: keyof Y = foo()" } // typescript + { input: "let x: keyof Y = foo()" }, // typescript ).test({ stderr: "", status: 0, diff --git a/tests/integration/__tests__/with-parser-inference.js b/tests/integration/__tests__/with-parser-inference.js index 5a5103010..c85c83401 100644 --- a/tests/integration/__tests__/with-parser-inference.js +++ b/tests/integration/__tests__/with-parser-inference.js @@ -22,13 +22,13 @@ describe("infers postcss parser with --list-different", () => { describe("infers parser from filename", () => { test("json from .prettierrc", async () => { expect( - await prettier.format(" { } ", { filepath: "x/y/.prettierrc" }) + await prettier.format(" { } ", { filepath: "x/y/.prettierrc" }), ).toBe("{}\n"); }); test("json from .stylelintrc", async () => { expect( - await prettier.format(" { } ", { filepath: "x/y/.stylelintrc" }) + await prettier.format(" { } ", { filepath: "x/y/.stylelintrc" }), ).toBe("{}\n"); }); @@ -36,7 +36,7 @@ describe("infers parser from filename", () => { expect( await prettier.format(" extends: '' ", { filepath: "x/y/.stylelintrc", - }) + }), ).toBe('extends: ""\n'); }); @@ -44,7 +44,7 @@ describe("infers parser from filename", () => { expect( await prettier.format("let foo = ( x = 1 ) => x", { filepath: "x/y/Jakefile", - }) + }), ).toBe("let foo = (x = 1) => x;\n"); }); @@ -58,8 +58,8 @@ describe("infers parser from filename", () => { "keepClassNames": false }} `, - { filepath: "/path/to/.swcrc" } - ) + { filepath: "/path/to/.swcrc" }, + ), ).toBe( outdent` { @@ -68,7 +68,7 @@ describe("infers parser from filename", () => { "keepClassNames": false } } - ` + "\n" + ` + "\n", ); }); @@ -76,7 +76,7 @@ describe("infers parser from filename", () => { expect( await prettier.format(" { '*': 'your-cmd' } ", { filepath: "/path/to/.lintstagedrc", - }) + }), ).toBe('{ "*": "your-cmd" }\n'); }); @@ -87,13 +87,13 @@ describe("infers parser from filename", () => { '*': - your-cmd `, - { filepath: "/path/to/.lintstagedrc" } - ) + { filepath: "/path/to/.lintstagedrc" }, + ), ).toBe( outdent` "*": - your-cmd - ` + "\n" + ` + "\n", ); }); }); diff --git a/tests/integration/cli-worker.js b/tests/integration/cli-worker.js index a01409215..7c8743af6 100644 --- a/tests/integration/cli-worker.js +++ b/tests/integration/cli-worker.js @@ -38,7 +38,7 @@ async function run() { originalStat( path.basename(filename) === "virtualDirectory" ? import.meta.url - : filename + : filename, ); readline.clearLine = (stream) => { @@ -49,7 +49,7 @@ async function run() { : stream === process.stderr ? "process.stderr" : "unknown stream" - })]]\n` + })]]\n`, ); }; @@ -80,7 +80,7 @@ async function run() { hasOwn(options.mockWriteFileErrors, filename) ) { throw new Error( - options.mockWriteFileErrors[filename] + " (mocked error)" + options.mockWriteFileErrors[filename] + " (mocked error)", ); } diff --git a/tests/integration/env.js b/tests/integration/env.js index 5f0d7e65b..5effb781d 100644 --- a/tests/integration/env.js +++ b/tests/integration/env.js @@ -8,7 +8,7 @@ const { PRETTIER_DIR } = process.env; const { bin } = require(path.join(PRETTIER_DIR, "package.json")); const prettierCli = path.join( PRETTIER_DIR, - typeof bin === "object" ? bin.prettier : bin + typeof bin === "object" ? bin.prettier : bin, ); const mockable = isProduction diff --git a/tests/integration/run-cli.js b/tests/integration/run-cli.js index aa44d5731..c9908e832 100644 --- a/tests/integration/run-cli.js +++ b/tests/integration/run-cli.js @@ -4,7 +4,7 @@ import { Worker } from "node:worker_threads"; const CLI_WORKER_FILE = new URL("./cli-worker.js", import.meta.url); const INTEGRATION_TEST_DIRECTORY = url.fileURLToPath( - new URL("./", import.meta.url) + new URL("./", import.meta.url), ); const streamToString = (stream) => @@ -137,7 +137,7 @@ function runCli(dir, args = [], options = {}) { if (name === "stdout" || name === "stderr") { value = result[name].replace( /\r/g, - options.ignoreLineEndings ? "" : "/*CR*/" + options.ignoreLineEndings ? "" : "/*CR*/", ); } diff --git a/tests/unit/get-descendants.js b/tests/unit/get-descendants.js index 036a710a9..521d5999c 100644 --- a/tests/unit/get-descendants.js +++ b/tests/unit/get-descendants.js @@ -31,7 +31,7 @@ test("options.filter", () => { getVisitorKeys, filter: (node) => node.id.includes("2"), }), - ].map((node) => node.id) + ].map((node) => node.id), ).toMatchInlineSnapshot(` [ "tree.list.2", diff --git a/tests/unit/print-doc-to-string.js b/tests/unit/print-doc-to-string.js index 4f1dedc2d..0adf04160 100644 --- a/tests/unit/print-doc-to-string.js +++ b/tests/unit/print-doc-to-string.js @@ -11,7 +11,8 @@ test("Should reject if too many cursor in doc", () => { test("Should trim blank first line", () => { expect( - printDocToString([" ", hardline, "Prettier", hardline], options).formatted + printDocToString([" ", hardline, "Prettier", hardline], options) + .formatted, ).toBe("\nPrettier\n"); }); @@ -19,8 +20,8 @@ test("Should properly trim with cursor", () => { expect( printDocToString( [cursor, "Prettier \t", cursor, "\t \t", hardline], - options - ) + options, + ), ).toEqual({ formatted: "Prettier\n", cursorNodeStart: 0, diff --git a/tests/unit/resolve-parser.js b/tests/unit/resolve-parser.js index 7663941f1..ed37db166 100644 --- a/tests/unit/resolve-parser.js +++ b/tests/unit/resolve-parser.js @@ -17,12 +17,12 @@ test("resolveParser should not trigger the plugin.parsers getters", async () => }, }, ]; - }) + }), ); const creatParsers = (names) => Object.defineProperties( Object.create(null), - createParserDescriptors(names) + createParserDescriptors(names), ); const options = { diff --git a/tests/unit/syntax-transform.js b/tests/unit/syntax-transform.js index 1cf2889b1..9ff63ef76 100644 --- a/tests/unit/syntax-transform.js +++ b/tests/unit/syntax-transform.js @@ -4,20 +4,20 @@ import path from "node:path"; import transformCode from "../../scripts/build/transform/index.js"; const file = url.fileURLToPath( - new URL("../../src/__dummy.js", import.meta.url) + new URL("../../src/__dummy.js", import.meta.url), ); const shimsDirectory = url.fileURLToPath( - new URL("../../scripts/build/shims", import.meta.url) + new URL("../../scripts/build/shims", import.meta.url), ); const transform = (code) => transformCode(code, file).replaceAll( JSON.stringify(shimsDirectory + path.sep).slice(1, -1), - "/" + "/", ); test("Object.hasOwn", () => { expect(transform("Object.hasOwn(foo, bar)")).toMatchInlineSnapshot( - `"Object.prototype.hasOwnProperty.call(foo, bar);"` + `"Object.prototype.hasOwnProperty.call(foo, bar);"`, ); }); diff --git a/website/blog/2017-05-03-1.3.0.md b/website/blog/2017-05-03-1.3.0.md index 6026f8e48..60f5f7c51 100644 --- a/website/blog/2017-05-03-1.3.0.md +++ b/website/blog/2017-05-03-1.3.0.md @@ -234,7 +234,7 @@ Template literals are very hard to deal with for a pretty printer because the sp insertRule( `*, *:before, *:after { box-sizing: inherit; - }` + }`, ); // After diff --git a/website/blog/2018-11-07-1.15.0.md b/website/blog/2018-11-07-1.15.0.md index 26ed13a73..25f11d254 100644 --- a/website/blog/2018-11-07-1.15.0.md +++ b/website/blog/2018-11-07-1.15.0.md @@ -166,7 +166,7 @@ The following Angular-specific syntax structures are supported: - `[(something)]` - `*something` - inline template - - `` @Component({ template: `
Hello World
` }) `` + - ``@Component({ template: `
Hello World
` })`` ### MDX diff --git a/website/pages/en/index.js b/website/pages/en/index.js index 28ca87905..942915182 100755 --- a/website/pages/en/index.js +++ b/website/pages/en/index.js @@ -169,7 +169,7 @@ const LanguagesSection = () => { } return acc; }, - [] + [], ); return ( @@ -336,7 +336,8 @@ const UsersSection = ({ language }) => {

- More than 14.8k{" "} + More than{" "} + 14.8k{" "} dependent packages on npm