@shikijs/core 2.4.0 → 2.4.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.
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { CreatedBundledHighlighterOptions, CreateHighlighterFactory, LanguageInput, ThemeInput, HighlighterCoreOptions, CodeToHastOptions, CodeToTokensOptions, TokensResult, RequireKeys, CodeToTokensBaseOptions, ThemedToken, CodeToTokensWithThemesOptions, ThemedTokenWithVariants, BundledHighlighterOptions, HighlighterGeneric, GrammarState, Awaitable, HighlighterCore, ShikiInternal, RegexEngine, LoadWasmOptions, ShikiTransformerContextCommon, CodeToHastRenderOptions, ShikiTransformerContextSource, ThemeRegistrationResolved, TokenizeWithThemeOptions, Grammar, ThemeRegistrationAny, ThemeRegistration, ShikiTransformer, MaybeArray, PlainTextLanguage, SpecialLanguage, SpecialTheme, MaybeGetter, TokenStyles, Position } from '@shikijs/types';
1
+ import { CreatedBundledHighlighterOptions, CreateHighlighterFactory, LanguageInput, ThemeInput, HighlighterCoreOptions, CodeToHastOptions, CodeToTokensOptions, TokensResult, RequireKeys, CodeToTokensBaseOptions, ThemedToken, CodeToTokensWithThemesOptions, ThemedTokenWithVariants, BundledHighlighterOptions, HighlighterGeneric, GrammarState, Awaitable, HighlighterCore, ShikiInternal, RegexEngine, LoadWasmOptions, ShikiTransformerContextCommon, CodeToHastRenderOptions, ShikiTransformerContextSource, ThemeRegistrationResolved, TokenizeWithThemeOptions, Grammar, ThemeRegistrationAny, ThemeRegistration, ShikiTransformer, MaybeArray, MaybeGetter, PlainTextLanguage, SpecialLanguage, SpecialTheme, Position, TokenStyles } from '@shikijs/types';
2
2
  export * from '@shikijs/types';
3
3
  import { Root, Element } from 'hast';
4
4
  import { JavaScriptRegexEngineOptions } from '@shikijs/engine-javascript';
@@ -219,11 +219,15 @@ declare function createCssVariablesTheme(options?: CssVariablesThemeOptions): Th
219
219
  */
220
220
  declare function transformerDecorations(): ShikiTransformer;
221
221
 
222
+ declare function resolveColorReplacements(theme: ThemeRegistrationAny | string, options?: TokenizeWithThemeOptions): Record<string, string | undefined>;
223
+ declare function applyColorReplacements(color: string, replacements?: Record<string, string | undefined>): string;
224
+ declare function applyColorReplacements(color?: string | undefined, replacements?: Record<string, string | undefined>): string | undefined;
225
+
222
226
  declare function toArray<T>(x: MaybeArray<T>): T[];
223
227
  /**
224
- * Split a string into lines, each line preserves the line ending.
228
+ * Normalize a getter to a promise.
225
229
  */
226
- declare function splitLines(code: string, preserveEnding?: boolean): [string, number][];
230
+ declare function normalizeGetter<T>(p: MaybeGetter<T>): Promise<T>;
227
231
  /**
228
232
  * Check if the language is plaintext that is ignored by Shiki.
229
233
  *
@@ -248,31 +252,18 @@ declare function isNoneTheme(theme: string | ThemeInput | null | undefined): the
248
252
  * Hard-coded themes: `none`.
249
253
  */
250
254
  declare function isSpecialTheme(theme: string | ThemeInput | null | undefined): theme is SpecialTheme;
255
+
251
256
  /**
252
257
  * Utility to append class to a hast node
253
258
  *
254
259
  * If the `property.class` is a string, it will be splitted by space and converted to an array.
255
260
  */
256
261
  declare function addClassToHast(node: Element, className: string | string[]): Element;
262
+
257
263
  /**
258
- * Split a token into multiple tokens by given offsets.
259
- *
260
- * The offsets are relative to the token, and should be sorted.
261
- */
262
- declare function splitToken<T extends Pick<ThemedToken, 'content' | 'offset'>>(token: T, offsets: number[]): T[];
263
- /**
264
- * Split 2D tokens array by given breakpoints.
265
- */
266
- declare function splitTokens<T extends Pick<ThemedToken, 'content' | 'offset'>>(tokens: T[][], breakpoints: number[] | Set<number>): T[][];
267
- /**
268
- * Normalize a getter to a promise.
264
+ * Split a string into lines, each line preserves the line ending.
269
265
  */
