Skip to content

Base64 and cursorOffset can break prettier #369

Open
@hyrious

Description

@hyrious

Related: #301 #60

TLDR: The plugin converts script contents into base64 and restore it later. This approach can break prettier when enabled cursorOffset because prettier will then try to restore the cursor position with the diff package, which breaks in such large input (each base64 character is considered a single word).

Here's the minimal reproduction:

# initialize
mkdir test && cd test
npm init -y && npm i prettier prettier-plugin-svelte

# get a reasonably sized (11KB) svlete file
curl -O https://raw.githubusercontent.com/sveltejs/vite-plugin-svelte/main/packages/vite-plugin-svelte-inspector/src/runtime/Inspector.svelte

touch a.mjs # see below
// a.mjs
import fs from "fs";
import prettier from "prettier";

const contents = fs.readFileSync("Inspector.svelte", "utf8");

console.time("format");
const result = prettier.formatWithCursor(contents, {
  ...config,
  parser: 'svelte',
  // cursorOffset: 0,
});

console.timeEnd("format");
console.log(result.formatted.length);

Run node a.mjs, it finishes in 300ms in my machine.

Now, try uncomment // cursorOffset: 0,, this process will hang forever.

Instructions about profile a node process and get flamegraph

Before continuing, update the script above to wait some seconds before it goes to hang, so that we could inspect into this process later.

Run node --inspect a.mjs, then open chrome://inspect to run profile on it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions