volar-service-prettier 0.0.31-patch.1 → 0.0.31-patch.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.d.ts +14 -37
  2. package/index.js +49 -58
  3. package/package.json +1 -1
package/index.d.ts CHANGED
@@ -1,13 +1,10 @@
1
- import type { ServicePlugin, ServiceEnvironment } from '@volar/language-service';
2
- import type { Options, ResolveConfigOptions } from 'prettier';
3
- export declare function create(options?: {
4
- /**
5
- * Languages to be formatted by prettier.
6
- *
7
- * @default
8
- * ['html', 'css', 'scss', 'typescript', 'javascript']
9
- */
10
- languages?: string[];
1
+ import type { DocumentSelector, FormattingOptions, Result, ServiceContext, ServicePlugin, TextDocument } from '@volar/language-service';
2
+ import type { Options } from 'prettier';
3
+ export declare function create(
4
+ /**
5
+ * Prettier instance or getter to use.
6
+ */
7
+ prettierInstanceOrGetter: typeof import('prettier') | ((context: ServiceContext) => typeof import('prettier') | undefined), { html, documentSelector, isFormattingEnabled, getFormattingOptions, }?: {
11
8
  html?: {
12
9
  /**
13
10
  * Preprocessing to break "contents" from "HTML tags".
@@ -17,33 +14,13 @@ export declare function create(options?: {
17
14
  breakContentsFromTags?: boolean;
18
15
  };
19
16
  /**
20
- * Do not use settings from VSCode's `editor.tabSize` and temporary tabSize on status bar
17
+ * Languages to be formatted by prettier.
21
18
  *
22
- * @see https://github.com/volarjs/services/issues/5
23
- */
24
- ignoreIdeOptions?: boolean;
25
- /**
26
- * Determine if IDE options should be used as a fallback if there's no Prettier specific settings in the workspace
27
- */
28
- useIdeOptionsFallback?: boolean;
29
- /**
30
- * Additional options to pass to Prettier
31
- * This is useful, for instance, to add specific plugins you need.
32
- */
33
- additionalOptions?: (resolvedConfig: Options) => Options | Promise<Options>;
34
- /**
35
- * Options to use when resolving the Prettier config
36
- */
37
- resolveConfigOptions?: ResolveConfigOptions;
38
- /**
39
- * Prettier instance to use. If undefined, Prettier will be imported through a normal `import('prettier')`.
40
- * This property is useful whenever you want to load a specific instance of Prettier (for instance, loading the Prettier version installed in the user's project)
41
- */
42
- prettier?: typeof import('prettier') | undefined;
43
- getPrettier?: (serviceEnv: ServiceEnvironment) => typeof import('prettier') | undefined;
44
- /**
45
- * If true, the plugin will not throw an error if it can't load Prettier either through the `prettier`, or `getPrettier` properties or through a normal `import('prettier')`.
19
+ * @default
20
+ * ['html', 'css', 'scss', 'typescript', 'javascript']
46
21
  */
47
- allowImportError?: boolean;
48
- }, getPrettierConfig?: (filePath: string, prettier: typeof import('prettier'), config?: ResolveConfigOptions) => Promise<Options>): ServicePlugin;
22
+ documentSelector?: DocumentSelector;
23
+ isFormattingEnabled?(prettier: typeof import('prettier'), document: TextDocument, context: ServiceContext): Result<boolean>;
24
+ getFormattingOptions?(prettier: typeof import('prettier'), document: TextDocument, formatOptions: FormattingOptions, context: ServiceContext): Result<Options>;
25
+ }): ServicePlugin;
49
26
  //# sourceMappingURL=index.d.ts.map
package/index.js CHANGED
@@ -2,77 +2,65 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.create = void 0;
4
4
  const vscode_uri_1 = require("vscode-uri");
5
- function create(options = {}, getPrettierConfig = async (filePath, prettier, config) => {
6
- return await prettier.resolveConfig(filePath, config) ?? {};
7
- }) {
5
+ function create(
6
+ /**
7
+ * Prettier instance or getter to use.
8
+ */
9
+ prettierInstanceOrGetter, { html, documentSelector = ['html', 'css', 'scss', 'typescript', 'javascript'], isFormattingEnabled = async (prettier, document) => {
10
+ const uri = vscode_uri_1.URI.parse(document.uri);
11
+ if (uri.scheme === 'file') {
12
+ try {
13
+ const fileInfo = await prettier.getFileInfo(uri.fsPath, { ignorePath: '.prettierignore', resolveConfig: false });
14
+ if (fileInfo.ignored) {
15
+ return false;
16
+ }
17
+ }
18
+ catch (err) {
19
+ console.warn(err);
20
+ }
21
+ }
22
+ return true;
23
+ }, getFormattingOptions = async (prettier, document, formatOptions, context) => {
24
+ const filepath = vscode_uri_1.URI.parse(document.uri).fsPath;
25
+ const configOptions = await prettier.resolveConfig(filepath);
26
+ const editorOptions = await context.env.getConfiguration?.('prettier', document.uri);
27
+ return {
28
+ filepath,
29
+ tabWidth: formatOptions.tabSize,
30
+ useTabs: !formatOptions.insertSpaces,
31
+ ...editorOptions,
32
+ ...configOptions,
33
+ };
34
+ }, } = {}) {
8
35
  return {
9
36
  name: 'prettier',
10
37
  create(context) {
11
- const languages = options.languages ?? ['html', 'css', 'scss', 'typescript', 'javascript'];
12
- let _prettier = options.prettier;
13
- try {
14
- if (!_prettier) {
15
- if (options.getPrettier) {
16
- _prettier = options.getPrettier(context.env);
17
- }
18
- else {
19
- _prettier = require('prettier');
20
- }
21
- }
22
- }
23
- catch (error) {
24
- if (!options.allowImportError) {
25
- throw new Error("Could not load Prettier: ");
26
- }
27
- ;
28
- }
29
- if (!_prettier) {
38
+ const prettier = typeof prettierInstanceOrGetter === 'function'
39
+ ? prettierInstanceOrGetter(context)
40
+ : prettierInstanceOrGetter;
41
+ if (!prettier) {
30
42
  return {};
31
43
  }
32
- const prettier = _prettier;
33
44
  return {
34
45
  async provideDocumentFormattingEdits(document, _, formatOptions) {
35
- if (!languages.includes(document.languageId)) {
46
+ if (!matchDocument(documentSelector, document)) {
36
47
  return;
37
48
  }
38
- const filePath = vscode_uri_1.URI.parse(document.uri).fsPath;
39
- const fileInfo = await prettier.getFileInfo(filePath, { ignorePath: '.prettierignore', resolveConfig: false });
40
- if (fileInfo.ignored) {
49
+ if (!isFormattingEnabled(prettier, document, context)) {
41
50
  return;
42
51
  }
43
- const filePrettierOptions = await getPrettierConfig(filePath, prettier, options.resolveConfigOptions);
44
- const editorPrettierOptions = await context.env.getConfiguration?.('prettier', document.uri);
45
- const ideFormattingOptions = formatOptions !== undefined && options.useIdeOptionsFallback // We need to check for options existing here because some editors might not have it
46
- ? {
47
- tabWidth: formatOptions.tabSize,
48
- useTabs: !formatOptions.insertSpaces,
49
- }
50
- : {};
51
- // Return a config with the following cascade:
52
- // - Prettier config file should always win if it exists, if it doesn't:
53
- // - Prettier config from the VS Code extension is used, if it doesn't exist:
54
- // - Use the editor's basic configuration settings
55
- const prettierOptions = returnObjectIfHasKeys(filePrettierOptions) || returnObjectIfHasKeys(editorPrettierOptions) || ideFormattingOptions;
56
- const currentPrettierConfig = {
57
- ...(options.additionalOptions
58
- ? await options.additionalOptions(prettierOptions)
59
- : prettierOptions),
60
- filepath: filePath,
61
- };
62
- if (!options.ignoreIdeOptions) {
63
- currentPrettierConfig.useTabs = !formatOptions.insertSpaces;
64
- currentPrettierConfig.tabWidth = formatOptions.tabSize;
65
- }
66
52
  const fullText = document.getText();
67
53
  let oldText = fullText;
68
- const isHTML = document.languageId === "html";
69
- if (isHTML && options.html?.breakContentsFromTags) {
54
+ const isHTML = document.languageId === 'html';
55
+ if (isHTML && html?.breakContentsFromTags) {
70
56
  oldText = oldText
71
- .replace(/(<[a-z][^>]*>)([^ \n])/gi, "$1 $2")
72
- .replace(/([^ \n])(<\/[a-z][a-z0-9\t\n\r -]*>)/gi, "$1 $2");
57
+ .replace(/(<[a-z][^>]*>)([^ \n])/gi, '$1 $2')
58
+ .replace(/([^ \n])(<\/[a-z][a-z0-9\t\n\r -]*>)/gi, '$1 $2');
73
59
  }
60
+ const prettierOptions = await getFormattingOptions(prettier, document, formatOptions, context);
61
+ const newText = await prettier.format(oldText, prettierOptions);
74
62
  return [{
75
- newText: await prettier.format(oldText, currentPrettierConfig),
63
+ newText,
76
64
  range: {
77
65
  start: document.positionAt(0),
78
66
  end: document.positionAt(fullText.length),
@@ -84,9 +72,12 @@ function create(options = {}, getPrettierConfig = async (filePath, prettier, con
84
72
  };
85
73
  }
86
74
  exports.create = create;
87
- function returnObjectIfHasKeys(obj) {
88
- if (Object.keys(obj || {}).length > 0) {
89
- return obj;
75
+ function matchDocument(selector, document) {
76
+ for (const sel of selector) {
77
+ if (sel === document.languageId || (typeof sel === 'object' && sel.language === document.languageId)) {
78
+ return true;
79
+ }
90
80
  }
81
+ return false;
91
82
  }
92
83
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "volar-service-prettier",
3
- "version": "0.0.31-patch.1",
3
+ "version": "0.0.31-patch.2",
4
4
  "description": "Integrate Prettier into Volar",
5
5
  "homepage": "https://github.com/volarjs/services/tree/master/packages/prettier",
6
6
  "bugs": "https://github.com/volarjs/services/issues",