270
- declare function normalizeGetter<T>(p: MaybeGetter<T>): Promise<T>;
271
- declare function resolveColorReplacements(theme: ThemeRegistrationAny | string, options?: TokenizeWithThemeOptions): Record<string, string | undefined>;
272
- declare function applyColorReplacements(color: string, replacements?: Record<string, string | undefined>): string;
273
- declare function applyColorReplacements(color?: string | undefined, replacements?: Record<string, string | undefined>): string | undefined;
274
- declare function getTokenStyleObject(token: TokenStyles): Record<string, string>;
275
- declare function stringifyTokenStyle(token: string | Record<string, string>): string;
266
+ declare function splitLines(code: string, preserveEnding?: boolean): [string, number][];
276
267
  /**
277
268
  * Creates a converter between index and position in a code block.
278
269
  *
@@ -283,6 +274,26 @@ declare function createPositionConverter(code: string): {
283
274
  indexToPos: (index: number) => Position;
284
275
  posToIndex: (line: number, character: number) => number;
285
276
  };
277
+ /**
278
+ * Guess embedded languages from given code and highlighter.
279
+ *
280
+ * When highlighter is provided, only bundled languages will be included.
281
+ */
282
+ declare function guessEmbeddedLanguages(code: string, _lang: string | undefined, highlighter?: HighlighterGeneric<any, any>): string[];
283
+
284
+ /**
285
+ * Split a token into multiple tokens by given offsets.
286
+ *
287
+ * The offsets are relative to the token, and should be sorted.
288
+ */
289
+ declare function splitToken<T extends Pick<ThemedToken, 'content' | 'offset'>>(token: T, offsets: number[]): T[];
290
+ /**
291
+ * Split 2D tokens array by given breakpoints.
292
+ */
293
+ declare function splitTokens<T extends Pick<ThemedToken, 'content' | 'offset'>>(tokens: T[][], breakpoints: number[] | Set<number>): T[][];
294
+ declare function flatTokenVariants(merged: ThemedTokenWithVariants, variantsOrder: string[], cssVariablePrefix: string, defaultColor: string | boolean): ThemedToken;
295
+ declare function getTokenStyleObject(token: TokenStyles): Record<string, string>;
296
+ declare function stringifyTokenStyle(token: string | Record<string, string>): string;
286
297
 
287
298
  type DeprecationTarget = 3;
288
299
  /**
@@ -298,4 +309,4 @@ declare function enableDeprecationWarnings(emitDeprecation?: DeprecationTarget |
298
309
  */
299
310
  declare function warnDeprecated(message: string, version?: DeprecationTarget): void;
300
311
 
301
- export { type CreateSingletonShorthandsOptions, type CssVariablesThemeOptions, type ShorthandsBundle, addClassToHast, applyColorReplacements, codeToHast, codeToHtml, codeToTokens, codeToTokensBase, codeToTokensWithThemes, createCssVariablesTheme, createHighlighterCore, createHighlighterCoreSync, createJavaScriptRegexEngine, createOnigurumaEngine, createPositionConverter, createShikiInternal, createShikiInternalSync, createSingletonShorthands, createWasmOnigEngine, createdBundledHighlighter, defaultJavaScriptRegexConstructor, enableDeprecationWarnings, getHighlighterCore, getShikiInternal, getSingletonHighlighterCore, getTokenStyleObject, isNoneTheme, isPlainLang, isSpecialLang, isSpecialTheme, loadWasm, makeSingletonHighlighter, makeSingletonHighlighterCore, normalizeGetter, normalizeTheme, resolveColorReplacements, splitLines, splitToken, splitTokens, stringifyTokenStyle, toArray, tokenizeAnsiWithTheme, tokenizeWithTheme, tokensToHast, transformerDecorations, warnDeprecated };
312
+ export { type CreateSingletonShorthandsOptions, type CssVariablesThemeOptions, type ShorthandsBundle, addClassToHast, applyColorReplacements, codeToHast, codeToHtml, codeToTokens, codeToTokensBase, codeToTokensWithThemes, createCssVariablesTheme, createHighlighterCore, createHighlighterCoreSync, createJavaScriptRegexEngine, createOnigurumaEngine, createPositionConverter, createShikiInternal, createShikiInternalSync, createSingletonShorthands, createWasmOnigEngine, createdBundledHighlighter, defaultJavaScriptRegexConstructor, enableDeprecationWarnings, flatTokenVariants, getHighlighterCore, getShikiInternal, getSingletonHighlighterCore, getTokenStyleObject, guessEmbeddedLanguages, isNoneTheme, isPlainLang, isSpecialLang, isSpecialTheme, loadWasm, makeSingletonHighlighter, makeSingletonHighlighterCore, normalizeGetter, normalizeTheme, resolveColorReplacements, splitLines, splitToken, splitTokens, stringifyTokenStyle, toArray, tokenizeAnsiWithTheme, tokenizeWithTheme, tokensToHast, transformerDecorations, warnDeprecated };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { CreatedBundledHighlighterOptions, CreateHighlighterFactory, LanguageInput, ThemeInput, HighlighterCoreOptions, CodeToHastOptions, CodeToTokensOptions, TokensResult, RequireKeys, CodeToTokensBaseOptions, ThemedToken, CodeToTokensWithThemesOptions, ThemedTokenWithVariants, BundledHighlighterOptions, HighlighterGeneric, GrammarState, Awaitable, HighlighterCore, ShikiInternal, RegexEngine, LoadWasmOptions, ShikiTransformerContextCommon, CodeToHastRenderOptions, ShikiTransformerContextSource, ThemeRegistrationResolved, TokenizeWithThemeOptions, Grammar, ThemeRegistrationAny, ThemeRegistration, ShikiTransformer, MaybeArray, PlainTextLanguage, SpecialLanguage, SpecialTheme, MaybeGetter, TokenStyles, Position } from '@shikijs/types';
1
+ import { CreatedBundledHighlighterOptions, CreateHighlighterFactory, LanguageInput, ThemeInput, HighlighterCoreOptions, CodeToHastOptions, CodeToTokensOptions, TokensResult, RequireKeys, CodeToTokensBaseOptions, ThemedToken, CodeToTokensWithThemesOptions, ThemedTokenWithVariants, BundledHighlighterOptions, HighlighterGeneric, GrammarState, Awaitable, HighlighterCore, ShikiInternal, RegexEngine, LoadWasmOptions, ShikiTransformerContextCommon, CodeToHastRenderOptions, ShikiTransformerContextSource, ThemeRegistrationResolved, TokenizeWithThemeOptions, Grammar, ThemeRegistrationAny, ThemeRegistration, ShikiTransformer, MaybeArray, MaybeGetter, PlainTextLanguage, SpecialLanguage, SpecialTheme, Position, TokenStyles } from '@shikijs/types';
2
2
  export * from '@shikijs/types';
