diff --git a/.eslintrc.cjs b/.eslintrc.cjs index a0f89301d..abd521300 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -176,10 +176,7 @@ module.exports = { { files: [ "**/*.cjs", - "src/common/**/*.js", - "src/config/**/*.js", "src/document/**/*.js", - "src/main/**/*.js", "src/utils/**/*.js", "scripts/tools/eslint-plugin-prettier-internal-rules/**/*.js", "website/**/*.js", diff --git a/scripts/build/bundler.mjs b/scripts/build/bundler.mjs index 6ddc3aae5..93b4a09ed 100644 --- a/scripts/build/bundler.mjs +++ b/scripts/build/bundler.mjs @@ -77,6 +77,11 @@ function* getEsbuildOptions(bundle, buildOptions) { }; } } + + // Use `__dirname` directly + replaceStrings[ + "const __dirname = path.dirname(fileURLToPath(import.meta.url));" + ] = ""; } else { // Universal bundle only use version info from package.json // Replace package.json with `{version: "{VERSION}"}` diff --git a/scripts/build/config.mjs b/scripts/build/config.mjs index 045a64ecf..2bb07e4c1 100644 --- a/scripts/build/config.mjs +++ b/scripts/build/config.mjs @@ -214,7 +214,8 @@ const coreBundles = [ external: ["benchmark"], }, { - input: "src/common/third-party.js", + input: "src/common/third-party.cjs", + output: "third-party.js", replace: { // cosmiconfig@6 -> import-fresh can't find parentModule, since module is bundled "parentModule(__filename)": "__filename", diff --git a/src/cli/format.js b/src/cli/format.js index 7ff3c603e..657005524 100644 --- a/src/cli/format.js +++ b/src/cli/format.js @@ -2,7 +2,7 @@ import { promises as fs } from "fs"; import path from "path"; import chalk from "chalk"; import prettier from "../index.js"; -import thirdParty from "../common/third-party.js"; +import thirdParty from "../common/third-party.cjs"; import prettierInternal from "./prettier-internal.js"; import { expandPatterns, fixWindowsSlashes } from "./expand-patterns.js"; import getOptionsForFile from "./options/get-options-for-file.js"; diff --git a/src/cli/is-tty.js b/src/cli/is-tty.js index 0379c61ba..64c37e82e 100644 --- a/src/cli/is-tty.js +++ b/src/cli/is-tty.js @@ -1,4 +1,4 @@ -import thirdParty from "../common/third-party.js"; +import thirdParty from "../common/third-party.cjs"; // Some CI pipelines incorrectly report process.stdout.isTTY status, // which causes unwanted lines in the output. An additional check for isCI() helps. diff --git a/src/common/ast-path.js b/src/common/ast-path.js index ade4952a1..eef2b6402 100644 --- a/src/common/ast-path.js +++ b/src/common/ast-path.js @@ -1,5 +1,4 @@ -"use strict"; -const getLast = require("../utils/get-last.js"); +import getLast from "../utils/get-last.js"; function getNodeHelper(path, count) { const stackIndex = getNodeStackIndexHelper(path.stack, count); @@ -194,4 +193,4 @@ class AstPath { } } -module.exports = AstPath; +export default AstPath; diff --git a/src/common/common-options.js b/src/common/common-options.js index 7fa62085a..6c35eae01 100644 --- a/src/common/common-options.js +++ b/src/common/common-options.js @@ -1,9 +1,7 @@ -"use strict"; - const CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/main/src/main/core-options.js -module.exports = { +const options = { bracketSpacing: { since: "0.0.0", category: CATEGORY_COMMON, @@ -62,3 +60,5 @@ module.exports = { description: "Enforce single attribute per line in HTML, Vue and JSX.", }, }; + +export default options; diff --git a/src/common/create-ignorer.js b/src/common/create-ignorer.js index 4ccfc4121..b7c7ade6b 100644 --- a/src/common/create-ignorer.js +++ b/src/common/create-ignorer.js @@ -1,8 +1,6 @@ -"use strict"; - -const path = require("path"); -const ignore = require("ignore"); -const getFileContentOrNull = require("../utils/get-file-content-or-null.js"); +import path from "path"; +import ignore from "ignore"; +import getFileContentOrNull from "../utils/get-file-content-or-null.js"; /** * @param {string?} ignorePath @@ -39,4 +37,4 @@ function _createIgnorer(ignoreContent, withNodeModules) { return ignorer; } -module.exports = createIgnorer; +export default createIgnorer; diff --git a/src/common/end-of-line.cjs b/src/common/end-of-line.cjs new file mode 100644 index 000000000..0c6365a28 --- /dev/null +++ b/src/common/end-of-line.cjs @@ -0,0 +1,54 @@ +// cjs version for ../doc to use +"use strict"; + +function guessEndOfLine(text) { + const index = text.indexOf("\r"); + if (index >= 0) { + return text.charAt(index + 1) === "\n" ? "crlf" : "cr"; + } + return "lf"; +} + +function convertEndOfLineToChars(value) { + switch (value) { + case "cr": + return "\r"; + case "crlf": + return "\r\n"; + default: + return "\n"; + } +} + +function countEndOfLineChars(text, eol) { + let regex; + + switch (eol) { + case "\n": + regex = /\n/g; + break; + case "\r": + regex = /\r/g; + break; + case "\r\n": + regex = /\r\n/g; + break; + default: + /* istanbul ignore next */ + throw new Error(`Unexpected "eol" ${JSON.stringify(eol)}.`); + } + + const endOfLines = text.match(regex); + return endOfLines ? endOfLines.length : 0; +} + +function normalizeEndOfLine(text) { + return text.replace(/\r\n?/g, "\n"); +} + +module.exports = { + guessEndOfLine, + convertEndOfLineToChars, + countEndOfLineChars, + normalizeEndOfLine, +}; diff --git a/src/common/end-of-line.js b/src/common/end-of-line.js index 994443c59..84b7c9ecd 100644 --- a/src/common/end-of-line.js +++ b/src/common/end-of-line.js @@ -1,5 +1,3 @@ -"use strict"; - function guessEndOfLine(text) { const index = text.indexOf("\r"); if (index >= 0) { @@ -45,7 +43,7 @@ function normalizeEndOfLine(text) { return text.replace(/\r\n?/g, "\n"); } -module.exports = { +export { guessEndOfLine, convertEndOfLineToChars, countEndOfLineChars, diff --git a/src/common/errors.js b/src/common/errors.js index 60979117b..bc060690f 100644 --- a/src/common/errors.js +++ b/src/common/errors.js @@ -1,13 +1,6 @@ -"use strict"; - class ConfigError extends Error {} class DebugError extends Error {} class UndefinedParserError extends Error {} class ArgExpansionBailout extends Error {} -module.exports = { - ConfigError, - DebugError, - UndefinedParserError, - ArgExpansionBailout, -}; +export { ConfigError, DebugError, UndefinedParserError, ArgExpansionBailout }; diff --git a/src/common/get-file-info.js b/src/common/get-file-info.js index d01d1ee95..4799680b1 100644 --- a/src/common/get-file-info.js +++ b/src/common/get-file-info.js @@ -1,9 +1,7 @@ -"use strict"; - -const path = require("path"); -const options = require("../main/options.js"); -const config = require("../config/resolve-config.js"); -const createIgnorer = require("./create-ignorer.js"); +import path from "path"; +import { inferParser } from "../main/options.js"; +import * as config from "../config/resolve-config.js"; +import createIgnorer from "./create-ignorer.js"; /** * @typedef {{ ignorePath?: string, withNodeModules?: boolean, plugins: object }} FileInfoOptions @@ -65,7 +63,7 @@ function getFileParser(resolvedConfig, filePath, plugins) { return resolvedConfig.parser; } - const inferredParser = options.inferParser(filePath, plugins); + const inferredParser = inferParser(filePath, plugins); if (inferredParser) { return inferredParser; @@ -120,4 +118,4 @@ function normalizeFilePath(filePath, ignorePath) { : filePath; } -module.exports = getFileInfo; +export default getFileInfo; diff --git a/src/common/load-plugins.js b/src/common/load-plugins.js index a70846b85..c34a6e39a 100644 --- a/src/common/load-plugins.js +++ b/src/common/load-plugins.js @@ -1,13 +1,16 @@ -"use strict"; +import { createRequire } from "module"; +import fs from "fs"; +import path from "path"; +import { fileURLToPath } from "url"; +import uniqBy from "lodash/uniqBy.js"; +import partition from "lodash/partition.js"; +import fastGlob from "fast-glob"; +import mem, { memClear } from "mem"; +import thirdParty from "./third-party.cjs"; +import resolve from "./resolve.js"; -const fs = require("fs"); -const path = require("path"); -const uniqBy = require("lodash/uniqBy.js"); -const partition = require("lodash/partition.js"); -const fastGlob = require("fast-glob"); -const { default: mem, memClear } = require("../../vendors/mem.js"); -const thirdParty = require("./third-party.js"); -const resolve = require("./resolve.js"); +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const require = createRequire(import.meta.url); const memoizedLoad = mem(load, { cacheKey: JSON.stringify }); const memoizedSearch = mem(findPluginsInNodeModules); @@ -125,7 +128,4 @@ function isDirectory(dir) { } } -module.exports = { - loadPlugins: memoizedLoad, - clearCache, -}; +export { memoizedLoad as loadPlugins, clearCache }; diff --git a/src/common/package.json b/src/common/package.json deleted file mode 100644 index 54d221724..000000000 --- a/src/common/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "//TODO": "Remove this file when we close #10157", - "type": "commonjs", - "description": "A package.json file to use `.js` files in this directory as CommonJS module." -} diff --git a/src/common/parser-create-error.js b/src/common/parser-create-error.js index f7ee8e5e1..7416c8fef 100644 --- a/src/common/parser-create-error.js +++ b/src/common/parser-create-error.js @@ -1,5 +1,3 @@ -"use strict"; - function createError(message, loc) { // Construct an error similar to the ones thrown by Babel. const error = new SyntaxError( @@ -10,4 +8,4 @@ function createError(message, loc) { return error; } -module.exports = createError; +export default createError; diff --git a/src/common/resolve.js b/src/common/resolve.js index 8989edc97..0dd18ec61 100644 --- a/src/common/resolve.js +++ b/src/common/resolve.js @@ -1,4 +1,6 @@ -"use strict"; +import { createRequire } from "module"; + +const require = createRequire(import.meta.url); let { resolve } = require; @@ -15,4 +17,4 @@ if (resolve.length === 1 || process.env.PRETTIER_FALLBACK_RESOLVE) { }; } -module.exports = resolve; +export default resolve; diff --git a/src/common/third-party.js b/src/common/third-party.cjs similarity index 100% rename from src/common/third-party.js rename to src/common/third-party.cjs diff --git a/src/common/util-shared.js b/src/common/util-shared.js index 0c03bb731..2d1aa8218 100644 --- a/src/common/util-shared.js +++ b/src/common/util-shared.js @@ -1,6 +1,4 @@ -"use strict"; - -const { +export { getMaxContinuousCount, getStringWidth, getAlignmentSize, @@ -24,30 +22,4 @@ const { addLeadingComment, addDanglingComment, addTrailingComment, -} = require("./util.js"); - -module.exports = { - getMaxContinuousCount, - getStringWidth, - getAlignmentSize, - getIndentSize, - skip, - skipWhitespace, - skipSpaces, - skipNewline, - skipToLineEnd, - skipEverythingButNewLine, - skipInlineComment, - skipTrailingComment, - hasNewline, - hasNewlineInRange, - hasSpaces, - isNextLineEmpty, - isNextLineEmptyAfterIndex, - isPreviousLineEmpty, - getNextNonSpaceNonCommentCharacterIndex, - makeString, - addLeadingComment, - addDanglingComment, - addTrailingComment, -}; +} from "./util.js"; diff --git a/src/common/util.js b/src/common/util.js index 4acfb14d9..3a1604641 100644 --- a/src/common/util.js +++ b/src/common/util.js @@ -1,20 +1,18 @@ -"use strict"; - -const escapeStringRegexp = require("escape-string-regexp"); -const getLast = require("../utils/get-last.js"); -const { getSupportInfo } = require("../main/support.js"); -const isNonEmptyArray = require("../utils/is-non-empty-array.js"); -const getStringWidth = require("../utils/get-string-width.js"); -const { +import escapeStringRegexp from "escape-string-regexp"; +import getLast from "../utils/get-last.js"; +import { getSupportInfo } from "../main/support.js"; +import isNonEmptyArray from "../utils/is-non-empty-array.js"; +import getStringWidth from "../utils/get-string-width.js"; +import { skipWhitespace, skipSpaces, skipToLineEnd, skipEverythingButNewLine, -} = require("../utils/text/skip.js"); -const skipInlineComment = require("../utils/text/skip-inline-comment.js"); -const skipTrailingComment = require("../utils/text/skip-trailing-comment.js"); -const skipNewline = require("../utils/text/skip-newline.js"); -const getNextNonSpaceNonCommentCharacterIndexWithStartIndex = require("../utils/text/get-next-non-space-non-comment-character-index-with-start-index.js"); +} from "../utils/text/skip.js"; +import skipInlineComment from "../utils/text/skip-inline-comment.js"; +import skipTrailingComment from "../utils/text/skip-trailing-comment.js"; +import skipNewline from "../utils/text/skip-newline.js"; +import getNextNonSpaceNonCommentCharacterIndexWithStartIndex from "../utils/text/get-next-non-space-non-comment-character-index-with-start-index.js"; const getPenultimate = (arr) => arr[arr.length - 2]; @@ -479,7 +477,7 @@ function describeNodeForDebugging(node) { return nodeType + (nodeName ? " " + nodeName : ""); } -module.exports = { +export { inferParserByLanguage, getStringWidth, getMaxContinuousCount, diff --git a/src/config/find-project-root.js b/src/config/find-project-root.js index 10ca7faeb..011c224c3 100644 --- a/src/config/find-project-root.js +++ b/src/config/find-project-root.js @@ -1,10 +1,8 @@ -"use strict"; - // Simple version of `find-project-root` // https://github.com/kirstein/find-project-root/blob/master/index.js -const fs = require("fs"); -const path = require("path"); +import fs from "fs"; +import path from "path"; const MARKERS = [".git", ".hg"]; @@ -23,4 +21,4 @@ function findProjectRoot(directory) { return directory; } -module.exports = findProjectRoot; +export default findProjectRoot; diff --git a/src/config/package.json b/src/config/package.json deleted file mode 100644 index 54d221724..000000000 --- a/src/config/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "//TODO": "Remove this file when we close #10157", - "type": "commonjs", - "description": "A package.json file to use `.js` files in this directory as CommonJS module." -} diff --git a/src/config/resolve-config-editorconfig.js b/src/config/resolve-config-editorconfig.js index e7db00d1c..df790dc30 100644 --- a/src/config/resolve-config-editorconfig.js +++ b/src/config/resolve-config-editorconfig.js @@ -1,11 +1,9 @@ -"use strict"; +import path from "path"; -const path = require("path"); - -const editorconfig = require("editorconfig"); -const editorConfigToPrettier = require("editorconfig-to-prettier"); -const { default: mem, memClear } = require("../../vendors/mem.js"); -const findProjectRoot = require("./find-project-root.js"); +import editorconfig from "editorconfig"; +import editorConfigToPrettier from "editorconfig-to-prettier"; +import mem, { memClear } from "mem"; +import findProjectRoot from "./find-project-root.js"; const jsonStringifyMem = (fn) => mem(fn, { cacheKey: JSON.stringify }); @@ -40,7 +38,4 @@ function clearCache() { memClear(editorconfigAsyncWithCache); } -module.exports = { - getLoadFunction, - clearCache, -}; +export { getLoadFunction, clearCache }; diff --git a/src/config/resolve-config.js b/src/config/resolve-config.js index 560ac428e..366232cea 100644 --- a/src/config/resolve-config.js +++ b/src/config/resolve-config.js @@ -1,14 +1,13 @@ -"use strict"; +import { createRequire } from "module"; +import path from "path"; +import micromatch from "micromatch"; +import mem, { memClear } from "mem"; +import thirdParty from "../common/third-party.cjs"; -const path = require("path"); -const micromatch = require("micromatch"); -const thirdParty = require("../common/third-party.js"); - -const loadToml = require("../utils/load-toml.js"); -const loadJson5 = require("../utils/load-json5.js"); -const resolve = require("../common/resolve.js"); -const { default: mem, memClear } = require("../../vendors/mem.js"); -const resolveEditorConfig = require("./resolve-config-editorconfig.js"); +import loadToml from "../utils/load-toml.js"; +import loadJson5 from "../utils/load-json5.js"; +import resolve from "../common/resolve.js"; +import * as resolveEditorConfig from "./resolve-config-editorconfig.js"; /** * @typedef {import("cosmiconfig/dist/Explorer").Explorer} Explorer @@ -20,6 +19,7 @@ const resolveEditorConfig = require("./resolve-config-editorconfig.js"); */ const getExplorerMemoized = mem( (opts) => { + const require = createRequire(import.meta.url); const cosmiconfig = thirdParty["cosmiconfig" + (opts.sync ? "Sync" : "")]; const explorer = cosmiconfig("prettier", { cache: opts.cache, @@ -192,8 +192,4 @@ function pathMatchesGlobs(filePath, patterns, excludedPatterns) { ); } -module.exports = { - resolveConfig, - resolveConfigFile, - clearCache, -}; +export { resolveConfig, resolveConfigFile, clearCache }; diff --git a/src/document/doc-printer.js b/src/document/doc-printer.js index 1a45f78c6..a8e422178 100644 --- a/src/document/doc-printer.js +++ b/src/document/doc-printer.js @@ -1,6 +1,6 @@ "use strict"; -const { convertEndOfLineToChars } = require("../common/end-of-line.js"); +const { convertEndOfLineToChars } = require("../common/end-of-line.cjs"); const getLast = require("../utils/get-last.js"); const getStringWidth = require("../utils/get-string-width.js"); const { fill, cursor, indent } = require("./doc-builders.js"); diff --git a/src/index.js b/src/index.js index dcdc496ba..bf0719b70 100644 --- a/src/index.js +++ b/src/index.js @@ -2,12 +2,28 @@ import { createRequire } from "module"; import core from "./main/core.js"; import { getSupportInfo } from "./main/support.js"; import getFileInfo from "./common/get-file-info.js"; -import sharedUtil from "./common/util-shared.js"; -import plugins from "./common/load-plugins.js"; -import config from "./config/resolve-config.js"; +import * as sharedUtil from "./common/util-shared.js"; +import { + loadPlugins, + clearCache as clearPluginCache, +} from "./common/load-plugins.js"; +import { + resolveConfig, + resolveConfigFile, + clearCache as clearConfigCache, +} from "./config/resolve-config.js"; import doc from "./document/index.js"; import languages from "./languages.js"; +import * as errors from "./common/errors.js"; +import * as coreOptions from "./main/core-options.js"; +import createIgnorer from "./common/create-ignorer.js"; +import * as optionsModule from "./main/options.js"; +import * as optionsNormalizer from "./main/options-normalizer.js"; +import arrayify from "./utils/arrayify.js"; +import getLast from "./utils/get-last.js"; +import { isNonEmptyArray } from "./common/util.js"; + const require = createRequire(import.meta.url); const { version } = require("../package.json"); @@ -22,7 +38,7 @@ function _withPlugins( ...opts, plugins: [ ...languages, - ...plugins.loadPlugins(opts.plugins, opts.pluginSearchDirs), + ...loadPlugins(opts.plugins, opts.pluginSearchDirs), ], }; return fn(...args); @@ -54,11 +70,11 @@ const prettier = { doc, - resolveConfig: config.resolveConfig, - resolveConfigFile: config.resolveConfigFile, + resolveConfig, + resolveConfigFile, clearConfigCache() { - config.clearCache(); - plugins.clearCache(); + clearConfigCache(); + clearPluginCache(); }, /** @type {typeof getFileInfo} */ @@ -72,15 +88,15 @@ const prettier = { // Internal shared __internal: { - errors: require("./common/errors.js"), - coreOptions: require("./main/core-options.js"), - createIgnorer: require("./common/create-ignorer.js"), - optionsModule: require("./main/options.js"), - optionsNormalizer: require("./main/options-normalizer.js"), + errors, + coreOptions, + createIgnorer, + optionsModule, + optionsNormalizer, utils: { - arrayify: require("./utils/arrayify.js"), - getLast: require("./utils/get-last.js"), - isNonEmptyArray: require("./common/util.js").isNonEmptyArray, + arrayify, + getLast, + isNonEmptyArray, }, }, diff --git a/src/language-html/utils/index.js b/src/language-html/utils/index.js index d932c3eb4..355b49e92 100644 --- a/src/language-html/utils/index.js +++ b/src/language-html/utils/index.js @@ -1,5 +1,5 @@ /** - * @typedef {import("../../common/ast-path")} AstPath + * @typedef {import("../../common/ast-path.js").default} AstPath */ import { inferParserByLanguage, isFrontMatterNode } from "../../common/util.js"; diff --git a/src/language-js/comments.js b/src/language-js/comments.js index 2bf77d630..b53acb3ce 100644 --- a/src/language-js/comments.js +++ b/src/language-js/comments.js @@ -33,7 +33,7 @@ import isBlockComment from "./utils/is-block-comment.js"; /** * @typedef {import("./types/estree").Node} Node * @typedef {import("./types/estree").Comment} Comment - * @typedef {import("../common/ast-path")} AstPath + * @typedef {import("../common/ast-path.js").default} AstPath * * @typedef {Object} CommentContext * @property {Comment} comment diff --git a/src/language-js/loc.cjs b/src/language-js/loc.cjs deleted file mode 100644 index 9d1be4f6f..000000000 --- a/src/language-js/loc.cjs +++ /dev/null @@ -1,33 +0,0 @@ -// A cjs version of loc.js to use in `../main/parser.js` -"use strict"; - -const isNonEmptyArray = require("../utils/is-non-empty-array.js"); - -/** - * @typedef {import("./types/estree").Node} Node - */ - -function locStart(node, opts) { - const { ignoreDecorators } = opts || {}; - - // Handle nodes with decorators. They should start at the first decorator - if (!ignoreDecorators) { - const decorators = - (node.declaration && node.declaration.decorators) || node.decorators; - - if (isNonEmptyArray(decorators)) { - return locStart(decorators[0]); - } - } - - return node.range ? node.range[0] : node.start; -} - -function locEnd(node) { - return node.range ? node.range[1] : node.end; -} - -module.exports = { - locStart, - locEnd, -}; diff --git a/src/language-js/print/angular.js b/src/language-js/print/angular.js index 1a86c0a6d..85f5c10dd 100644 --- a/src/language-js/print/angular.js +++ b/src/language-js/print/angular.js @@ -6,7 +6,7 @@ const { builders: { join, line, group }, } = doc; -/** @typedef {import("../../common/ast-path")} AstPath */ +/** @typedef {import("../../common/ast-path.js").default} AstPath */ function printAngular(path, options, print) { const node = path.getValue(); diff --git a/src/language-js/print/jsx.js b/src/language-js/print/jsx.js index 0a7b55bd2..3ad204bc4 100644 --- a/src/language-js/print/jsx.js +++ b/src/language-js/print/jsx.js @@ -36,7 +36,7 @@ const isEmptyStringOrAnyLine = (doc) => doc === "" || doc === line || doc === hardline || doc === softline; /** - * @typedef {import("../../common/ast-path")} AstPath + * @typedef {import("../../common/ast-path.js").default} AstPath * @typedef {import("../types/estree").Node} Node * @typedef {import("../types/estree").JSXElement} JSXElement */ diff --git a/src/language-js/print/ternary.js b/src/language-js/print/ternary.js index c8ef1568f..44b1943b2 100644 --- a/src/language-js/print/ternary.js +++ b/src/language-js/print/ternary.js @@ -24,7 +24,7 @@ const { /** * @typedef {import("../../document").Doc} Doc - * @typedef {import("../../common/ast-path")} AstPath + * @typedef {import("../../common/ast-path.js").default} AstPath * * @typedef {any} Options - Prettier options (TBD ...) */ diff --git a/src/language-js/utils/index.js b/src/language-js/utils/index.js index aed479c22..229415241 100644 --- a/src/language-js/utils/index.js +++ b/src/language-js/utils/index.js @@ -26,7 +26,7 @@ const isIdentifierName = esutils.keyword.isIdentifierNameES5; * @typedef {import("../types/estree").TaggedTemplateExpression} TaggedTemplateExpression * @typedef {import("../types/estree").Literal} Literal * - * @typedef {import("../../common/ast-path")} AstPath + * @typedef {import("../../common/ast-path.js").default} AstPath */ // We match any whitespace except line terminators because diff --git a/src/main/ast-to-doc.js b/src/main/ast-to-doc.js index 46d6b8d5d..c8f2280e3 100644 --- a/src/main/ast-to-doc.js +++ b/src/main/ast-to-doc.js @@ -1,12 +1,12 @@ -"use strict"; +import AstPath from "../common/ast-path.js"; +import doc from "../document/index.js"; +import { printComments } from "./comments.js"; +import { printSubtree } from "./multiparser.js"; -const AstPath = require("../common/ast-path.js"); const { builders: { hardline, addAlignmentToDoc }, utils: { propagateBreaks }, -} = require("../document/index.js"); -const { printComments } = require("./comments.js"); -const multiparser = require("./multiparser.js"); +} = doc; /** * Takes an abstract syntax tree (AST) and recursively converts it to a @@ -119,7 +119,7 @@ function callPluginPrintFunction(path, options, printPath, args) { if (node) { try { // Potentially switch to a different parser - doc = multiparser.printSubtree(path, printPath, options, printAstToDoc); + doc = printSubtree(path, printPath, options, printAstToDoc); } catch (error) { /* istanbul ignore if */ if (process.env.PRETTIER_DEBUG) { @@ -148,4 +148,4 @@ function callPluginPrintFunction(path, options, printPath, args) { return doc; } -module.exports = printAstToDoc; +export default printAstToDoc; diff --git a/src/main/comments.js b/src/main/comments.js index 77d961586..e860b1b10 100644 --- a/src/main/comments.js +++ b/src/main/comments.js @@ -1,12 +1,8 @@ -"use strict"; +import assert from "assert"; -const assert = require("assert"); +import doc from "../document/index.js"; -const { - builders: { line, hardline, breakParent, indent, lineSuffix, join, cursor }, -} = require("../document/index.js"); - -const { +import { hasNewline, skipNewline, skipSpaces, @@ -14,7 +10,11 @@ const { addLeadingComment, addDanglingComment, addTrailingComment, -} = require("../common/util.js"); +} from "../common/util.js"; + +const { + builders: { line, hardline, breakParent, indent, lineSuffix, join, cursor }, +} = doc; const childNodesCache = new WeakMap(); function getSortedChildNodes(node, options, resultArray) { @@ -601,7 +601,7 @@ function ensureAllCommentsPrinted(astComments) { } } -module.exports = { +export { attach, printComments, printCommentsSeparately, diff --git a/src/main/core-options.js b/src/main/core-options.js index 5992da931..30587e79c 100644 --- a/src/main/core-options.js +++ b/src/main/core-options.js @@ -1,6 +1,4 @@ -"use strict"; - -const { outdent } = require("outdent"); +import { outdent } from "outdent"; const CATEGORY_CONFIG = "Config"; const CATEGORY_EDITOR = "Editor"; @@ -266,7 +264,7 @@ const options = { }, }; -module.exports = { +export { CATEGORY_CONFIG, CATEGORY_EDITOR, CATEGORY_FORMAT, diff --git a/src/main/core.js b/src/main/core.js index 07e40624f..d6d8fddbb 100644 --- a/src/main/core.js +++ b/src/main/core.js @@ -1,25 +1,25 @@ -"use strict"; - // Use `diff/lib/diff/array.js` instead of `diff` to reduce bundle size -const { diffArrays } = require("diff/lib/diff/array.js"); +import { diffArrays } from "diff/lib/diff/array.js"; -const { - printer: { printDocToString }, - debug: { printDocToDebug }, -} = require("../document/index.js"); -const { getAlignmentSize } = require("../common/util.js"); -const { +import doc from "../document/index.js"; +import { getAlignmentSize } from "../common/util.js"; +import { guessEndOfLine, convertEndOfLineToChars, countEndOfLineChars, normalizeEndOfLine, -} = require("../common/end-of-line.js"); -const normalizeOptions = require("./options.js").normalize; -const massageAST = require("./massage-ast.js"); -const comments = require("./comments.js"); -const parser = require("./parser.js"); -const printAstToDoc = require("./ast-to-doc.js"); -const rangeUtil = require("./range-util.js"); +} from "../common/end-of-line.js"; +import { normalize as normalizeOptions } from "./options.js"; +import massageAST from "./massage-ast.js"; +import { ensureAllCommentsPrinted, attach } from "./comments.js"; +import { parse, resolveParser } from "./parser.js"; +import printAstToDoc from "./ast-to-doc.js"; +import { calculateRange, findNodeAtOffset } from "./range-util.js"; + +const { + printer: { printDocToString }, + debug: { printDocToDebug }, +} = doc; const BOM = "\uFEFF"; @@ -29,7 +29,7 @@ function attachComments(text, ast, opts) { const astComments = ast.comments; if (astComments) { delete ast.comments; - comments.attach(astComments, ast, text, opts); + attach(astComments, ast, text, opts); } opts[Symbol.for("comments")] = astComments || []; opts[Symbol.for("tokens")] = ast.tokens || []; @@ -42,10 +42,10 @@ function coreFormat(originalText, opts, addAlignmentSize = 0) { return { formatted: "", cursorOffset: -1, comments: [] }; } - const { ast, text } = parser.parse(originalText, opts); + const { ast, text } = parse(originalText, opts); if (opts.cursorOffset >= 0) { - const nodeResult = rangeUtil.findNodeAtOffset(ast, opts.cursorOffset, opts); + const nodeResult = findNodeAtOffset(ast, opts.cursorOffset, opts); if (nodeResult && nodeResult.node) { opts.cursorNode = nodeResult.node; } @@ -56,7 +56,7 @@ function coreFormat(originalText, opts, addAlignmentSize = 0) { const result = printDocToString(doc, opts); - comments.ensureAllCommentsPrinted(astComments); + ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline if (addAlignmentSize > 0) { const trimmed = result.formatted.trim(); @@ -146,8 +146,8 @@ function coreFormat(originalText, opts, addAlignmentSize = 0) { } function formatRange(originalText, opts) { - const { ast, text } = parser.parse(originalText, opts); - const { rangeStart, rangeEnd } = rangeUtil.calculateRange(text, opts, ast); + const { ast, text } = parse(originalText, opts); + const { rangeStart, rangeEnd } = calculateRange(text, opts, ast); const rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line. @@ -276,7 +276,7 @@ function normalizeInputAndOptions(text, options) { } function hasPragma(text, options) { - const selectedParser = parser.resolveParser(options); + const selectedParser = resolveParser(options); return !selectedParser.hasPragma || selectedParser.hasPragma(text); } @@ -324,7 +324,7 @@ function formatWithCursor(originalText, originalOptions) { return result; } -module.exports = { +const prettier = { formatWithCursor, parse(originalText, originalOptions, massage) { @@ -332,7 +332,7 @@ module.exports = { originalText, normalizeOptions(originalOptions) ); - const parsed = parser.parse(text, options); + const parsed = parse(text, options); if (massage) { parsed.ast = massageAST(parsed.ast, options); } @@ -355,7 +355,7 @@ module.exports = { printToDoc(originalText, options) { options = normalizeOptions(options); - const { ast, text } = parser.parse(originalText, options); + const { ast, text } = parse(originalText, options); attachComments(text, ast, options); return printAstToDoc(ast, options); }, @@ -364,3 +364,5 @@ module.exports = { return printDocToString(doc, normalizeOptions(options)); }, }; + +export default prettier; diff --git a/src/main/massage-ast.js b/src/main/massage-ast.js index 784b568e9..f8dfbe1b7 100644 --- a/src/main/massage-ast.js +++ b/src/main/massage-ast.js @@ -1,5 +1,3 @@ -"use strict"; - function massageAST(ast, options, parent) { if (Array.isArray(ast)) { return ast.map((e) => massageAST(e, options, parent)).filter(Boolean); @@ -37,4 +35,4 @@ function massageAST(ast, options, parent) { return newObj; } -module.exports = massageAST; +export default massageAST; diff --git a/src/main/multiparser.js b/src/main/multiparser.js index 3af8b24f7..f40c66865 100644 --- a/src/main/multiparser.js +++ b/src/main/multiparser.js @@ -1,10 +1,11 @@ -"use strict"; +import doc from "../document/index.js"; +import { normalize } from "./options.js"; +import { ensureAllCommentsPrinted, attach } from "./comments.js"; +import { parse } from "./parser.js"; const { utils: { stripTrailingHardline }, -} = require("../document/index.js"); -const { normalize } = require("./options.js"); -const comments = require("./comments.js"); +} = doc; function printSubtree(path, print, options, printAstToDoc) { if (options.printer.embed && options.embeddedLanguageFormatting === "auto") { @@ -42,18 +43,18 @@ function textToDoc( { passThrough: true } ); - const result = require("./parser.js").parse(text, nextOptions); + const result = parse(text, nextOptions); const { ast } = result; text = result.text; const astComments = ast.comments; delete ast.comments; - comments.attach(astComments, ast, text, nextOptions); + attach(astComments, ast, text, nextOptions); nextOptions[Symbol.for("comments")] = astComments || []; nextOptions[Symbol.for("tokens")] = ast.tokens || []; const doc = printAstToDoc(ast, nextOptions); - comments.ensureAllCommentsPrinted(astComments); + ensureAllCommentsPrinted(astComments); if (shouldStripTrailingHardline) { // TODO: move this to `stripTrailingHardline` function in `/src/document/doc-utils.js` @@ -68,6 +69,4 @@ function textToDoc( return doc; } -module.exports = { - printSubtree, -}; +export { printSubtree }; diff --git a/src/main/options-normalizer.js b/src/main/options-normalizer.js index 17742108f..59b1b8c30 100644 --- a/src/main/options-normalizer.js +++ b/src/main/options-normalizer.js @@ -1,8 +1,6 @@ -"use strict"; - -const vnopts = require("vnopts"); -const leven = require("leven"); -const getLast = require("../utils/get-last.js"); +import vnopts from "vnopts"; +import leven from "leven"; +import getLast from "../utils/get-last.js"; const cliDescriptor = { key: (key) => (key.length === 1 ? `-${key}` : `--${key}`), @@ -257,7 +255,4 @@ function normalizeCliOptions(options, optionInfos, opts) { return normalizeOptions(options, optionInfos, { isCLI: true, ...opts }); } -module.exports = { - normalizeApiOptions, - normalizeCliOptions, -}; +export { normalizeApiOptions, normalizeCliOptions }; diff --git a/src/main/options.js b/src/main/options.js index 27f21f7b7..25f213ce4 100644 --- a/src/main/options.js +++ b/src/main/options.js @@ -1,10 +1,9 @@ -"use strict"; - -const path = require("path"); -const { UndefinedParserError } = require("../common/errors.js"); -const { getSupportInfo } = require("../main/support.js"); -const normalizer = require("./options-normalizer.js"); -const { resolveParser } = require("./parser.js"); +import { createRequire } from "module"; +import path from "path"; +import { UndefinedParserError } from "../common/errors.js"; +import { getSupportInfo } from "../main/support.js"; +import { normalizeApiOptions } from "./options-normalizer.js"; +import { resolveParser } from "./parser.js"; const hiddenDefaults = { astFormat: "estree", @@ -52,7 +51,7 @@ function normalize(options, opts = {}) { } const parser = resolveParser( - normalizer.normalizeApiOptions( + normalizeApiOptions( rawOptions, [supportOptions.find((x) => x.name === "parser")], { passThrough: true, logger: false } @@ -90,7 +89,7 @@ function normalize(options, opts = {}) { rawOptions.trailingComma = "none"; } - return normalizer.normalizeApiOptions(rawOptions, supportOptions, { + return normalizeApiOptions(rawOptions, supportOptions, { passThrough: Object.keys(hiddenDefaults), ...opts, }); @@ -140,6 +139,7 @@ function inferParser(filepath, plugins) { !language && !filename.includes(".") ) { + const require = createRequire(import.meta.url); // `getInterpreter` requires file access, put `require()` in the `if` block, // So we can easily remove this part during build const getInterpreter = require("../utils/get-interpreter.js"); @@ -153,4 +153,4 @@ function inferParser(filepath, plugins) { return language && language.parsers[0]; } -module.exports = { normalize, hiddenDefaults, inferParser }; +export { normalize, hiddenDefaults, inferParser }; diff --git a/src/main/package.json b/src/main/package.json deleted file mode 100644 index 54d221724..000000000 --- a/src/main/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "//TODO": "Remove this file when we close #10157", - "type": "commonjs", - "description": "A package.json file to use `.js` files in this directory as CommonJS module." -} diff --git a/src/main/parser.js b/src/main/parser.js index defccccd0..e49d9c75d 100644 --- a/src/main/parser.js +++ b/src/main/parser.js @@ -1,11 +1,9 @@ -"use strict"; +import { createRequire } from "module"; +import path from "path"; +import { ConfigError } from "../common/errors.js"; +import { locStart, locEnd } from "../language-js/loc.js"; -const path = require("path"); -const { ConfigError } = require("../common/errors.js"); -// TODO: Use esm version -const jsLoc = require("../language-js/loc.cjs"); - -const { locStart, locEnd } = jsLoc; +const require = createRequire(import.meta.url); // Use defineProperties()/getOwnPropertyDescriptor() to prevent // triggering the parsers getters. @@ -111,4 +109,4 @@ function parse(text, opts) { } } -module.exports = { parse, resolveParser }; +export { parse, resolveParser }; diff --git a/src/main/range-util.js b/src/main/range-util.js index ecb396ef1..b6c364cc9 100644 --- a/src/main/range-util.js +++ b/src/main/range-util.js @@ -1,7 +1,5 @@ -"use strict"; - -const assert = require("assert"); -const comments = require("./comments.js"); +import assert from "assert"; +import { getSortedChildNodes } from "./comments.js"; const isJsonParser = ({ parser }) => parser === "json" || parser === "json5" || parser === "json-stringify"; @@ -93,7 +91,7 @@ function findNodeAtOffset( return; } - for (const childNode of comments.getSortedChildNodes(node, options)) { + for (const childNode of getSortedChildNodes(node, options)) { const childResult = findNodeAtOffset( childNode, offset, @@ -252,7 +250,4 @@ function calculateRange(text, opts, ast) { }; } -module.exports = { - calculateRange, - findNodeAtOffset, -}; +export { calculateRange, findNodeAtOffset }; diff --git a/src/main/support.js b/src/main/support.js index 6bf3ad8d8..5eb258b0b 100644 --- a/src/main/support.js +++ b/src/main/support.js @@ -1,13 +1,13 @@ -"use strict"; +import { createRequire } from "module"; +import semverCompare from "semver/functions/compare.js"; +import semverGte from "semver/functions/gte.js"; +import semverLt from "semver/functions/lt.js"; +import arrayify from "../utils/arrayify.js"; +import { options as coreOptions } from "./core-options.js"; + +const require = createRequire(import.meta.url); -const semver = { - compare: require("semver/functions/compare"), - lt: require("semver/functions/lt"), - gte: require("semver/functions/gte"), -}; -const arrayify = require("../utils/arrayify.js"); const currentVersion = require("../../package.json").version; -const coreOptions = require("./core-options.js").options; /** * Strings in `plugins` and `pluginSearchDirs` are handled by a wrapped version @@ -50,7 +50,7 @@ function getSupportInfo({ : option.default .filter(filterSince) .sort((info1, info2) => - semver.compare(info2.since, info1.since) + semverCompare(info2.since, info1.since) )[0].value; } @@ -83,7 +83,7 @@ function getSupportInfo({ return ( showUnreleased || !("since" in object) || - (object.since && semver.gte(version, object.since)) + (object.since && semverGte(version, object.since)) ); } @@ -91,7 +91,7 @@ function getSupportInfo({ return ( showDeprecated || !("deprecated" in object) || - (object.deprecated && semver.lt(version, object.deprecated)) + (object.deprecated && semverLt(version, object.deprecated)) ); } @@ -125,6 +125,4 @@ function collectParsersFromLanguages(option, languages, plugins) { } } -module.exports = { - getSupportInfo, -}; +export { getSupportInfo }; diff --git a/src/standalone.js b/src/standalone.js index 9f38ffe45..2f809f2a9 100644 --- a/src/standalone.js +++ b/src/standalone.js @@ -1,7 +1,7 @@ import { createRequire } from "module"; import core from "./main/core.js"; import { getSupportInfo } from "./main/support.js"; -import sharedUtil from "./common/util-shared.js"; +import * as sharedUtil from "./common/util-shared.js"; import languages from "./languages.js"; import doc from "./document/index.js"; diff --git a/tests/integration/__tests__/bundle.js b/tests/integration/__tests__/bundle.js index 57c23a1f7..523f29556 100644 --- a/tests/integration/__tests__/bundle.js +++ b/tests/integration/__tests__/bundle.js @@ -2,7 +2,7 @@ import path from "node:path"; import createEsmUtils from "esm-utils"; import fastGlob from "fast-glob"; import { projectRoot } from "../env.js"; -import coreOptions from "../../../src/main/core-options.js"; +import * as coreOptions from "../../../src/main/core-options.js"; import codeSamples from "../../../website/playground/codeSamples.mjs"; import jestPathSerializer from "../path-serializer.js"; diff --git a/tests/integration/__tests__/util-shared.js b/tests/integration/__tests__/util-shared.js index 6947373e5..d3d23fe14 100644 --- a/tests/integration/__tests__/util-shared.js +++ b/tests/integration/__tests__/util-shared.js @@ -1,4 +1,4 @@ -import sharedUtil from "../../../src/common/util-shared.js"; +import * as sharedUtil from "../../../src/common/util-shared.js"; test("shared util has correct structure", () => { expect(typeof sharedUtil.getMaxContinuousCount).toBe("function");