-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathutils.ts
More file actions
218 lines (195 loc) · 6.63 KB
/
Copy pathutils.ts
File metadata and controls
218 lines (195 loc) · 6.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import fs from "node:fs";
import path from "node:path";
import type {
TwoslashExecuteOptions,
TwoslashGenericFunction,
TwoslashInstance,
TwoslashOptions,
} from "@ec-ts/twoslash";
import { createTwoslasher } from "@ec-ts/twoslash";
import { createTwoslasher as createTwoslasherVue } from "@ec-ts/twoslash-vue";
import type { ExpressiveCodeBlock } from "@expressive-code/core";
import {
type CreateTwoslashESLintOptions,
createTwoslasher as createTwoslasherEslint,
} from "twoslash-eslint";
import ts from "typescript";
import type { PluginTwoslashOptions } from "../types.ts";
import { reTrigger, twoslashDefaultTags } from "./regex.ts";
/**
* Calculates the width of a given text in pixels based on the character location, font size, and character width.
*
* @param textLoc - The location of the text (number of characters).
* @param fontSize - The font size in pixels. Defaults to 16.
* @param charWidth - The width of a single character in pixels. Defaults to 8.
* @returns The width of the text in pixels.
*/
export function getTextWidthInPixels(textLoc: number, fontSize = 16, charWidth = 8): number {
return textLoc * charWidth * (fontSize / 16);
}
/**
* Merges custom tags from the provided `twoslashOptions` with the default tags.
* Ensures that there are no duplicate tags in the final list.
*
* @param twoslashOptions - The options object containing custom tags to be merged.
* @returns A new `TwoslashOptions` object with merged custom tags.
*/
export function checkForCustomTagsAndMerge(twoslashOptions: TwoslashOptions | undefined) {
const customTags = twoslashOptions?.customTags ?? [];
const defaultTags = twoslashDefaultTags;
const allTags: string[] = [...defaultTags];
for (const tag of customTags) {
if (!allTags.includes(tag)) {
allTags.push(tag);
}
}
return {
...twoslashOptions,
customTags: allTags,
} as TwoslashOptions;
}
/**
* Interface representing the data structure for a Twoslash instance, including its trigger pattern, supported languages, and the corresponding twoslasher functions.
*/
export interface TwoslashMapData {
trigger: RegExp;
languages: readonly string[];
twoslashers: (options: TwoslashOptions) => {
default: TwoslashGenericFunction<TwoslashExecuteOptions>;
[key: string]: TwoslashGenericFunction<TwoslashExecuteOptions>;
};
}
export const BuiltInTwoslashers = ["twoslash", "eslint"] as const;
export type BuiltInTwoslashers = (typeof BuiltInTwoslashers)[number];
/**
* A map that holds the configuration for built-in twoslash instances, including their trigger patterns, supported languages, and the corresponding twoslasher functions.
*/
export const TwoslashInstanceMap = new Map<BuiltInTwoslashers, TwoslashMapData>([
[
"twoslash",
{
trigger: reTrigger,
languages: ["ts", "tsx", "vue"],
twoslashers: (options: TwoslashOptions) => ({
default: createTwoslasher(options),
vue: createTwoslasherVue(options),
}),
},
],
[
"eslint",
{
trigger: /\beslint\b/,
languages: ["ts", "tsx"],
twoslashers: (options: TwoslashOptions) => ({
default: createTwoslasherEslint(
options as CreateTwoslashESLintOptions,
) as TwoslashGenericFunction<TwoslashExecuteOptions>,
}),
},
],
]);
/**
* Retrieves a twoslasher instance configuration and applies optional overrides from plugin options.
*
* @param key - The built-in twoslasher type identifier to retrieve from the instance map
* @param opts - Optional plugin configuration containing instance-specific overrides
*
* @returns An object containing the twoslasher instances, trigger pattern, and supported languages
*
* @throws {Error} When no twoslash instance is found for the provided key
*
* @internal
*/
const __getTwoslasherAndOverride = (
key: BuiltInTwoslashers,
opts: PluginTwoslashOptions["instanceConfigs"],
) => {
const data = TwoslashInstanceMap.get(key);
if (!data) {
throw new Error(`No twoslash instance found for key: ${key}`);
}
const { trigger, languages, twoslashers } = data;
const triggerOverride = opts?.[key]?.explicitTrigger;
const languagesOverride = opts?.[key]?.languages;
return {
twoslashers,
trigger: triggerOverride instanceof RegExp ? triggerOverride : trigger,
languages: languagesOverride ?? languages,
};
};
/**
* Creates a function that applies Twoslash transformations to code blocks.
*
* @param opts - Plugin configuration options for Twoslash instances
* @param options - Twoslash processing options
* @returns A function that processes a code block and applies the appropriate Twoslash transformer based on language and metadata triggers
*
* @template A - The return type of the transformation function
*
* @example
* ```ts
* const transformer = getTwoslasher(config, options);
* const result = await transformer(codeBlock, (twoslash) => twoslash.transform());
* ```
*/
export const getTwoslasher = (
opts: PluginTwoslashOptions["instanceConfigs"],
options: TwoslashOptions,
) => {
const twoslashersMap = BuiltInTwoslashers.reduce(
(acc, key) => {
const twoslasher = __getTwoslasherAndOverride(key, opts);
acc[key] = twoslasher;
return acc;
},
{} as Record<string, TwoslashMapData>,
);
return <A>(
codeBlock: ExpressiveCodeBlock,
fn: (
transformer: TwoslashInstance | TwoslashGenericFunction<TwoslashExecuteOptions>,
trigger: string,
) => Promise<A> | A,
) => {
for (const key in twoslashersMap) {
const { trigger, languages, twoslashers } = twoslashersMap[key as BuiltInTwoslashers];
if (languages.includes(codeBlock.language) && trigger.test(codeBlock.meta)) {
const transformer =
twoslashers(options)[codeBlock.language] ?? twoslashers(options).default;
return fn(transformer, key);
}
}
return null;
};
};
export const resolveTsconfigPath = (paths: string, overridePath?: string): string => {
if (overridePath === undefined) {
return path.join(paths, "tsconfig.json");
}
if (path.isAbsolute(overridePath) === true) {
return overridePath;
}
return path.resolve(paths, overridePath);
};
export const parseSnippetTsconfig = (
tsconfigPath: string,
): { source: string; options: ts.CompilerOptions } => {
if (fs.existsSync(tsconfigPath) === false) {
throw new Error(`tsconfig not found at ${tsconfigPath}`);
}
const source = fs.readFileSync(tsconfigPath, "utf8");
const configFile = ts.readConfigFile(tsconfigPath, ts.sys.readFile);
if (configFile.error !== undefined) {
const message = ts.flattenDiagnosticMessageText(configFile.error.messageText, "\n");
throw new Error(`Unable to read ${tsconfigPath}: ${message}`);
}
const parsed = ts.parseJsonConfigFileContent(
configFile.config,
ts.sys,
path.dirname(tsconfigPath),
undefined,
tsconfigPath,
);
return { source, options: parsed.options };
};