3
3
  import { Root, Element } from 'hast';
4
4
  import { JavaScriptRegexEngineOptions } from '@shikijs/engine-javascript';
@@ -219,11 +219,15 @@ declare function createCssVariablesTheme(options?: CssVariablesThemeOptions): Th
219
219
  */
220
220
  declare function transformerDecorations(): ShikiTransformer;
221
221
 
222
+ declare function resolveColorReplacements(theme: ThemeRegistrationAny | string, options?: TokenizeWithThemeOptions): Record<string, string | undefined>;
223
+ declare function applyColorReplacements(color: string, replacements?: Record<string, string | undefined>): string;
224
+ declare function applyColorReplacements(color?: string | undefined, replacements?: Record<string, string | undefined>): string | undefined;
225
+
222
226
  declare function toArray<T>(x: MaybeArray<T>): T[];
223
227
  /**
224
- * Split a string into lines, each line preserves the line ending.
228
+ * Normalize a getter to a promise.
225
229
  */
226
- declare function splitLines(code: string, preserveEnding?: boolean): [string, number][];
230
+ declare function normalizeGetter<T>(p: MaybeGetter<T>): Promise<T>;
227
231
  /**
228
232
  * Check if the language is plaintext that is ignored by Shiki.
229
233
  *
@@ -248,31 +252,18 @@ declare function isNoneTheme(theme: string | ThemeInput | null | undefined): the
248
252
  * Hard-coded themes: `none`.
249
253
  */
250
254
  declare function isSpecialTheme(theme: string | ThemeInput | null | undefined): theme is SpecialTheme;
255
+
251
256
  /**
252
257
  * Utility to append class to a hast node
253
258
  *
254
259
  * If the `property.class` is a string, it will be splitted by space and converted to an array.
255
260
  */
256
261
  declare function addClassToHast(node: Element, className: string | string[]): Element;
262
+
257
263
  /**
258
- * Split a token into multiple tokens by given offsets.
259
- *
260
- * The offsets are relative to the token, and should be sorted.
261
- */
262
- declare function splitToken<T extends Pick<ThemedToken, 'content' | 'offset'>>(token: T, offsets: number[]): T[];
263
- /**
264
- * Split 2D tokens array by given breakpoints.
265
- */
266
- declare function splitTokens<T extends Pick<ThemedToken, 'content' | 'offset'>>(tokens: T[][], breakpoints: number[] | Set<number>): T[][];
267
- /**
268
- * Normalize a getter to a promise.
264
+ * Split a string into lines, each line preserves the line ending.
269
265
  */
270
- declare function normalizeGetter<T>(p: MaybeGetter<T>): Promise<T>;
271
- declare function resolveColorReplacements(theme: ThemeRegistrationAny | string, options?: TokenizeWithThemeOptions): Record<string, string | undefined>;
272
- declare function applyColorReplacements(color: string, replacements?: Record<string, string | undefined>): string;
273
- declare function applyColorReplacements(color?: string | undefined, replacements?: Record<string, string | undefined>): string | undefined;
274
- declare function getTokenStyleObject(token: TokenStyles): Record<string, string>;
275
- declare function stringifyTokenStyle(token: string | Record<string, string>): string;
266
+ declare function splitLines(code: string, preserveEnding?: boolean): [string, number][];
276
267
  /**
277
268
  * Creates a converter between index and position in a code block.
278
269
  *
@@ -283,6 +274,26 @@ declare function createPositionConverter(code: string): {
283
274
  indexToPos: (index: number) => Position;
284
275
  posToIndex: (line: number, character: number) => number;
285
276
  };
277
+ /**
278
+ * Guess embedded languages from given code and highlighter.
279
+ *
280
+ * When highlighter is provided, only bundled languages will be included.
281
+ */
282
+ declare function guessEmbeddedLanguages(code: string, _lang: string | undefined, highlighter?: HighlighterGeneric<any, any>): string[];
283
+
284
+ /**
285
+ * Split a token into multiple tokens by given offsets.
286
+ *
287
+ * The offsets are relative to the token, and should be sorted.
288
+ */
289
+ declare function splitToken<T extends Pick<ThemedToken, 'content' | 'offset'>>(token: T, offsets: number[]): T[];
290
+ /**
291
+ * Split 2D tokens array by given breakpoints.
292
+ */
293
+ declare function splitTokens<T extends Pick<ThemedToken, 'content' | 'offset'>>(tokens: T[][], breakpoints: number[] | Set<number>): T[][];
294
+ declare function flatTokenVariants(merged: ThemedTokenWithVariants, variantsOrder: string[], cssVariablePrefix: string, defaultColor: string | boolean): ThemedToken;
295
+ declare function getTokenStyleObject(token: TokenStyles): Record<string, string>;
296
+ declare function stringifyTokenStyle(token: string | Record<string, string>): string;
286
297
 
287
298
  type DeprecationTarget = 3;
288
299
  /**
@@ -298,4 +309,4 @@ declare function enableDeprecationWarnings(emitDeprecation?: DeprecationTarget |
298
309
  */
299
310
  declare function warnDeprecated(message: string, version?: DeprecationTarget): void;
300
311
 
301
- export { type CreateSingletonShorthandsOptions, type CssVariablesThemeOptions, type ShorthandsBundle, addClassToHast, applyColorReplacements, codeToHast, codeToHtml, codeToTokens, codeToTokensBase, codeToTokensWithThemes, createCssVariablesTheme, createHighlighterCore, createHighlighterCoreSync, createJavaScriptRegexEngine, createOnigurumaEngine, createPositionConverter, createShikiInternal, createShikiInternalSync, createSingletonShorthands, createWasmOnigEngine, createdBundledHighlighter, defaultJavaScriptRegexConstructor, enableDeprecationWarnings, getHighlighterCore, getShikiInternal, getSingletonHighlighterCore, getTokenStyleObject, isNoneTheme, isPlainLang, isSpecialLang, isSpecialTheme, loadWasm, makeSingletonHighlighter, makeSingletonHighlighterCore, normalizeGetter, normalizeTheme, resolveColorReplacements, splitLines, splitToken, splitTokens, stringifyTokenStyle, toArray, tokenizeAnsiWithTheme, tokenizeWithTheme, tokensToHast, transformerDecorations, warnDeprecated };
312
+ export { type CreateSingletonShorthandsOptions, type CssVariablesThemeOptions, type ShorthandsBundle, addClassToHast, applyColorReplacements, codeToHast, codeToHtml, codeToTokens, codeToTokensBase, codeToTokensWithThemes, createCssVariablesTheme, createHighlighterCore, createHighlighterCoreSync, createJavaScriptRegexEngine, createOnigurumaEngine, createPositionConverter, createShikiInternal, createShikiInternalSync, createSingletonShorthands, createWasmOnigEngine, createdBundledHighlighter, defaultJavaScriptRegexConstructor, enableDeprecationWarnings, flatTokenVariants, getHighlighterCore, getShikiInternal, getSingletonHighlighterCore, getTokenStyleObject, guessEmbeddedLanguages, isNoneTheme, isPlainLang, isSpecialLang, isSpecialTheme, loadWasm, makeSingletonHighlighter, makeSingletonHighlighterCore, normalizeGetter, normalizeTheme, resolveColorReplacements, splitLines, splitToken, splitTokens, stringifyTokenStyle, toArray, tokenizeAnsiWithTheme, tokenizeWithTheme, tokensToHast, transformerDecorations, warnDeprecated };
package/dist/index.mjs CHANGED
@@ -22,20 +22,28 @@ function loadWasm(options) {
22
22
  return loadWasm$1(options);
23
23
  }
24
24
 
25
+ function resolveColorReplacements(theme, options) {
26
+ const replacements = typeof theme === "string" ? {} : { ...theme.colorReplacements };
27
+ const themeName = typeof theme === "string" ? theme : theme.name;
28
+ for (const [key, value] of Object.entries(options?.colorReplacements || {})) {
29
+ if (typeof value === "string")
30
+ replacements[key] = value;
31
+ else if (key === themeName)
32
+ Object.assign(replacements, value);
33
+ }
34
+ return replacements;
35
+ }
36
+ function applyColorReplacements(color, replacements) {
37
+ if (!color)
38
+ return color;
39
+ return replacements?.[color?.toLowerCase()] || color;
40
+ }
41
+
25
42
  function toArray(x) {
26
43
  return Array.isArray(x) ? x : [x];
27
44
  }
28
- function splitLines(code, preserveEnding = false) {
29
- const parts = code.split(/(\r?\n)/g);
30
- let index = 0;
31
- const lines = [];
32
- for (let i = 0; i < parts.length; i += 2) {
33
- const line = preserveEnding ? parts[i] + (parts[i + 1] || "") : parts[i];
34
- lines.push([line, index]);
35
- index += parts[i].length;
36
- index += parts[i + 1]?.length || 0;
37
- }
38
- return lines;
45
+ async function normalizeGetter(p) {
46
+ return Promise.resolve(typeof p === "function" ? p() : p).then((r) => r.default || r);
39
47
  }
40
48
  function isPlainLang(lang) {
41
49
  return !lang || ["plaintext", "txt", "text", "plain"].includes(lang);
@@ -49,6 +57,7 @@ function isNoneTheme(theme) {
49
57
  function isSpecialTheme(theme) {
50
58
  return isNoneTheme(theme);
51
59
  }
60
+
52
61
  function addClassToHast(node, className) {
53
62
  if (!className)
54
63
  return node;
@@ -65,6 +74,68 @@ function addClassToHast(node, className) {
65
74
  }
66
75
  return node;
67
76
  }
77
+
78
+ function splitLines(code, preserveEnding = false) {
79
+ const parts = code.split(/(\r?\n)/g);
80
+ let index = 0;
81
+ const lines = [];
82
+ for (let i = 0; i < parts.length; i += 2) {
83
+ const line = preserveEnding ? parts[i] + (parts[i + 1] || "") : parts[i];
84
+ lines.push([line, index]);
85
+ index += parts[i].length;
86
+ index += parts[i + 1]?.length || 0;
87
+ }
88
+ return lines;
89
+ }
90
+ function createPositionConverter(code) {
91
+ const lines = splitLines(code, true).map(([line]) => line);
92
+ function indexToPos(index) {
93
+ if (index === code.length) {
94
+ return {
95
+ line: lines.length - 1,
96
+ character: lines[lines.length - 1].length
97
+ };
98
+ }
99
+ let character = index;
100
+ let line = 0;
101
+ for (const lineText of lines) {
102
+ if (character < lineText.length)
103
+ break;
104
+ character -= lineText.length;
105
+ line++;
106
+ }
107
+ return { line, character };
108
+ }
109
+ function posToIndex(line, character) {
110
+ let index = 0;
111
+ for (let i = 0; i < line; i++)
112
+ index += lines[i].length;
113
+ index += character;
114
+ return index;
115
+ }
116
+ return {
117
+ lines,
118
+ indexToPos,
119
+ posToIndex
120
+ };
121
+ }
122
+ function guessEmbeddedLanguages(code, _lang, highlighter) {
123
+ const langs = /* @__PURE__ */ new Set();
124
+ for (const match of code.matchAll(/lang=["']([\w-]+)["']/g)) {
125
+ langs.add(match[1]);
126
+ }
127
+ for (const match of code.matchAll(/(?:```|~~~)([\w-]+)/g)) {
128
+ langs.add(match[1]);
129
+ }
130
+ for (const match of code.matchAll(/\\begin\{([\w-]+)\}/g)) {
131
+ langs.add(match[1]);
132
+ }
133
+ if (!highlighter)
134
+ return Array.from(langs);
135
+ const bundle = highlighter.getBundledLanguages();
136
+ return Array.from(langs).filter((l) => l && bundle[l]);
137
+ }
138
+
68
139
  function splitToken(token, offsets) {
69
140
  let lastOffset = 0;
70
141
  const tokens = [];
@@ -100,24 +171,29 @@ function splitTokens(tokens, breakpoints) {
100
171
  });
101
172
  });
102
173
  }
103
- async function normalizeGetter(p) {
104
- return Promise.resolve(typeof p === "function" ? p() : p).then((r) => r.default || r);
105
- }
106
- function resolveColorReplacements(theme, options) {
107
- const replacements = typeof theme === "string" ? {} : { ...theme.colorReplacements };
108
- const themeName = typeof theme === "string" ? theme : theme.name;
109
- for (const [key, value] of Object.entries(options?.colorReplacements || {})) {
110
- if (typeof value === "string")
111
- replacements[key] = value;
112
- else if (key === themeName)
113
- Object.assign(replacements, value);
114
- }
115
- return replacements;
116
- }
117
- function applyColorReplacements(color, replacements) {
118
- if (!color)
119
- return color;
120
- return replacements?.[color?.toLowerCase()] || color;
174
+ function flatTokenVariants(merged, variantsOrder, cssVariablePrefix, defaultColor) {
175
+ const token = {
176
+ content: merged.content,
177
+ explanation: merged.explanation,
178
+ offset: merged.offset
179
+ };
180
+ const styles = variantsOrder.map((t) => getTokenStyleObject(merged.variants[t]));
181
+ const styleKeys = new Set(styles.flatMap((t) => Object.keys(t)));
182
+ const mergedStyles = {};
183
+ styles.forEach((cur, idx) => {
184
+ for (const key of styleKeys) {
185
+ const value = cur[key] || "inherit";
186
+ if (idx === 0 && defaultColor) {
187
+ mergedStyles[key] = value;
188
+ } else {
189
+ const keyName = key === "color" ? "" : key === "background-color" ? "-bg" : `-${key}`;
190
+ const varKey = cssVariablePrefix + variantsOrder[idx] + (key === "color" ? "" : keyName);
191
+ mergedStyles[varKey] = value;
192
+ }
193
+ }
194
+ });
195
+ token.htmlStyle = mergedStyles;
196
+ return token;
121
197
  }
122
198
  function getTokenStyleObject(token) {
123
199
  const styles = {};
@@ -140,45 +216,6 @@ function stringifyTokenStyle(token) {
140
216
  return token;
141
217
  return Object.entries(token).map(([key, value]) => `${key}:${value}`).join(";");
142
218
  }
143
- function createPositionConverter(code) {
144
- const lines = splitLines(code, true).map(([line]) => line);
145
- function indexToPos(index) {
146
- if (index === code.length) {
147
- return {
148
- line: lines.length - 1,
149
- character: lines[lines.length - 1].length
150
- };
151
- }
152
- let character = index;
153
- let line = 0;
154
- for (const lineText of lines) {
155
- if (character < lineText.length)
156
- break;
157
- character -= lineText.length;
158
- line++;
159
- }
160
- return { line, character };
161
- }
162
- function posToIndex(line, character) {
163
- let index = 0;
164
- for (let i = 0; i < line; i++)
165
- index += lines[i].length;
166
- index += character;
167
- return index;
168
- }
169
- return {
170
- lines,
171
- indexToPos,
172
- posToIndex
173
- };
174
- }
175
-
176
- class ShikiError extends Error {
177
- constructor(message) {
178
- super(message);
179
- this.name = "ShikiError";
180
- }
181
- }
182
219
 
183
220
  const _grammarStateMap = /* @__PURE__ */ new WeakMap();
184
221
  function setLastGrammarStateToMap(keys, state) {
@@ -266,7 +303,7 @@ function getScopes(stack) {
266
303
  }
267
304
  function getGrammarStack(state, theme) {
268
305
  if (!(state instanceof GrammarState))
269
- throw new ShikiError("Invalid grammar state");
306
+ throw new ShikiError$1("Invalid grammar state");
270
307
  return state.getInternalStack(theme);
271
308
  }
272
309
 
@@ -277,7 +314,7 @@ function transformerDecorations() {
277
314
  let normalizePosition = function(p) {
278
315
  if (typeof p === "number") {
279
316
  if (p < 0 || p > shiki.source.length)
280
- throw new ShikiError(`Invalid decoration offset: ${p}. Code length: ${shiki.source.length}`);
317
+ throw new ShikiError$1(`Invalid decoration offset: ${p}. Code length: ${shiki.source.length}`);
281
318
  return {
282
319
  ...converter.indexToPos(p),
283
320
  offset: p
@@ -285,9 +322,9 @@ function transformerDecorations() {
285
322
  } else {
286
323
  const line = converter.lines[p.line];
287
324
  if (line === void 0)
288
- throw new ShikiError(`Invalid decoration position ${JSON.stringify(p)}. Lines length: ${converter.lines.length}`);
325
+ throw new ShikiError$1(`Invalid decoration position ${JSON.stringify(p)}. Lines length: ${converter.lines.length}`);
289
326
  if (p.character < 0 || p.character > line.length)
290
- throw new ShikiError(`Invalid decoration position ${JSON.stringify(p)}. Line ${p.line} length: ${line.length}`);
327
+ throw new ShikiError$1(`Invalid decoration position ${JSON.stringify(p)}. Line ${p.line} length: ${line.length}`);
291
328
  return {
292
329
  ...p,
293
330
  offset: converter.posToIndex(p.line, p.character)
@@ -325,7 +362,7 @@ function transformerDecorations() {
325
362
  const ctx = getContext(this);
326
363
  const lines = Array.from(codeEl.children).filter((i) => i.type === "element" && i.tagName === "span");
327
364
  if (lines.length !== ctx.converter.lines.length)
328
- throw new ShikiError(`Number of lines in code element (${lines.length}) does not match the number of lines in the source (${ctx.converter.lines.length}). Failed to apply decorations.`);
365
+ throw new ShikiError$1(`Number of lines in code element (${lines.length}) does not match the number of lines in the source (${ctx.converter.lines.length}). Failed to apply decorations.`);
329
366
  function applyLineSection(line, start, end, decoration) {
330
367
  const lineEl = lines[line];
331
368
  let text = "";
@@ -347,9 +384,9 @@ function transformerDecorations() {
347
384
  }
348
385
  }
349
386
  if (startIndex === -1)
350
- throw new ShikiError(`Failed to find start index for decoration ${JSON.stringify(decoration.start)}`);
387
+ throw new ShikiError$1(`Failed to find start index for decoration ${JSON.stringify(decoration.start)}`);
351
388
  if (endIndex === -1)
352
- throw new ShikiError(`Failed to find end index for decoration ${JSON.stringify(decoration.end)}`);
389
+ throw new ShikiError$1(`Failed to find end index for decoration ${JSON.stringify(decoration.end)}`);
353
390
  const children = lineEl.children.slice(startIndex, endIndex);
354
391
  if (!decoration.alwaysWrap && children.length === lineEl.children.length) {
355
392
  applyDecoration(lineEl, decoration, "line");
@@ -404,7 +441,7 @@ function verifyIntersections(items) {
404
441
  for (let i = 0; i < items.length; i++) {
405
442
  const foo = items[i];
406
443
  if (foo.start.offset > foo.end.offset)
407
- throw new ShikiError(`Invalid decoration range: ${JSON.stringify(foo.start)} - ${JSON.stringify(foo.end)}`);
444
+ throw new ShikiError$1(`Invalid decoration range: ${JSON.stringify(foo.start)} - ${JSON.stringify(foo.end)}`);
408
445
  for (let j = i + 1; j < items.length; j++) {
409
446
  const bar = items[j];
410
447
  const isFooHasBarStart = foo.start.offset <= bar.start.offset && bar.start.offset < foo.end.offset;
@@ -416,7 +453,7 @@ function verifyIntersections(items) {
416
453
  continue;
417
454
  if (isBarHasFooStart && isBarHasFooEnd)
418
455
  continue;
419
- throw new ShikiError(`Decorations ${JSON.stringify(foo.start)} and ${JSON.stringify(bar.start)} intersect.`);
456
+ throw new ShikiError$1(`Decorations ${JSON.stringify(foo.start)} and ${JSON.stringify(bar.start)} intersect.`);
420
457
  }
421
458
  }
422
459
  }
@@ -1098,7 +1135,7 @@ function codeToTokens(internal, code, options) {
1098
1135
  throw new ShikiError$1(`\`themes\` option must contain the defaultColor key \`${defaultColor}\``);
1099
1136
  const themeRegs = themes.map((t) => internal.getTheme(t.theme));
1100
1137
  const themesOrder = themes.map((t) => t.color);
1101
- tokens = themeTokens.map((line) => line.map((token) => mergeToken(token, themesOrder, cssVariablePrefix, defaultColor)));
1138
+ tokens = themeTokens.map((line) => line.map((token) => flatTokenVariants(token, themesOrder, cssVariablePrefix, defaultColor)));
1102
1139
  if (grammarState)
1103
1140
  setLastGrammarStateToMap(tokens, grammarState);
1104
1141
  const themeColorReplacements = themes.map((t) => resolveColorReplacements(t.theme, options));
@@ -1130,30 +1167,6 @@ function codeToTokens(internal, code, options) {
1130
1167
  grammarState
1131
1168
  };
1132
1169
  }
1133
- function mergeToken(merged, variantsOrder, cssVariablePrefix, defaultColor) {
1134
- const token = {
1135
- content: merged.content,
1136
- explanation: merged.explanation,
1137
- offset: merged.offset
1138
- };
1139
- const styles = variantsOrder.map((t) => getTokenStyleObject(merged.variants[t]));
1140
- const styleKeys = new Set(styles.flatMap((t) => Object.keys(t)));
1141
- const mergedStyles = {};
1142
- styles.forEach((cur, idx) => {
1143
- for (const key of styleKeys) {
1144
- const value = cur[key] || "inherit";
1145
- if (idx === 0 && defaultColor) {
1146
- mergedStyles[key] = value;
1147
- } else {
1148
- const keyName = key === "color" ? "" : key === "background-color" ? "-bg" : `-${key}`;
1149
- const varKey = cssVariablePrefix + variantsOrder[idx] + (key === "color" ? "" : keyName);
1150
- mergedStyles[varKey] = value;
1151
- }
1152
- }
1153
- });
1154
- token.htmlStyle = mergedStyles;
1155
- return token;
1156
- }
1157
1170
 
1158
1171
  function codeToHast(internal, code, options, transformerContext = {
1159
1172
  meta: {},
@@ -1512,6 +1525,13 @@ async function resolveThemes(themes) {
1512
1525
  return resolved.filter((i) => !!i);
1513
1526
  }
1514
1527
 
1528
+ class ShikiError extends Error {
1529
+ constructor(message) {
1530
+ super(message);
1531
+ this.name = "ShikiError";
1532
+ }
1533
+ }
1534
+
1515
1535
  class Registry extends Registry$1 {
1516
1536
  constructor(_resolver, _themes, _langs, _alias = {}) {
1517
1537
  super(_resolver);
@@ -2246,4 +2266,4 @@ function createCssVariablesTheme(options = {}) {
2246
2266
  return theme;
2247
2267
  }
2248
2268
 
2249
- export { addClassToHast, applyColorReplacements, codeToHast, codeToHtml, codeToTokens, codeToTokensBase, codeToTokensWithThemes, createCssVariablesTheme, createHighlighterCore, createHighlighterCoreSync, createJavaScriptRegexEngine, createOnigurumaEngine, createPositionConverter, createShikiInternal, createShikiInternalSync, createSingletonShorthands, createWasmOnigEngine, createdBundledHighlighter, defaultJavaScriptRegexConstructor, getHighlighterCore, getShikiInternal, getSingletonHighlighterCore, getTokenStyleObject, isNoneTheme, isPlainLang, isSpecialLang, isSpecialTheme, loadWasm, makeSingletonHighlighter, makeSingletonHighlighterCore, normalizeGetter, normalizeTheme, resolveColorReplacements, splitLines, splitToken, splitTokens, stringifyTokenStyle, toArray, tokenizeAnsiWithTheme, tokenizeWithTheme, tokensToHast, transformerDecorations, warnDeprecated };
2269
+ export { addClassToHast, applyColorReplacements, codeToHast, codeToHtml, codeToTokens, codeToTokensBase, codeToTokensWithThemes, createCssVariablesTheme, createHighlighterCore, createHighlighterCoreSync, createJavaScriptRegexEngine, createOnigurumaEngine, createPositionConverter, createShikiInternal, createShikiInternalSync, createSingletonShorthands, createWasmOnigEngine, createdBundledHighlighter, defaultJavaScriptRegexConstructor, flatTokenVariants, getHighlighterCore, getShikiInternal, getSingletonHighlighterCore, getTokenStyleObject, guessEmbeddedLanguages, isNoneTheme, isPlainLang, isSpecialLang, isSpecialTheme, loadWasm, makeSingletonHighlighter, makeSingletonHighlighterCore, normalizeGetter, normalizeTheme, resolveColorReplacements, splitLines, splitToken, splitTokens, stringifyTokenStyle, toArray, tokenizeAnsiWithTheme, tokenizeWithTheme, tokensToHast, transformerDecorations, warnDeprecated };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@shikijs/core",
3
3
  "type": "module",
4
- "version": "2.4.0",
4
+ "version": "2.4.2",
5
5
  "description": "Core of Shiki",
6
6
  "author": "Pine Wu <octref@gmail.com>; Anthony Fu <anthonyfu117@hotmail.com>",
7
7
  "license": "MIT",
@@ -63,9 +63,9 @@
63
63
  "@shikijs/vscode-textmate": "^10.0.2",
64
64
  "@types/hast": "^3.0.4",
65
65
  "hast-util-to-html": "^9.0.4",
66
- "@shikijs/engine-javascript": "2.4.0",
67
- "@shikijs/types": "2.4.0",
68
- "@shikijs/engine-oniguruma": "2.4.0"
66
+ "@shikijs/engine-oniguruma": "2.4.2",
67
+ "@shikijs/types": "2.4.2",
68
+ "@shikijs/engine-javascript": "2.4.2"
69
69
  },
70
70
  "scripts": {
71
71
  "build": "unbuild",