diff --git a/.github/renovate.json b/.github/renovate.json index e334cc23..b1ad17fa 100644 --- a/.github/renovate.json +++ b/.github/renovate.json @@ -10,7 +10,7 @@ "@rslib/core", "@rslint/core", "@rstest/core", - "@swc-next/parser", + "@swc-next/formatter-prettier-plugin", "prettier" ], "groupName": null, diff --git a/packages/rstack/THIRD_PARTY_NOTICES.md b/packages/rstack/THIRD_PARTY_NOTICES.md index 4948fef4..cc354db3 100644 --- a/packages/rstack/THIRD_PARTY_NOTICES.md +++ b/packages/rstack/THIRD_PARTY_NOTICES.md @@ -29,36 +29,6 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -## Prettier SWC next parser adapter - -The local SWC Next parser adapter includes portions derived from -[@prettier/plugin-yuku](https://github.com/prettier/prettier/tree/main/packages/plugin-yuku) -and Prettier's JavaScript parser postprocessing. The adapter reuses the public -ESTree printer, formatter options, and parser utilities from the installed -`prettier` package. - -License: MIT - -Copyright © James Long and contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - ## fresh-import This package includes bundled code from [fresh-import](https://github.com/sapphi-red/fresh-import). diff --git a/packages/rstack/package.json b/packages/rstack/package.json index dedc2088..ec7e8843 100644 --- a/packages/rstack/package.json +++ b/packages/rstack/package.json @@ -77,7 +77,7 @@ "@rslib/core": "catalog:", "@rslint/core": "catalog:", "@rstest/core": "catalog:", - "@swc-next/parser": "catalog:", + "@swc-next/formatter-prettier-plugin": "catalog:", "prettier": "catalog:", "tinypool": "catalog:" }, diff --git a/packages/rstack/src/configLayers.ts b/packages/rstack/src/configLayers.ts index 615db230..b2973213 100644 --- a/packages/rstack/src/configLayers.ts +++ b/packages/rstack/src/configLayers.ts @@ -120,7 +120,7 @@ export const resolveFmtConfigLayers = async ( ): Promise => { const configs = await resolveConfigLayers(layers, 'fmt'); return configs.length > 1 - ? (Object.assign({}, ...configs) as FmtConfig) + ? Object.assign({}, ...configs) as FmtConfig : configs[0]; }; diff --git a/packages/rstack/src/fmt/prettierPlugins.ts b/packages/rstack/src/fmt/prettierPlugins.ts index 9c3cb2b2..281d27fd 100644 --- a/packages/rstack/src/fmt/prettierPlugins.ts +++ b/packages/rstack/src/fmt/prettierPlugins.ts @@ -17,16 +17,72 @@ const fmtOptionsPlugin = { const defaultFmtPlugins: PrettierPlugins = [swcNextPlugin, fmtOptionsPlugin]; -/** Prepends bundled plugins so project plugins can override their parsers. */ +/** Selects SWC for JS/TS files and Markdown fences unless a project plugin overrides it. */ const getPrettierPlugins = async ( options: ResolvedFmtOptions, filePath: string, ): Promise => { - // An explicit native parser is also the escape hatch for bypassing SWC Next. + const projectPlugins = await Promise.all( + (options.plugins ?? []).map(async (plugin): Promise => { + if (typeof plugin === 'string' || plugin instanceof URL) { + const loaded = (await import(String(plugin))) as Plugin & { + default?: Plugin; + }; + return loaded.default ?? loaded; + } + return plugin; + }), + ); + // Parser wrappers such as Tailwind require Prettier's AST, not a prebuilt document. + const hasJavaScriptPlugin = projectPlugins.some((plugin) => + ['babel', 'typescript', 'swc', 'swc-ts', 'swc-tsx'].some( + (parser) => plugin.parsers?.[parser], + ), + ); + // Explicit SWC parsers retain the published plugin's behavior and validation. + const isSwcParser = /^(?:swc|swc-ts|swc-tsx|swc-next|swc-next-ts)$/.test( + typeof options.parser === 'string' ? options.parser : '', + ); + const isSwcDefault = + !options.parser && + /\.(?:[cm]?[jt]s|[jt]sx)$/i.test(filePath) && + !hasJavaScriptPlugin; + // cspell:ignore mkdn mdwn mkdown + const isMarkdown = options.parser + ? typeof options.parser === 'string' && + /^(?:markdown|mdx|remark)$/.test(options.parser) + : /\.(?:md|mdx|markdown|mdown|mkdn|mkd|mdwn|mkdown|ron)$/i.test(filePath); + const isSwcEmbedded = isMarkdown && !hasJavaScriptPlugin; + // Validate before Prettier can skip empty files or files without a pragma. + // Unsupported SWC options must fail instead of silently selecting another parser. + if (isSwcParser || isSwcDefault) { + if ( + options.requirePragma || + options.insertPragma || + options.checkIgnorePragma + ) { + throw new Error('SWCFMT does not yet support pragma options'); + } + if ( + (options.rangeStart ?? 0) > 0 || + (options.rangeEnd !== undefined && options.rangeEnd !== Infinity) + ) { + throw new Error('SWCFMT currently supports whole-file formatting only'); + } + if ( + options.experimentalTernaries || + options.experimentalOperatorPosition === 'start' || + options.objectWrap === 'collapse' + ) { + throw new Error( + 'SWCFMT does not yet support the requested layout option', + ); + } + } const defaultPlugins = - options.parser === 'babel' || options.parser === 'typescript' - ? [fmtOptionsPlugin] - : defaultFmtPlugins; + isSwcParser || isSwcDefault || isSwcEmbedded + ? defaultFmtPlugins + : [fmtOptionsPlugin]; const plugins = options.sortPackageJson === true && /(^|[/\\])package\.json$/.test(filePath) ? [ @@ -35,7 +91,7 @@ const getPrettierPlugins = async ( ] : defaultPlugins; - return options.plugins?.length ? [...plugins, ...options.plugins] : plugins; + return projectPlugins.length ? [...plugins, ...projectPlugins] : plugins; }; export { getPrettierPlugins }; diff --git a/packages/rstack/src/fmt/swcNextPlugin.ts b/packages/rstack/src/fmt/swcNextPlugin.ts index 12ced541..e533cc87 100644 --- a/packages/rstack/src/fmt/swcNextPlugin.ts +++ b/packages/rstack/src/fmt/swcNextPlugin.ts @@ -1,649 +1,39 @@ -// Adapted from @prettier/plugin-yuku: -// https://github.com/prettier/prettier/blob/315f28198200d7678dadd3fd5eece499b127ff2a/packages/plugin-yuku/index.js -// https://github.com/prettier/prettier/blob/315f28198200d7678dadd3fd5eece499b127ff2a/src/language-js/parse/postprocess/index.js -// -// Differences from upstream: -// - Bundles the adapter locally and reuses Prettier's printer to avoid duplication. -// - Uses SWC Next instead of Yuku, removing unused branches and redundant checks. -// - Avoids repeated source copying and linear searches when processing comments. -// - Registers babel/typescript aliases for other plugins; uses Babel's File root for Vue. - -import * as prettierEstreePlugin from 'prettier/plugins/estree'; -import type { Parser, ParserOptions, Plugin } from 'prettier'; -import { - langFromPath, - parseSync as parseWithSwcNext, - type Comment, - type Diagnostic, - type Lang, - type ParseResult, - type SourceType, -} from '@swc-next/parser'; - -const AST_FORMAT = 'estree-swc-next'; -const JS_TS_FILE_REGEXP = /\.(?:js|mjs|cjs|jsx|ts|mts|cts|tsx)$/i; -const JSX_REGEXP = /^[^"'`]*<\/|^[^/]{2}.*\/>/m; -const SOURCE_TYPE_COMBINATIONS: SourceType[] = ['module', 'commonjs']; - -type Range = [start: number, end: number]; - -type Locatable = { - __contentEnd?: number; - alternate?: Locatable | null; - body?: Locatable; - consequent?: Locatable; - declaration?: { decorators?: Locatable[] }; - declarations?: Locatable[]; - decorators?: Locatable[]; - end?: number; - label?: Locatable | null; - range?: Range; - start?: number; - type?: string; -}; - -type AstNode = Locatable & { - [key: string]: unknown; - type: string; -}; - -type PrettierComment = Comment & { - range?: Range; -}; - -type EstreePlugin = typeof prettierEstreePlugin & { - options: NonNullable; -}; - -const estreePlugin = prettierEstreePlugin as EstreePlugin; -const estreePrinter = estreePlugin.printers.estree; - -const CONTENT_END_NODE_TYPES = new Set([ - 'ExpressionStatement', - 'Directive', - 'ImportDeclaration', - 'ExportDefaultDeclaration', - 'ExportNamedDeclaration', - 'ExportAllDeclaration', - 'ReturnStatement', - 'ThrowStatement', - 'DoWhileStatement', -]); - -/** Mirrors Prettier's JavaScript location helpers without loading its Babel plugin. */ -const locStart = (node: Locatable): number => { - const start = (node.range?.[0] ?? node.start) as number; - const firstDecorator = (node.declaration?.decorators ?? node.decorators)?.[0]; - - return firstDecorator ? Math.min(locStart(firstDecorator), start) : start; -}; - -const locEndWithFullText = (node: Locatable): number => - (node.range?.[1] ?? node.end) as number; - -const locEnd = (node: Locatable): number => { - switch (node.type) { - case 'IfStatement': - return locEnd((node.alternate ?? node.consequent) as Locatable); - - case 'ForInStatement': - case 'ForOfStatement': - case 'ForStatement': - case 'LabeledStatement': - case 'WithStatement': - case 'WhileStatement': - return locEnd(node.body as Locatable); - - case 'BreakStatement': - return node.label ? locEnd(node.label) : locStart(node) + 'break'.length; - - case 'ContinueStatement': - return node.label - ? locEnd(node.label) - : locStart(node) + 'continue'.length; - - case 'DebuggerStatement': - return locStart(node) + 'debugger'.length; - - case 'VariableDeclaration': - return locEnd(node.declarations?.at(-1) as Locatable); - - default: - return CONTENT_END_NODE_TYPES.has(node.type ?? '') - ? (node.__contentEnd ?? locEndWithFullText(node)) - : locEndWithFullText(node); - } -}; - -const DOCBLOCK_REGEXP = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/; -const COMMENT_END_REGEXP = /\*\/$/; -const COMMENT_START_REGEXP = /^\/\*\*?/; -const DOCBLOCK_LINE_START_REGEXP = /(\r?\n|^) *\* ?/g; -const PRAGMA_REGEXP = /(?:^|\r?\n) *@(\S+) *([^\n\r]*)/g; -const FORMAT_PRAGMAS = new Set(['format', 'prettier']); -const FORMAT_IGNORE_PRAGMAS = new Set(['noformat', 'noprettier']); - -/** Matches Prettier's leading JavaScript docblock pragma handling. */ -const hasPragmaFrom = (originalText: string, pragmas: Set): boolean => { - let text = originalText; - - if (text.startsWith('#!')) { - const lineEnd = text.indexOf('\n'); - text = text.slice((lineEnd === -1 ? text.length : lineEnd) + 1); - } - - const docblock = (text.match(DOCBLOCK_REGEXP)?.[0] ?? '') - .trimStart() - .replace(COMMENT_START_REGEXP, '') - .replace(COMMENT_END_REGEXP, '') - .replaceAll(DOCBLOCK_LINE_START_REGEXP, '$1'); - - for (const match of docblock.matchAll(PRAGMA_REGEXP)) { - if (pragmas.has(match[1])) { - return true; - } - } - - return false; -}; - -const hasPragma = (text: string): boolean => - hasPragmaFrom(text, FORMAT_PRAGMAS); -const hasIgnorePragma = (text: string): boolean => - hasPragmaFrom(text, FORMAT_IGNORE_PRAGMAS); - -const getVisitorKeys = estreePrinter.getVisitorKeys as - ((node: AstNode) => string[]) | undefined; - -if (!getVisitorKeys) { - throw new Error('The Prettier ESTree printer does not expose visitor keys.'); -} - -const isAstNode = (value: unknown): value is AstNode => - value !== null && - typeof value === 'object' && - !Array.isArray(value) && - typeof (value as { type?: unknown }).type === 'string'; - -const asAstNode = (value: unknown): AstNode => { - if (!isAstNode(value)) { - throw new TypeError('Expected a SWC Next AST node.'); - } - return value; -}; - -const withExtra = ( - node: AstNode, - extra: Record, -): Record => ({ - ...(node.extra !== null && typeof node.extra === 'object' - ? (node.extra as Record) - : undefined), - ...extra, -}); - -const isIndentableBlockComment = (comment: PrettierComment): boolean => { - if (comment.type !== 'Block' || !comment.value.includes('\n')) { - return false; - } - - for (let line of `*${comment.value}*`.split('\n')) { - line = line.trimStart(); - if (!line.startsWith('*')) { - return false; - } - } - - return true; -}; - -const mergeNestedJsdocComments = (comments: PrettierComment[]): void => { - let followingComment: PrettierComment | undefined; - - for (let index = comments.length - 1; index >= 0; index--) { - const comment = comments[index]; - - if ( - followingComment && - locEnd(comment) === locStart(followingComment) && - isIndentableBlockComment(comment) && - isIndentableBlockComment(followingComment) - ) { - comments.splice(index + 1, 1); - comment.value += `*//*${followingComment.value}`; - comment.range = [locStart(comment), locEnd(followingComment)]; - } - - followingComment = comment; - } -}; - -const stripComments = ( - originalText: string, - comments: PrettierComment[], -): string => { - if (comments.length === 0) { - return originalText; - } - - const chunks: string[] = []; - let cursor = 0; - - // SWC Next returns comments in source order, so mask each range while copying the source only once. - for (const comment of comments) { - const start = locStart(comment); - const end = locEnd(comment); - chunks.push(originalText.slice(cursor, start)); - chunks.push(originalText.slice(start, end).replace(/[^\n]/g, ' ')); - cursor = end; - } - - chunks.push(originalText.slice(cursor)); - return chunks.join(''); -}; - -const setContentEnd = ( - node: AstNode, - originalText: string, - getTextWithoutComments: () => string, -): void => { - if (!CONTENT_END_NODE_TYPES.has(node.type)) { - return; - } - - let end = node.range?.[1] ?? node.end; - if (end === undefined || originalText[end - 1] !== ';') { - return; - } - - end -= 1; - const textWithoutComments = getTextWithoutComments(); - const textBeforeSemicolon = textWithoutComments.slice(locStart(node), end); - const cleanedText = textBeforeSemicolon.trimEnd(); - node.__contentEnd = end - (textBeforeSemicolon.length - cleanedText.length); -}; - -const isTypeCastComment = (comment: PrettierComment): boolean => - comment.type === 'Block' && - comment.value.startsWith('*') && - /@(?:type|satisfies)\b/.test(comment.value); - -/** - * Returns the greatest value less than or equal to `target` from an ascending - * array, or `undefined` when no such value exists. - */ -const findLastAtOrBefore = ( - sortedValues: number[], - target: number, -): number | undefined => { - let lower = 0; - let upper = sortedValues.length; - - while (lower < upper) { - const middle = lower + Math.floor((upper - lower) / 2); - if (sortedValues[middle] <= target) { - lower = middle + 1; - } else { - upper = middle; - } - } - - return sortedValues[lower - 1]; -}; - -type VisitOptions = { - onEnter?: (node: AstNode) => AstNode | undefined; - onLeave?: (node: AstNode) => AstNode | undefined; -}; - -const visitNode = (value: unknown, options: VisitOptions): unknown => { - if (value === null || typeof value !== 'object') { - return value; - } - - if (Array.isArray(value)) { - for (let index = 0; index < value.length; index++) { - value[index] = visitNode(value[index], options); - } - return value; - } - - // Trust the parser's child nodes; validate the root at the parser entry point. - let node = value as AstNode; - - if (options.onEnter) { - const result = options.onEnter(node) ?? node; - if (result !== node) { - return visitNode(result, options); - } - node = result; - } - - for (const key of getVisitorKeys(node)) { - node[key] = visitNode(node[key], options); - } - - return options.onLeave?.(node) ?? node; -}; - -const isUnbalancedLogicalTree = (node: AstNode): boolean => { - if (node.type !== 'LogicalExpression') { - return false; - } - - const right = node.right as AstNode; - return right.type === 'LogicalExpression' && node.operator === right.operator; -}; - -const rebalanceLogicalTree = (node: AstNode): AstNode => { - if (!isUnbalancedLogicalTree(node)) { - return node; - } - - const left = node.left as AstNode; - const right = node.right as AstNode; - const rightLeft = right.left as AstNode; - const rightRight = right.right as AstNode; - - return rebalanceLogicalTree({ - type: 'LogicalExpression', - operator: node.operator, - left: rebalanceLogicalTree({ - type: 'LogicalExpression', - operator: node.operator, - left, - right: rightLeft, - range: [locStart(left), locEnd(rightLeft)], - }), - right: rightRight, - range: [locStart(node), locEnd(node)], - }); -}; - -const postprocess = ( - ast: AstNode, - comments: PrettierComment[], - text: string, - astType: 'swc-next-js' | 'swc-next-ts', -): AstNode => { - mergeNestedJsdocComments(comments); - - if (isAstNode(ast.hashbang)) { - comments.unshift(ast.hashbang as unknown as PrettierComment); - delete ast.hashbang; - } - - ast.comments = comments; - ast.range = [0, text.length]; - - let textWithoutComments: string | undefined; - const getTextWithoutComments = (): string => { - textWithoutComments ??= stripComments(text, comments); - return textWithoutComments; - }; - let typeCastCommentEnds: number[] | undefined; - - return visitNode(ast, { - onEnter(node) { - setContentEnd(node, text, getTextWithoutComments); - - switch (node.type) { - case 'TSModuleDeclaration': - // Prettier's printer silently drops these attributes. - // https://github.com/prettier/prettier/issues/20531 - if (node.attributes) { - throw new SyntaxError( - 'Prettier does not support formatting ambient module import attributes yet.', - ); - } - break; - - case 'ParenthesizedExpression': { - const expression = node.expression as AstNode; - const start = locStart(node); - - // SWC Next comments are in source order, so these end offsets are sorted. - typeCastCommentEnds ??= comments - .filter(isTypeCastComment) - .map((comment) => locEnd(comment)); - - const previousCommentEnd = findLastAtOrBefore( - typeCastCommentEnds, - start, - ); - const shouldKeepParentheses = - previousCommentEnd !== undefined && - text.slice(previousCommentEnd, start).trim().length === 0; - - if (shouldKeepParentheses) { - return undefined; - } - - expression.extra = withExtra(expression, { parenthesized: true }); - return expression; - } - - case 'TemplateElement': { - if (astType === 'swc-next-ts') { - const start = locStart(node) + 1; - const end = locEnd(node) - (node.tail ? 1 : 2); - node.range = [start, end]; - } - break; - } - - case 'TSParenthesizedType': - return node.typeAnnotation as AstNode; - - case 'TSUnionType': - case 'TSIntersectionType': { - const types = node.types as unknown[]; - if (types.length === 1) { - return types[0] as AstNode; - } - break; - } - } - - return undefined; - }, - onLeave(node) { - return isUnbalancedLogicalTree(node) - ? rebalanceLogicalTree(node) - : undefined; - }, - }) as AstNode; -}; - -const indexToPosition = ( - text: string, - index: number, -): { column: number; line: number } => { - const lineBreakBefore = index === 0 ? -1 : text.lastIndexOf('\n', index - 1); - let line = 1; - - for (let current = 0; current <= lineBreakBefore; current++) { - if (text[current] === '\n') { - line++; - } - } - - return { - column: index - lineBreakBefore, - line, - }; -}; - -const createParseError = (error: Diagnostic, text: string): SyntaxError => { - const start = indexToPosition(text, error.start); - const end = indexToPosition(text, error.end); - - return Object.assign( - new SyntaxError(`${error.message} (${start.line}:${start.column})`), - { - cause: error, - loc: { start, end }, - }, - ); -}; - -const parseWithOptions = ( - text: string, - options: { sourceType: SourceType; lang: Lang }, -): ParseResult => { - const result = parseWithSwcNext(text, { - preserveParens: true, - comments: 'all', - // Return diagnostics so they can be converted to Prettier-compatible errors. - errorRecovery: true, - ...options, - }); - - if (result.diagnostics.length > 0) { - throw createParseError(result.diagnostics[0], text); - } - - return result; -}; - -const getSourceType = (filepath: string): SourceType | undefined => { - if (/\.(?:mjs|mts)$/i.test(filepath)) { - return 'module'; - } - - if (/\.(?:cjs|cts)$/i.test(filepath)) { - return 'commonjs'; - } - - return undefined; -}; - -const getLanguageCombinations = (text: string, filepath: string): Lang[] => { - const normalizedPath = filepath.toLowerCase(); - - if (JS_TS_FILE_REGEXP.test(normalizedPath)) { - return [langFromPath(normalizedPath)]; - } - - // Embedded code from Vue or Svelte keeps the host file path, so detect JSX from its content. - return JSX_REGEXP.test(text) ? ['tsx', 'ts', 'dts'] : ['ts', 'tsx', 'dts']; -}; - -const tryCombinations = (combinations: (() => ParseResult)[]): ParseResult => { - let firstError: unknown; - let hasError = false; - - for (const combination of combinations) { - try { - return combination(); - } catch (error) { - if (!hasError) { - firstError = error; - hasError = true; - } - } - } - - if (hasError) { - throw firstError; - } - - throw new Error('No SWC Next parser combinations were provided.'); -}; - -const parseJavaScript = ( - text: string, - options: ParserOptions, -): AstNode => { - const sourceType = getSourceType(options.filepath); - const combinations = ( - sourceType ? [sourceType] : SOURCE_TYPE_COMBINATIONS - ).map( - (candidate) => () => - parseWithOptions(text, { sourceType: candidate, lang: 'jsx' }), - ); - const result = tryCombinations(combinations); - - return postprocess( - asAstNode(result.program), - result.comments, - text, - 'swc-next-js', - ); -}; - -const parseTypeScript = ( - text: string, - options: ParserOptions, -): AstNode => { - const sourceType = getSourceType(options.filepath); - const languages = getLanguageCombinations(text, options.filepath); - const combinations = ( - sourceType ? [sourceType] : SOURCE_TYPE_COMBINATIONS - ).flatMap((candidate) => - languages.map( - (lang) => () => parseWithOptions(text, { sourceType: candidate, lang }), - ), - ); - const result = tryCombinations(combinations); - - return postprocess( - asAstNode(result.program), - result.comments, - text, - 'swc-next-ts', - ); -}; - -const createParser = ( - parse: (text: string, options: ParserOptions) => AstNode, -): Parser => ({ - astFormat: AST_FORMAT, - hasIgnorePragma, - hasPragma, - locEnd, - locStart, - parse, -}); - -/** Match the AST root returned by Prettier's native Babel parser. */ -const parseBabel = (text: string, options: ParserOptions): AstNode => { - const program = parseJavaScript(text, options); - const comments = program.comments; - const start = locStart(program); - const end = locEndWithFullText(program); - - // Babel stores comments on the File node rather than its Program child. - delete program.comments; - - return { - type: 'File', - comments, - end, - errors: [], - program, - range: [start, end], - start, - }; +import * as swc from '@swc-next/formatter-prettier-plugin'; +import type { Plugin } from 'prettier'; + +const parsers = swc.parsers!; +const swcNextTypeScriptParser: (typeof parsers)[string] = { + ...parsers['swc-ts'], + parse(text, options) { + const parser = /\.tsx$/i.test(options.filepath ?? '') + ? 'swc-tsx' + : 'swc-ts'; + return parsers[parser].parse(text, options); + }, }; -const swcNextParser = createParser(parseJavaScript); -const swcNextBabelParser = createParser(parseBabel); -const swcNextTypeScriptParser = createParser(parseTypeScript); - +// Keep the existing parser names available to configurations using them explicitly. const swcNextPlugin: Plugin = { - options: estreePlugin.options, + ...swc, + // Markdown resolves fence languages by name and alias before file extension. + // The published plugin omits these aliases and a separate JSX language entry. + languages: [ + ...swc.languages!.map((language) => ({ + ...language, + aliases: + language.name === 'JavaScript' + ? ['js', 'node'] + : language.name === 'TypeScript' + ? ['ts'] + : ['typescriptreact'], + })), + { name: 'JSX', parsers: ['swc'], extensions: ['.jsx'] }, + ], parsers: { - // Prettier resolves parsers from the last plugin that provides the name. - // Project plugins are loaded after this one, so parser wrappers take priority. - babel: swcNextBabelParser, - typescript: swcNextTypeScriptParser, - 'swc-next': swcNextParser, + ...parsers, + 'swc-next': parsers.swc, 'swc-next-ts': swcNextTypeScriptParser, }, - printers: { - [AST_FORMAT]: estreePrinter, - }, }; export { swcNextPlugin }; diff --git a/packages/rstack/src/fmt/worker.ts b/packages/rstack/src/fmt/worker.ts index dfe27df7..8c524657 100644 --- a/packages/rstack/src/fmt/worker.ts +++ b/packages/rstack/src/fmt/worker.ts @@ -78,7 +78,7 @@ const formatFile = async ({ hasDottedBasename(file.path) ? '' : (contentHash ?? - hashContent(sourceBuffer ?? readFileSync(file.path))), + hashContent(sourceBuffer ?? readFileSync(file.path))), cache.optionsHash, 'unsupported', ], diff --git a/packages/rstack/src/staged.ts b/packages/rstack/src/staged.ts index 1eae82fc..71ead5ea 100644 --- a/packages/rstack/src/staged.ts +++ b/packages/rstack/src/staged.ts @@ -67,7 +67,7 @@ export async function runStagedCLI(args: string[]): Promise { concurrent: values.concurrent === undefined ? undefined - : (JSON.parse(values.concurrent) as boolean | number), + : JSON.parse(values.concurrent) as boolean | number, config: stagedConfig, cwd: values.cwd, debug: values.debug, diff --git a/packages/rstack/tests/fmt/runner.test.ts b/packages/rstack/tests/fmt/runner.test.ts index 35933c70..b2f6a0f9 100644 --- a/packages/rstack/tests/fmt/runner.test.ts +++ b/packages/rstack/tests/fmt/runner.test.ts @@ -23,21 +23,23 @@ const ambientModuleWithAttributes = `declare module "*" with { type: "text" } { } `; -test('reports unsupported ambient module attributes without rewriting the file', async () => { +test('formats ambient module attributes without dropping them', async () => { await withTempProject(async (rootPath) => { const filePath = path.join(rootPath, 'example.d.ts'); - writeFileSync(filePath, ambientModuleWithAttributes); + writeFileSync( + filePath, + ambientModuleWithAttributes.replace( + 'const content: string;', + 'const content:string', + ), + ); const result = await run([createFmtRequest(filePath, {})]); expect(result).toMatchObject({ - exitCode: 2, - files: [{ path: filePath, status: 'error' }], + exitCode: 0, + files: [{ path: filePath, status: 'written' }], }); - expect(result.files[0]).toHaveProperty( - 'error.message', - 'Prettier does not support formatting ambient module import attributes yet.', - ); expect(readFileSync(filePath, 'utf8')).toBe(ambientModuleWithAttributes); }); }); diff --git a/packages/rstack/tests/fmt/runnerCache.test.ts b/packages/rstack/tests/fmt/runnerCache.test.ts index 429a8773..fdc91b30 100644 --- a/packages/rstack/tests/fmt/runnerCache.test.ts +++ b/packages/rstack/tests/fmt/runnerCache.test.ts @@ -250,16 +250,14 @@ test('caches only plugins with stable fingerprints', async () => { writePackageJson('1.0.0'); await run([file], 'check', cache); - const firstHash = ( - await loadFmtCacheStore(cache.filePath, cacheNamespace) - ).get('data.fixture')?.[1]; + const firstHash = (await loadFmtCacheStore(cache.filePath, cacheNamespace)) + .get('data.fixture')?.[1]; expect(firstHash).toHaveLength(cacheHashLength); writePackageJson('2.0.0'); await run([file], 'check', cache); - const secondHash = ( - await loadFmtCacheStore(cache.filePath, cacheNamespace) - ).get('data.fixture')?.[1]; + const secondHash = (await loadFmtCacheStore(cache.filePath, cacheNamespace)) + .get('data.fixture')?.[1]; expect(secondHash).toHaveLength(cacheHashLength); expect(secondHash).not.toBe(firstHash); }); diff --git a/packages/rstack/tests/fmt/swcNextPlugin.test.ts b/packages/rstack/tests/fmt/swcNextPlugin.test.ts index 2f4b884d..20d0e988 100644 --- a/packages/rstack/tests/fmt/swcNextPlugin.test.ts +++ b/packages/rstack/tests/fmt/swcNextPlugin.test.ts @@ -1,10 +1,6 @@ -import { - format, - getFileInfo, - type Options, - type ParserOptions, -} from 'prettier'; -import { describe, expect, test } from 'rstack/test'; +import { format, getFileInfo, type Options } from 'prettier'; +import { describe, expect, rs, test } from 'rstack/test'; +import { formatFmtSource } from '../../src/fmt/format.ts'; import { getPrettierPlugins } from '../../src/fmt/prettierPlugins.ts'; import { swcNextPlugin } from '../../src/fmt/swcNextPlugin.ts'; @@ -20,44 +16,15 @@ const formatWithSwcNext = ( `example.${options.parser === 'swc-next' ? 'js' : 'ts'}`, }); -test('overrides the default JavaScript and TypeScript parsers', async () => { - expect(swcNextPlugin.languages).toBeUndefined(); - expect(swcNextPlugin.parsers?.babel).not.toBe( - swcNextPlugin.parsers?.['swc-next'], - ); - expect(swcNextPlugin.parsers?.typescript).toBe( - swcNextPlugin.parsers?.['swc-next-ts'], - ); - +test.each([ + ['js', 'swc'], + ['jsx', 'swc'], + ['ts', 'swc-ts'], + ['tsx', 'swc-tsx'], +])('infers the official parser for .%s files', async (extension, parser) => { await expect( - Promise.all( - ['js', 'jsx', 'ts', 'tsx'].map(async (extension) => - getFileInfo(`example.${extension}`, { plugins: [swcNextPlugin] }), - ), - ), - ).resolves.toEqual([ - { ignored: false, inferredParser: 'babel' }, - { ignored: false, inferredParser: 'babel' }, - { ignored: false, inferredParser: 'typescript' }, - { ignored: false, inferredParser: 'typescript' }, - ]); -}); - -test('matches the native Babel AST root shape', async () => { - const parser = swcNextPlugin.parsers?.babel; - if (!parser) { - throw new Error('The Babel-compatible SWC Next parser is not registered.'); - } - - const ast = (await parser.parse('// comment\nconst value = 1', { - filepath: 'example.js', - } as ParserOptions)) as Record; - const program = ast.program as Record; - - expect(ast.type).toBe('File'); - expect(ast.comments).toHaveLength(1); - expect(program.type).toBe('Program'); - expect(program.comments).toBeUndefined(); + getFileInfo(`example.${extension}`, { plugins: [swcNextPlugin] }), + ).resolves.toEqual({ ignored: false, inferredParser: parser }); }); test.each(['babel', 'typescript'] as const)( @@ -72,6 +39,99 @@ test.each(['babel', 'typescript'] as const)( }, ); +test('keeps SWC enabled for plugins that do not override JavaScript parsers', async () => { + await expect( + getPrettierPlugins( + { plugins: [await import('heading-case')] }, + 'example.js', + ), + ).resolves.toContain(swcNextPlugin); +}); + +test.each([ + ['js', 'swc'], + ['javascript', 'swc'], + ['node', 'swc'], + ['jsx', 'swc'], + ['ts', 'swc-ts'], + ['typescript', 'swc-ts'], + ['tsx', 'swc-tsx'], + ['typescriptreact', 'swc-tsx'], +])('formats %s Markdown fences with %s', async (language, parser) => { + const parse = rs.spyOn(swcNextPlugin.parsers![parser], 'parse'); + try { + for (const extension of ['md', 'mdx']) { + const source = `# api usage\n\n\`\`\`${language}\nconst value={answer:42}\n\`\`\`\n`; + const request = { + path: `example.${extension}`, + options: { plugins: [await import('heading-case')] }, + }; + const result = await formatFmtSource(request, () => source); + expect(result).toMatchObject({ + formatted: `# api usage\n\n\`\`\`${language}\nconst value = { answer: 42 };\n\`\`\`\n`, + }); + expect(parse).toHaveBeenCalled(); + parse.mockClear(); + } + } finally { + parse.mockRestore(); + } +}); + +test('preserves Markdown host behavior and formats nested fences', async () => { + const source = [ + 'import {a} from "a"', + '', + 'export const value={answer:42}', + '', + '', + '', + '> ```tsx', + '> const view=', + '> ```', + '', + '```js', + 'const = invalid', + '```', + '', + '```css', + 'a{color:red}', + '```', + ].join('\n'); + const request = { path: 'example.mdx', options: {} }; + const result = await formatFmtSource(request, () => source); + const formatted = await format(source, { parser: 'mdx' }); + expect(result).toMatchObject({ formatted }); + expect(await formatFmtSource(request, () => formatted)).toMatchObject({ + formatted, + }); +}); + +test('honors embeddedLanguageFormatting and project JS parsers in Markdown', async () => { + const source = '```js\nconst value={answer:42}\n```\n'; + await expect( + formatFmtSource( + { + path: 'example.md', + options: { embeddedLanguageFormatting: 'off' }, + }, + () => source, + ), + ).resolves.toMatchObject({ formatted: source }); + const parse = rs.spyOn(swcNextPlugin.parsers!.swc, 'parse'); + try { + const options = { plugins: [await import('prettier/plugins/babel')] }; + await expect( + formatFmtSource({ path: 'example.md', options }, () => source), + ).resolves.toMatchObject({ + formatted: '```js\nconst value = { answer: 42 };\n```\n', + }); + expect(parse).not.toHaveBeenCalled(); + } finally { + parse.mockRestore(); + } +}); + test('parses JSX in JavaScript files', async () => { await expect( formatWithSwcNext('const view=', { @@ -107,7 +167,7 @@ test.each(['example.d.ts', 'example.d.mts', 'example.d.cts'])( }, ); -describe("should match Prettier's postprocess behavior", () => { +describe('formatting compatibility', () => { test.each([ { name: 'hashbangs and unicode locations', @@ -165,7 +225,7 @@ describe("should match Prettier's postprocess behavior", () => { expected: 'const view = {item};\n', }, - ])('normalizes $name for the ESTree printer', async (fixture) => { + ])('formats $name', async (fixture) => { await expect( formatWithSwcNext(fixture.source, { filepath: fixture.filepath, @@ -187,166 +247,83 @@ describe("should match Prettier's postprocess behavior", () => { expect(await formatWithSwcNext(formatted, { parser })).toBe(formatted); }, ); - - test('matches the official hashbang AST shape', async () => { - const parser = swcNextPlugin.parsers?.['swc-next']; - if (!parser) { - throw new Error('The SWC Next parser is not registered.'); - } - - const options = { filepath: 'example.js' } as ParserOptions; - const astWithoutHashbang = (await parser.parse( - 'const value = 1', - options, - )) as Record; - const astWithHashbang = (await parser.parse( - '#!/usr/bin/env node\nconst value = 1', - options, - )) as Record; - - expect(Object.hasOwn(astWithoutHashbang, 'hashbang')).toBe(true); - expect(astWithoutHashbang.hashbang).toBeNull(); - expect(Object.hasOwn(astWithHashbang, 'hashbang')).toBe(false); - }); -}); - -test('reuses Prettier options and pragma handling', async () => { - await expect( - formatWithSwcNext('/** @format */\nconst value={answer:"yes"}', { - parser: 'swc-next', - requirePragma: true, - singleQuote: true, - }), - ).resolves.toBe("/** @format */\nconst value = { answer: 'yes' };\n"); - - await expect( - formatWithSwcNext('/** @noformat */\nconst value={answer:"yes"}', { - checkIgnorePragma: true, - parser: 'swc-next', - }), - ).resolves.toBe('/** @noformat */\nconst value={answer:"yes"}'); }); test.each([ - { - source: '/** @prettier */\nconst value=1', - hasPragma: true, - hasIgnorePragma: false, - }, - { - source: '/* @format */\nconst value=1', - hasPragma: true, - hasIgnorePragma: false, - }, - { - source: '#!/usr/bin/env node\r\n/** @format */\r\nconst value=1', - hasPragma: true, - hasIgnorePragma: false, - }, - { - source: '/**\n * @prettier\n * @noformat\n */\nconst value=1', - hasPragma: true, - hasIgnorePragma: true, - }, - { - source: '/** @prettier @noformat */\nconst value=1', - hasPragma: true, - hasIgnorePragma: false, - }, - { - source: '/** text @prettier */\nconst value=1', - hasPragma: false, - hasIgnorePragma: false, - }, - { - source: '// before\n/** @prettier */\nconst value=1', - hasPragma: false, - hasIgnorePragma: false, - }, + { requirePragma: true }, + { insertPragma: true }, + { checkIgnorePragma: true }, + { rangeStart: 20 }, + { rangeEnd: 20 }, + { objectWrap: 'collapse' as const }, + { experimentalTernaries: true }, + { experimentalOperatorPosition: 'start' as const }, ])( - 'matches Prettier pragma detection for $source', - ({ source, hasPragma, hasIgnorePragma }) => { - const parser = swcNextPlugin.parsers?.['swc-next']; - if (!parser?.hasPragma || !parser.hasIgnorePragma) { - throw new Error('The SWC Next parser does not expose pragma handlers.'); - } - - expect(parser.hasPragma(source)).toBe(hasPragma); - expect(parser.hasIgnorePragma(source)).toBe(hasIgnorePragma); + 'rejects unsupported SWC options instead of changing parsers: %j', + async (options) => { + await expect( + formatFmtSource({ path: 'example.js', options }, () => ''), + ).rejects.toThrow('SWCFMT'); }, ); -test('matches Prettier JavaScript location overrides', () => { - const parser = swcNextPlugin.parsers?.['swc-next']; - if (!parser) { - throw new Error('The SWC Next parser is not registered.'); - } - - expect( - parser.locStart({ - type: 'ClassDeclaration', - range: [10, 80], - decorators: [{ type: 'Decorator', range: [2, 9] }], - }), - ).toBe(2); +test.each([ + '// a ` marker\nconst value={answer:42}', + 'const value=`answer: ${42}`', + 'const query = /* GraphQL */ `query{user{id name}}`', +])('uses SWCFMT for templates and comments: %s', async (source) => { + const result = await formatFmtSource( + { path: 'example.js', options: {} }, + () => source, + ); + expect(result).toEqual({ + status: 'formatted', + source, + formatted: await formatWithSwcNext(source, { parser: 'swc-next' }), + }); +}); - expect( - parser.locStart({ - type: 'ExportNamedDeclaration', - range: [10, 80], - declaration: { decorators: [{ type: 'Decorator', range: [2, 9] }] }, - }), - ).toBe(2); +test('leaves embedded template contents unchanged unless Prettier is explicitly selected', async () => { + const source = 'const query = /* GraphQL */ `query{user{id name}}`'; + const result = await formatFmtSource( + { path: 'example.js', options: {} }, + () => source, + ); + expect(result).toMatchObject({ formatted: `${source};\n` }); + const explicit = await formatFmtSource( + { path: 'example.js', options: { parser: 'babel' } }, + () => source, + ); + expect(explicit).toMatchObject({ + formatted: await format(source, { parser: 'babel' }), + }); + expect(explicit).not.toEqual(result); +}); - const endCases = [ - { - expected: 44, - node: { - type: 'IfStatement', - range: [0, 50], - consequent: { type: 'BlockStatement', range: [3, 20] }, - alternate: { type: 'BlockStatement', range: [21, 44] }, - }, - }, - { - expected: 45, - node: { - type: 'ForStatement', - range: [0, 50], - body: { type: 'BlockStatement', range: [20, 45] }, - }, - }, - { expected: 15, node: { type: 'BreakStatement', range: [10, 50] } }, - { - expected: 21, - node: { - type: 'BreakStatement', - range: [10, 50], - label: { type: 'Identifier', range: [16, 21] }, - }, - }, - { expected: 18, node: { type: 'ContinueStatement', range: [10, 50] } }, - { expected: 18, node: { type: 'DebuggerStatement', range: [10, 50] } }, +test('honors a project parser plugin and its embedded-language support', async () => { + const source = 'const query = /* GraphQL */ `query{user{id name}}`'; + const result = await formatFmtSource( { - expected: 22, - node: { - type: 'VariableDeclaration', - range: [0, 30], - declarations: [ - { type: 'VariableDeclarator', range: [4, 10] }, - { type: 'VariableDeclarator', range: [12, 22] }, - ], + path: 'example.js', + options: { + plugins: [await import('prettier/plugins/babel')], + rangeEnd: 1000, }, }, - { - expected: 10, - node: { type: 'ExpressionStatement', range: [0, 12], __contentEnd: 10 }, - }, - ]; + () => source, + ); + expect(result).toMatchObject({ + formatted: await format(source, { parser: 'babel' }), + }); +}); - for (const { node, expected } of endCases) { - expect(parser.locEnd(node)).toBe(expected); - } +test('reports unsupported import-source syntax instead of retrying another parser', async () => { + await expect( + formatFmtSource( + { path: 'example.js', options: {} }, + () => 'import source mod from "./module.wasm";', + ), + ).rejects.toThrow('formatting import phase'); }); test('supports CommonJS source semantics for .cjs files', async () => { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 72962655..31027259 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -210,7 +210,7 @@ catalogs: '@rstest/core': specifier: ~0.12.6 version: 0.12.6 - '@swc-next/parser': + '@swc-next/formatter-prettier-plugin': specifier: 0.7.0 version: 0.7.0 '@testing-library/dom': @@ -534,9 +534,9 @@ importers: '@rstest/core': specifier: 'catalog:' version: 0.12.6(happy-dom@20.14.5) - '@swc-next/parser': + '@swc-next/formatter-prettier-plugin': specifier: 'catalog:' - version: 0.7.0 + version: 0.7.0(prettier@3.10.1) prettier: specifier: 'catalog:' version: 3.10.1 @@ -1731,89 +1731,91 @@ packages: peerDependencies: acorn: ^8.9.0 - '@swc-next/parser-binding-darwin-arm64@0.7.0': - resolution: {integrity: sha512-JfycoXuNEFgmXU5oBfYVC+wjIL9EGJadXyw01VW7T8iYhv0a/aPdAwfqIAWzvPFPBWAmmKKF/0CzlCLKhHabjQ==} + '@swc-next/formatter-js-binding-darwin-arm64@0.7.0': + resolution: {integrity: sha512-k2c8QSVqdDqk8lWjl1yagbxl5cqHqI5UjeQGFZfoDZzPC/9I6vKjQ0A0DeYXuBEayIsVJMF27lrmmUf4hyy5pQ==} cpu: [arm64] os: [darwin] - '@swc-next/parser-binding-darwin-x64@0.7.0': - resolution: {integrity: sha512-xIK0tfTG0YV2GkYGRbCd7M8FomfxnG9kJ8P768qTcjZg8qYqM4OqxPPDkKiK2uR7Tc0D6DGd9E/vrpqCdTGyCA==} + '@swc-next/formatter-js-binding-darwin-x64@0.7.0': + resolution: {integrity: sha512-EhoIK2qhCaL0LuQ23gvBwD7buqVbUqC6UQvOKyWFQZaKz9fGGYcXekAj5QqI+fvKin58dRwpiRtWf6g8tFC4hQ==} cpu: [x64] os: [darwin] - '@swc-next/parser-binding-linux-arm64-gnu@0.7.0': - resolution: {integrity: sha512-OW9w4PQjdBLjVWCRlBeswLINu5Sf+5c1A8SCru9jKW9VTHoq++9orof7lWGAUlqcZS1PVhaALGSzu6QceexcFg==} + '@swc-next/formatter-js-binding-linux-arm64-gnu@0.7.0': + resolution: {integrity: sha512-JjWi+kWNT0SqNM7ORf+tYh4ooRavOtuCjUqclZOSoVQf9ya6Aqm8I1myosHwBvdkfI0KUJRNe608BVYHXviIHA==} cpu: [arm64] os: [linux] libc: [glibc] - '@swc-next/parser-binding-linux-arm64-musl@0.7.0': - resolution: {integrity: sha512-LiOlOdJRupb1LSurX2ACnCMXsp817p4Jpo3P1aUnL/BccTM3M8jPgNSapy8vEwyOExNYpOeHm8tJeWmhdN63KA==} + '@swc-next/formatter-js-binding-linux-arm64-musl@0.7.0': + resolution: {integrity: sha512-CbsJzoWAQ9m4gbqeLq7Rv2izvCOXiETFxipf3cPp2kQIKoiHcf4oE2z+FdeVETBD/ak0pK+6eo2VjbSNPBk11Q==} cpu: [arm64] os: [linux] libc: [musl] - '@swc-next/parser-binding-linux-ppc64-gnu@0.7.0': - resolution: {integrity: sha512-wUBwFcPZhiUnh/1/341Y94erFrWu6uJOcWx79IszSMfi3w+P7PumpJufcm8gDy6uzbrPgsGHnTmr5AF2QcLfmQ==} + '@swc-next/formatter-js-binding-linux-ppc64-gnu@0.7.0': + resolution: {integrity: sha512-2CrDz0rKdEbp60xBUgMVZwVSmzkrBZfCW3IOr0gNyQJAg9gHrT+8QbI2Qy2gmaH+IW4gI8RgcM7A/vLssuPfFQ==} cpu: [ppc64] os: [linux] libc: [glibc] - '@swc-next/parser-binding-linux-riscv64-gnu@0.7.0': - resolution: {integrity: sha512-wGBlnDeimrU4o4d+lMPAi4Qoa/EltyXPJr7G4DP9hDUKJj6a4lMx/IFYy93MTlAwRobJjSgx1qYpNfxRDssxfw==} + '@swc-next/formatter-js-binding-linux-riscv64-gnu@0.7.0': + resolution: {integrity: sha512-JsLZgLspqD+xPpdmTPHWRegfVji321dbaotc2+uam1+5kJfm/gliMbVY7gBPsawXMEyIX5pgcP8l7Pa7/oRnFg==} cpu: [riscv64] os: [linux] libc: [glibc] - '@swc-next/parser-binding-linux-riscv64-musl@0.7.0': - resolution: {integrity: sha512-ebz+9KvGm2fyit+oRQ0ckNPa7UitIExfQw7FgFGTEsYIjyFSFSAat7WDd8QcH5YUXhSl0kOdCvx/Hw3eq0GnHA==} + '@swc-next/formatter-js-binding-linux-riscv64-musl@0.7.0': + resolution: {integrity: sha512-MxkKb9wf44+tN3TOXDw5pJ/frdBFtQk5KAC6DTzdEjx+eDsnQ5eVh1Z6XNZxB+LZwFzMBMKXmCkEZeaFCfMtcA==} cpu: [riscv64] os: [linux] libc: [musl] - '@swc-next/parser-binding-linux-s390x-gnu@0.7.0': - resolution: {integrity: sha512-bhWFopzo7OY9Cxa0nz6a5RZD+rbmwRDCxfVUPzVWytDb9i7EPQrVPlIXaBSYJac0geY2dWqcEbG47Fop+R3iYA==} + '@swc-next/formatter-js-binding-linux-s390x-gnu@0.7.0': + resolution: {integrity: sha512-h48emgvc6+JYcwVrgcK1lfKXrT/zykS+4FbYt75tPaiznDEwucSarkGrg0pxpBr4FenL4S9fjPz8+H1XnIYRBw==} cpu: [s390x] os: [linux] libc: [glibc] - '@swc-next/parser-binding-linux-x64-gnu@0.7.0': - resolution: {integrity: sha512-qdT9jCf+SDfn9Ugw0gJJScXalv7oJHgLJKqqe+wu+kCDEgyUEqMI29cYJWYKxkYKMAx9yNb/yOUy9ZjIZX4NnA==} + '@swc-next/formatter-js-binding-linux-x64-gnu@0.7.0': + resolution: {integrity: sha512-AvNJrw/1161u8bW9yQR04ouDlzp41JGmXkpX/lVinG0U6KoPR0jb90qaVLkgC6zEauWIzYiobfNtiaGihXCgdQ==} cpu: [x64] os: [linux] libc: [glibc] - '@swc-next/parser-binding-linux-x64-musl@0.7.0': - resolution: {integrity: sha512-qwJJDsyY+78Dayxy3FwsjByu0KwGVyV7OwsIAGyDJgBJx9w6iBm8f+bLzzhXGewm7bpy9AzXZ1iJsdqfjzoSOg==} + '@swc-next/formatter-js-binding-linux-x64-musl@0.7.0': + resolution: {integrity: sha512-k7tGTq2Ry+3Bba0vz82oyjWn2wsZRNeNQzsqnuP7I0W2/mmruQRltpiy+KrSzDFkiFeCnx/zYxWA/u2BHyczIw==} cpu: [x64] os: [linux] libc: [musl] - '@swc-next/parser-binding-win32-arm64-msvc@0.7.0': - resolution: {integrity: sha512-OXc5L/b+tpnaMh8Emh1VSjw25Gx94eJQeWcINTxUSVl5pUwVlAhMyyP17ciqSROpv4zTiyvWYsOce9+kBpvSwQ==} + '@swc-next/formatter-js-binding-win32-arm64-msvc@0.7.0': + resolution: {integrity: sha512-PRiOQZirHK1pBYZnsWeeMpNrf9noqgPeghhrsZ/0jVawEYSNaLjge2z7OXh/Zu0ku/WMNmZ/YPx9RDxBPovTrg==} cpu: [arm64] os: [win32] - '@swc-next/parser-binding-win32-ia32-msvc@0.7.0': - resolution: {integrity: sha512-9PLpgidEgLla3ZemTihm/hB0AxpkAtvF7opmIcHxUR81cJwq5XBNd97WKD+/g4Hwogw+nPxGh5M3wUfux7oRkQ==} + '@swc-next/formatter-js-binding-win32-ia32-msvc@0.7.0': + resolution: {integrity: sha512-QIjfL+QN8eGt8r3FiIiK0V5EiAQ7mEB19gg4wd1FiEjwTPTRKixG1uftZsTKrWHyve8U2NaL6p6+JKelrdbqxQ==} cpu: [ia32] os: [win32] - '@swc-next/parser-binding-win32-x64-msvc@0.7.0': - resolution: {integrity: sha512-g4nEBoTjkRFR/in+fUx7So/YPAN5HjH5C6VeXet68+rtnBcreuF+eynncxVJtPqIWDSHw5d/NI11PJn4vUaUXA==} + '@swc-next/formatter-js-binding-win32-x64-msvc@0.7.0': + resolution: {integrity: sha512-98C1FQY82YUNzsWPuZprZ5gpb8MrHEr7dK8dPO1adcFaJCy8dF9OXk6rHK4yWanQKLepguPpCgNBoMn4T358ow==} cpu: [x64] os: [win32] - '@swc-next/parser@0.7.0': - resolution: {integrity: sha512-nQuKQi+zg4EieOK4flkBNxTpJ3Y5ohnelhf/aCNhMFlvs0yUDS78RwuDFKALOHOTZhO3AiDKxU20bZ3nAz3NBQ==} + '@swc-next/formatter-js@0.7.0': + resolution: {integrity: sha512-QNLhRyYaTkFK/PaU3dmUd0I2cKZxDVHgRV6lX3CfjyGSErowr2gEQhD/MGBjZbW0mm+XSUhHmwVIMA+mJQ3nEg==} peerDependencies: - '@swc-next/parser-binding-wasm': 0.7.0 + '@swc-next/formatter-js-binding-wasm': 0.7.0 peerDependenciesMeta: - '@swc-next/parser-binding-wasm': + '@swc-next/formatter-js-binding-wasm': optional: true - '@swc-next/types@0.7.0': - resolution: {integrity: sha512-1PJpYfi0ST0b0+iZu/+YGbQu+aPNi2LHIdFSDtMn8Oh7gJV1dN2eRFHDYbSMKKKyb4k3a6EbYu5XuQefRBGL6g==} + '@swc-next/formatter-prettier-plugin@0.7.0': + resolution: {integrity: sha512-r+8JPt1Il+gCG8Tof53k3ajm//8y/4gOLJEHudUg8ZPQVTgJkiVcOklzVbBQTkLOMnF4XNNHW1KRzzsUpJe5EQ==} + peerDependencies: + prettier: 3.9.9 '@swc/helpers@0.5.24': resolution: {integrity: sha512-6tcXo4kA8HgGO7AVmawB57RYi/piBPYVHVcO6dXjX+SZw8GoHmi262sp4v2Ha2kNP9Cx84qei27yT+fjS1lxgg==} @@ -4508,64 +4510,67 @@ snapshots: dependencies: acorn: 8.19.0 - '@swc-next/parser-binding-darwin-arm64@0.7.0': + '@swc-next/formatter-js-binding-darwin-arm64@0.7.0': optional: true - '@swc-next/parser-binding-darwin-x64@0.7.0': + '@swc-next/formatter-js-binding-darwin-x64@0.7.0': optional: true - '@swc-next/parser-binding-linux-arm64-gnu@0.7.0': + '@swc-next/formatter-js-binding-linux-arm64-gnu@0.7.0': optional: true - '@swc-next/parser-binding-linux-arm64-musl@0.7.0': + '@swc-next/formatter-js-binding-linux-arm64-musl@0.7.0': optional: true - '@swc-next/parser-binding-linux-ppc64-gnu@0.7.0': + '@swc-next/formatter-js-binding-linux-ppc64-gnu@0.7.0': optional: true - '@swc-next/parser-binding-linux-riscv64-gnu@0.7.0': + '@swc-next/formatter-js-binding-linux-riscv64-gnu@0.7.0': optional: true - '@swc-next/parser-binding-linux-riscv64-musl@0.7.0': + '@swc-next/formatter-js-binding-linux-riscv64-musl@0.7.0': optional: true - '@swc-next/parser-binding-linux-s390x-gnu@0.7.0': + '@swc-next/formatter-js-binding-linux-s390x-gnu@0.7.0': optional: true - '@swc-next/parser-binding-linux-x64-gnu@0.7.0': + '@swc-next/formatter-js-binding-linux-x64-gnu@0.7.0': optional: true - '@swc-next/parser-binding-linux-x64-musl@0.7.0': + '@swc-next/formatter-js-binding-linux-x64-musl@0.7.0': optional: true - '@swc-next/parser-binding-win32-arm64-msvc@0.7.0': + '@swc-next/formatter-js-binding-win32-arm64-msvc@0.7.0': optional: true - '@swc-next/parser-binding-win32-ia32-msvc@0.7.0': + '@swc-next/formatter-js-binding-win32-ia32-msvc@0.7.0': optional: true - '@swc-next/parser-binding-win32-x64-msvc@0.7.0': + '@swc-next/formatter-js-binding-win32-x64-msvc@0.7.0': optional: true - '@swc-next/parser@0.7.0': - dependencies: - '@swc-next/types': 0.7.0 + '@swc-next/formatter-js@0.7.0': optionalDependencies: - '@swc-next/parser-binding-darwin-arm64': 0.7.0 - '@swc-next/parser-binding-darwin-x64': 0.7.0 - '@swc-next/parser-binding-linux-arm64-gnu': 0.7.0 - '@swc-next/parser-binding-linux-arm64-musl': 0.7.0 - '@swc-next/parser-binding-linux-ppc64-gnu': 0.7.0 - '@swc-next/parser-binding-linux-riscv64-gnu': 0.7.0 - '@swc-next/parser-binding-linux-riscv64-musl': 0.7.0 - '@swc-next/parser-binding-linux-s390x-gnu': 0.7.0 - '@swc-next/parser-binding-linux-x64-gnu': 0.7.0 - '@swc-next/parser-binding-linux-x64-musl': 0.7.0 - '@swc-next/parser-binding-win32-arm64-msvc': 0.7.0 - '@swc-next/parser-binding-win32-ia32-msvc': 0.7.0 - '@swc-next/parser-binding-win32-x64-msvc': 0.7.0 - - '@swc-next/types@0.7.0': {} + '@swc-next/formatter-js-binding-darwin-arm64': 0.7.0 + '@swc-next/formatter-js-binding-darwin-x64': 0.7.0 + '@swc-next/formatter-js-binding-linux-arm64-gnu': 0.7.0 + '@swc-next/formatter-js-binding-linux-arm64-musl': 0.7.0 + '@swc-next/formatter-js-binding-linux-ppc64-gnu': 0.7.0 + '@swc-next/formatter-js-binding-linux-riscv64-gnu': 0.7.0 + '@swc-next/formatter-js-binding-linux-riscv64-musl': 0.7.0 + '@swc-next/formatter-js-binding-linux-s390x-gnu': 0.7.0 + '@swc-next/formatter-js-binding-linux-x64-gnu': 0.7.0 + '@swc-next/formatter-js-binding-linux-x64-musl': 0.7.0 + '@swc-next/formatter-js-binding-win32-arm64-msvc': 0.7.0 + '@swc-next/formatter-js-binding-win32-ia32-msvc': 0.7.0 + '@swc-next/formatter-js-binding-win32-x64-msvc': 0.7.0 + + '@swc-next/formatter-prettier-plugin@0.7.0(prettier@3.10.1)': + dependencies: + '@swc-next/formatter-js': 0.7.0 + prettier: 3.10.1 + transitivePeerDependencies: + - '@swc-next/formatter-js-binding-wasm' '@swc/helpers@0.5.24': {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index de78925b..06732fc6 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -29,7 +29,7 @@ catalog: '@rstest/adapter-rsbuild': '~0.12.6' '@rstest/adapter-rslib': '~0.12.6' '@rstest/core': '~0.12.6' - '@swc-next/parser': '0.7.0' + '@swc-next/formatter-prettier-plugin': '0.7.0' '@testing-library/dom': '^10.4.2' '@testing-library/jest-dom': '^7.0.1' '@testing-library/react': '^16.3.3' @@ -68,6 +68,11 @@ dedupePeers: true autoInstallPeers: false +peerDependencyRules: + allowedVersions: + # Upstream publishes its pinned test version; 3.10.1 is verified locally. + '@swc-next/formatter-prettier-plugin@0.7.0>prettier': '3.10.1' + engineStrict: true hoistPattern: [] diff --git a/scripts/dictionary.txt b/scripts/dictionary.txt index 0ccff542..9102a232 100644 --- a/scripts/dictionary.txt +++ b/scripts/dictionary.txt @@ -36,6 +36,7 @@ rstest shiki shikijs solidjs +SWCFMT Trae turborepo typicode diff --git a/website/docs/en/guide/formatting.mdx b/website/docs/en/guide/formatting.mdx index 9550ea33..efe6fe05 100644 --- a/website/docs/en/guide/formatting.mdx +++ b/website/docs/en/guide/formatting.mdx @@ -9,11 +9,13 @@ import { PackageManagerTabs } from '@rspress/core/theme'; Rstack CLI includes a formatter built on [Prettier](https://prettier.io/). Compared with running Prettier directly, `rs fmt` offers better performance in three ways: - **Parallel formatting**: Files are formatted concurrently in a worker pool. -- **SWC Next parser**: The high-performance [SWC Next](https://www.npmjs.com/package/@swc-next/parser) parser is used by default for JavaScript, JSX, and TypeScript files. +- **SWC Next formatter**: The official [SWC Next Prettier plugin](https://www.npmjs.com/package/@swc-next/formatter-prettier-plugin) is used by default for JavaScript, JSX, TypeScript, and TSX files. - **Persistent cache**: Content-based results let later runs skip formatting unchanged files. `rs fmt` supports Prettier options and plugins and adds built-in capabilities such as [sorting package.json fields](#sort-package-json). +The SWC Next formatter is experimental, and its output can differ from Prettier. JavaScript, JSX, TypeScript, and TSX code fences in Markdown and MDX also use SWC Next. Prettier still handles the surrounding document and MDX import/export and JSX nodes. HTML, CSS, GraphQL, and other embedded languages inside JavaScript templates are not formatted, even when `embeddedLanguageFormatting` is enabled. Range formatting (any finite `rangeEnd`), pragma, and unsupported layout options produce an explicit error for SWC-formatted files. Project plugins that override JavaScript or TypeScript parsers retain precedence; other host languages, including Vue and Svelte scripts, continue using their Prettier formatters. Set `parser: 'babel'` or `parser: 'typescript'` in `define.fmt()` or an override to explicitly use Prettier and its embedded-language support. + ## Basic usage Run `rs fmt` without file arguments to format files in the current directory and save the changes: diff --git a/website/docs/zh/guide/formatting.mdx b/website/docs/zh/guide/formatting.mdx index e6455f61..0e58cd8a 100644 --- a/website/docs/zh/guide/formatting.mdx +++ b/website/docs/zh/guide/formatting.mdx @@ -9,11 +9,13 @@ import { PackageManagerTabs } from '@rspress/core/theme'; Rstack CLI 提供了基于 [Prettier](https://prettier.io/) 的格式化工具。相比直接使用 Prettier,`rs fmt` 的性能更好,主要得益于以下三点: - **并行格式化**:通过 worker 池并行格式化文件。 -- **SWC Next 解析器**:默认使用高性能的 [SWC Next](https://www.npmjs.com/package/@swc-next/parser) 解析器处理 JavaScript、JSX 和 TypeScript 文件。 +- **SWC Next 格式化器**:默认使用官方 [SWC Next Prettier 插件](https://www.npmjs.com/package/@swc-next/formatter-prettier-plugin) 处理 JavaScript、JSX、TypeScript 和 TSX 文件。 - **持久化缓存**:基于文件内容缓存结果,后续运行可以跳过未变化文件的格式化。 `rs fmt` 兼容 Prettier 的选项和插件,并提供更多内置能力,例如支持[排序 package.json 字段](#sort-package-json)。 +SWC Next 格式化器仍处于实验阶段,输出可能与 Prettier 不同。Markdown 和 MDX 中的 JavaScript、JSX、TypeScript 和 TSX 代码块也使用 SWC Next;外围文档以及 MDX 的 import/export 和 JSX 节点仍由 Prettier 处理。JavaScript 模板内的 HTML、CSS、GraphQL 等嵌入语言暂不格式化,即使开启了 `embeddedLanguageFormatting`。对使用 SWC 格式化的文件,范围格式化(包括任何有限值的 `rangeEnd`)、pragma 和尚不支持的布局选项会明确报错。覆盖 JavaScript 或 TypeScript 解析器的项目插件仍保留优先级;其他宿主语言(包括 Vue 和 Svelte 中的脚本)继续使用对应的 Prettier 格式化器。在 `define.fmt()` 或 override 中设置 `parser: 'babel'` 或 `parser: 'typescript'`,可显式使用 Prettier 及其嵌入语言支持。 + ## 基本用法 \{#basic-usage} 直接运行 `rs fmt`,即可格式化当前目录中的文件并保存修改: