shiki-codegen 3.22.0 → 4.0.0

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/cli.d.mts CHANGED
@@ -1,2 +1 @@
1
-
2
- export { };
1
+ export { };
package/dist/cli.mjs CHANGED
@@ -1,33 +1,32 @@
1
- import fs from 'node:fs/promises';
2
- import { resolve, dirname } from 'node:path';
3
- import { cac } from 'cac';
4
- import { codegen } from './index.mjs';
5
- import 'shiki/bundle/full';
1
+ import { codegen } from "./index.mjs";
2
+ import fs from "node:fs/promises";
3
+ import { dirname, resolve } from "node:path";
4
+ import { cac } from "cac";
6
5
 
6
+ //#region src/cli.ts
7
7
  const cli = cac("shiki-codegen");
8
8
  cli.command("[path]", "Generate shiki bundle module").option("--themes <themes>", "Themes to include").option("--langs <langs>", "Languages to include").option("--engine <engine>", "Engine to use", { default: "javascript" }).option("--precompiled", "Use precompiled languages", { default: false }).option("--shorthands", "Generate shorthands", { default: true }).option("--format", "Use prettier to format", { default: true }).action(async (path, options) => {
9
- const output = resolve(path || "shiki.bundle.ts");
10
- const langs = (Array.isArray(options.langs) ? options.langs.join(",") : options.langs || "").split(",").map((lang) => lang.trim()).filter(Boolean);
11
- const themes = (Array.isArray(options.themes) ? options.themes.join(",") : options.themes || "").split(",").map((theme) => theme.trim()).filter(Boolean);
12
- const isTypeScript = !!output.match(/\.[cm]?ts$/i);
13
- if (!themes.length) {
14
- throw new Error("No themes specified, use --themes=theme-name to specify themes");
15
- }
16
- if (!langs.length) {
17
- throw new Error("No langs specified, use --langs=lang-name to specify langs");
18
- }
19
- const { code } = await codegen({
20
- langs,
21
- themes,
22
- engine: options.engine,
23
- precompiled: options.precompiled,
24
- shorthands: options.shorthands,
25
- format: options.format,
26
- typescript: isTypeScript
27
- });
28
- await fs.mkdir(dirname(output), { recursive: true });
29
- await fs.writeFile(output, code, "utf-8");
30
- console.log(`Generated bundle to ${output}`);
9
+ const output = resolve(path || "shiki.bundle.ts");
10
+ const langs = (Array.isArray(options.langs) ? options.langs.join(",") : options.langs || "").split(",").map((lang) => lang.trim()).filter(Boolean);
11
+ const themes = (Array.isArray(options.themes) ? options.themes.join(",") : options.themes || "").split(",").map((theme) => theme.trim()).filter(Boolean);
12
+ const isTypeScript = !!output.match(/\.[cm]?ts$/i);
13
+ if (!themes.length) throw new Error("No themes specified, use --themes=theme-name to specify themes");
14
+ if (!langs.length) throw new Error("No langs specified, use --langs=lang-name to specify langs");
15
+ const { code } = await codegen({
16
+ langs,
17
+ themes,
18
+ engine: options.engine,
19
+ precompiled: options.precompiled,
20
+ shorthands: options.shorthands,
21
+ format: options.format,
22
+ typescript: isTypeScript
23
+ });
24
+ await fs.mkdir(dirname(output), { recursive: true });
25
+ await fs.writeFile(output, code, "utf-8");
26
+ console.log(`Generated bundle to ${output}`);
31
27
  });
32
28
  cli.help();
33
29
  cli.parse();
30
+
31
+ //#endregion
32
+ export { };
package/dist/index.d.mts CHANGED
@@ -1,51 +1,51 @@
1
- import { Options } from 'prettier';
2
- import { BundledLanguage, BundledTheme } from 'shiki';
1
+ import { Options } from "prettier";
2
+ import { BundledLanguage, BundledTheme } from "shiki";
3
3
 
4
+ //#region src/index.d.ts
4
5
  interface ShikiCodegenOptions {
5
- /**
6
- * The header to add to the generated code.
7
- *
8
- * @default '/* Generate by @shikijs/codegen *\/'
9
- */
10
- header?: string;
11
- /**
12
- * The languages to bundle.
13
- */
14
- langs: readonly BundledLanguage[];
15
- /**
16
- * The themes to bundle.
17
- */
18
- themes: readonly BundledTheme[];
19
- /**
20
- * The engine to use for syntax highlighting.
21
- */
22
- engine: 'oniguruma' | 'javascript' | 'javascript-raw';
23
- /**
24
- * Use precompiled grammars.
25
- * Only available when `engine` is set to `javascript` or `javascript-raw`.
26
- */
27
- precompiled?: boolean;
28
- /**
29
- * Whether to generate TypeScript code.
30
- *
31
- * @default true
32
- */
33
- typescript?: boolean;
34
- /**
35
- * Generate shorthands for the highlighter.
36
- *
37
- * @default true
38
- */
39
- shorthands?: boolean;
40
- /**
41
- * Use Prettier to format the generated code.
42
- */
43
- format?: boolean | Options;
6
+ /**
7
+ * The header to add to the generated code.
8
+ *
9
+ * @default '/* Generate by @shikijs/codegen *\/'
10
+ */
11
+ header?: string;
12
+ /**
13
+ * The languages to bundle.
14
+ */
15
+ langs: readonly BundledLanguage[];
16
+ /**
17
+ * The themes to bundle.
18
+ */
19
+ themes: readonly BundledTheme[];
20
+ /**
21
+ * The engine to use for syntax highlighting.
22
+ */
23
+ engine: 'oniguruma' | 'javascript' | 'javascript-raw';
24
+ /**
25
+ * Use precompiled grammars.
26
+ * Only available when `engine` is set to `javascript` or `javascript-raw`.
27
+ */
28
+ precompiled?: boolean;
29
+ /**
30
+ * Whether to generate TypeScript code.
31
+ *
32
+ * @default true
33
+ */
34
+ typescript?: boolean;
35
+ /**
36
+ * Generate shorthands for the highlighter.
37
+ *
38
+ * @default true
39
+ */
40
+ shorthands?: boolean;
41
+ /**
42
+ * Use Prettier to format the generated code.
43
+ */
44
+ format?: boolean | Options;
44
45
  }
45
46
  interface ShikiCodegenResult {
46
- code: string;
47
+ code: string;
47
48
  }
48
49
  declare function codegen(options: ShikiCodegenOptions): Promise<ShikiCodegenResult>;
49
-
50
- export { codegen };
51
- export type { ShikiCodegenOptions, ShikiCodegenResult };
50
+ //#endregion
51
+ export { ShikiCodegenOptions, ShikiCodegenResult, codegen };
package/dist/index.mjs CHANGED
@@ -1,152 +1,95 @@
1
- import { bundledLanguagesInfo, bundledThemesInfo } from 'shiki/bundle/full';
1
+ import { bundledLanguagesInfo, bundledThemesInfo } from "shiki/bundle/full";
2
2
 
3
+ //#region src/index.ts
3
4
  async function codegen(options) {
4
- const {
5
- header = "/* Generate by @shikijs/codegen */",
6
- typescript = true,
7
- precompiled = false,
8
- format: _format = true,
9
- shorthands = true
10
- } = options;
11
- const ts = (code2) => typescript ? code2 : "";
12
- if (precompiled && options.engine !== "javascript" && options.engine !== "javascript-raw")
13
- throw new Error("Precompiled grammars are only available when using the JavaScript engine");
14
- const langs = options.langs.map((lang) => {
15
- const info = bundledLanguagesInfo.find((i) => i.id === lang || i.aliases?.includes(lang));
16
- if (!info)
17
- throw new Error(`Language ${lang} not found`);
18
- return info;
19
- });
20
- const themes = options.themes.map((theme) => {
21
- const info = bundledThemesInfo.find((i) => i.id === theme);
22
- if (!info)
23
- throw new Error(`Theme ${theme} not found`);
24
- return info;
25
- });
26
- const langsCode = `{
27
- ${langs.flatMap((lang) => {
28
- const ids = [lang.id, ...lang.aliases || []];
29
- return ids.map((id) => {
30
- return `${JSON.stringify(id)}: () => import('@shikijs/${precompiled ? "langs-precompiled" : "langs"}/${lang.id}'),
31
- `;
32
- });
33
- }).join("")}}`;
34
- const themesCode = `{
35
- ${themes.map((theme) => {
36
- return `${JSON.stringify(theme.id)}: () => import('@shikijs/themes/${theme.id}'),
37
- `;
38
- }).join("")}}`;
39
- const typeImports = {
40
- "@shikijs/types": ["HighlighterGeneric", "DynamicImportThemeRegistration", "DynamicImportLanguageRegistration"]
41
- };
42
- const imports = {
43
- "@shikijs/core": ["createBundledHighlighter"]
44
- };
45
- const lines = [
46
- ""
47
- ];
48
- const exports$1 = [];
49
- const typeExports = [];
50
- if (typescript) {
51
- lines.push(
52
- "",
53
- `type BundledLanguage = ${langs.flatMap((lang) => [lang.id, ...lang.aliases || []]).map((lang) => `'${lang}'`).join(" | ")}`,
54
- `type BundledTheme = ${themes.map((theme) => `'${theme.id}'`).join(" | ")}`,
55
- `type Highlighter = HighlighterGeneric<BundledLanguage, BundledTheme>`,
56
- ""
57
- );
58
- typeExports.push("BundledLanguage", "BundledTheme", "Highlighter");
59
- }
60
- lines.push(
61
- "",
62
- `const bundledLanguages = ${langsCode}${ts(" as Record<BundledLanguage, DynamicImportLanguageRegistration>")}`,
63
- "",
64
- `const bundledThemes = ${themesCode}${ts(" as Record<BundledTheme, DynamicImportThemeRegistration>")}`,
65
- ""
66
- );
67
- exports$1.push("bundledLanguages", "bundledThemes");
68
- let engine;
69
- if (options.engine === "javascript") {
70
- imports["@shikijs/engine-javascript"] = ["createJavaScriptRegexEngine"];
71
- engine = "createJavaScriptRegexEngine()";
72
- } else if (options.engine === "javascript-raw") {
73
- imports["@shikijs/engine-javascript/raw"] = ["createJavaScriptRawEngine"];
74
- engine = "createJavaScriptRawEngine()";
75
- } else {
76
- imports["@shikijs/engine-oniguruma"] = ["createOnigurumaEngine"];
77
- engine = "createOnigurumaEngine(import('shiki/wasm'))";
78
- }
79
- lines.push(
80
- "",
81
- `const createHighlighter = /* @__PURE__ */ createBundledHighlighter${ts("<BundledLanguage, BundledTheme>")}({`,
82
- ` langs: bundledLanguages,`,
83
- ` themes: bundledThemes,`,
84
- ` engine: () => ${engine}`,
85
- `})`
86
- );
87
- exports$1.push("createHighlighter");
88
- if (shorthands) {
89
- imports["@shikijs/core"].push("createSingletonShorthands");
90
- const shorthandFunctions = [
91
- "codeToHtml",
92
- "codeToHast",
93
- "codeToTokensBase",
94
- "codeToTokens",
95
- "codeToTokensWithThemes",
96
- "getSingletonHighlighter",
97
- "getLastGrammarState"
98
- ];
99
- lines.push(
100
- "",
101
- `const { ${shorthandFunctions.join(", ")} } = /* @__PURE__ */ createSingletonShorthands${ts("<BundledLanguage,BundledTheme>")}(createHighlighter)`
102
- );
103
- exports$1.push(
104
- ...shorthandFunctions
105
- );
106
- }
107
- lines.unshift(
108
- Object.entries(imports).map(
109
- ([module, imports2]) => {
110
- return `import { ${imports2.sort().join(", ")} } from '${module}'`;
111
- }
112
- ).join("\n")
113
- );
114
- if (typescript) {
115
- lines.unshift(
116
- Object.entries(typeImports).map(
117
- ([module, types]) => {
118
- return `import type { ${types.sort().join(", ")} } from '${module}'`;
119
- }
120
- ).join("\n")
121
- );
122
- }
123
- lines.push(
124
- "",
125
- `export { ${exports$1.sort().join(", ")} }`
126
- );
127
- if (typescript) {
128
- lines.push(
129
- `export type { ${typeExports.sort().join(", ")} }`
130
- );
131
- }
132
- lines.unshift(header);
133
- let code = lines.join("\n");
134
- if (_format) {
135
- const { format } = await import('prettier');
136
- const prettierOptions = {
137
- parser: typescript ? "typescript" : "babel",
138
- semi: false,
139
- tabWidth: 2,
140
- useTabs: false,
141
- singleQuote: true,
142
- trailingComma: "all",
143
- ..._format === true ? {} : _format
144
- };
145
- code = await format(code, prettierOptions);
146
- }
147
- return {
148
- code
149
- };
5
+ const { header = "/* Generate by @shikijs/codegen */", typescript = true, precompiled = false, format: _format = true, shorthands = true } = options;
6
+ const ts = (code) => typescript ? code : "";
7
+ if (precompiled && options.engine !== "javascript" && options.engine !== "javascript-raw") throw new Error("Precompiled grammars are only available when using the JavaScript engine");
8
+ const langs = options.langs.map((lang) => {
9
+ const info = bundledLanguagesInfo.find((i) => i.id === lang || i.aliases?.includes(lang));
10
+ if (!info) throw new Error(`Language ${lang} not found`);
11
+ return info;
12
+ });
13
+ const themes = options.themes.map((theme) => {
14
+ const info = bundledThemesInfo.find((i) => i.id === theme);
15
+ if (!info) throw new Error(`Theme ${theme} not found`);
16
+ return info;
17
+ });
18
+ const langsCode = `{\n${langs.flatMap((lang) => {
19
+ return [lang.id, ...lang.aliases || []].map((id) => {
20
+ return `${JSON.stringify(id)}: () => import('@shikijs/${precompiled ? "langs-precompiled" : "langs"}/${lang.id}'),\n`;
21
+ });
22
+ }).join("")}}`;
23
+ const themesCode = `{\n${themes.map((theme) => {
24
+ return `${JSON.stringify(theme.id)}: () => import('@shikijs/themes/${theme.id}'),\n`;
25
+ }).join("")}}`;
26
+ const typeImports = { "@shikijs/types": [
27
+ "HighlighterGeneric",
28
+ "DynamicImportThemeRegistration",
29
+ "DynamicImportLanguageRegistration"
30
+ ] };
31
+ const imports = { "@shikijs/core": ["createBundledHighlighter"] };
32
+ const lines = [""];
33
+ const exports = [];
34
+ const typeExports = [];
35
+ if (typescript) {
36
+ lines.push("", `type BundledLanguage = ${langs.flatMap((lang) => [lang.id, ...lang.aliases || []]).map((lang) => `'${lang}'`).join(" | ")}`, `type BundledTheme = ${themes.map((theme) => `'${theme.id}'`).join(" | ")}`, `type Highlighter = HighlighterGeneric<BundledLanguage, BundledTheme>`, "");
37
+ typeExports.push("BundledLanguage", "BundledTheme", "Highlighter");
38
+ }
39
+ lines.push("", `const bundledLanguages = ${langsCode}${ts(" as Record<BundledLanguage, DynamicImportLanguageRegistration>")}`, "", `const bundledThemes = ${themesCode}${ts(" as Record<BundledTheme, DynamicImportThemeRegistration>")}`, "");
40
+ exports.push("bundledLanguages", "bundledThemes");
41
+ let engine;
42
+ if (options.engine === "javascript") {
43
+ imports["@shikijs/engine-javascript"] = ["createJavaScriptRegexEngine"];
44
+ engine = "createJavaScriptRegexEngine()";
45
+ } else if (options.engine === "javascript-raw") {
46
+ imports["@shikijs/engine-javascript/raw"] = ["createJavaScriptRawEngine"];
47
+ engine = "createJavaScriptRawEngine()";
48
+ } else {
49
+ imports["@shikijs/engine-oniguruma"] = ["createOnigurumaEngine"];
50
+ engine = "createOnigurumaEngine(import('shiki/wasm'))";
51
+ }
52
+ lines.push("", `const createHighlighter = /* @__PURE__ */ createBundledHighlighter${ts("<BundledLanguage, BundledTheme>")}({`, ` langs: bundledLanguages,`, ` themes: bundledThemes,`, ` engine: () => ${engine}`, `})`);
53
+ exports.push("createHighlighter");
54
+ if (shorthands) {
55
+ imports["@shikijs/core"].push("createSingletonShorthands");
56
+ const shorthandFunctions = [
57
+ "codeToHtml",
58
+ "codeToHast",
59
+ "codeToTokensBase",
60
+ "codeToTokens",
61
+ "codeToTokensWithThemes",
62
+ "getSingletonHighlighter",
63
+ "getLastGrammarState"
64
+ ];
65
+ lines.push("", `const { ${shorthandFunctions.join(", ")} } = /* @__PURE__ */ createSingletonShorthands${ts("<BundledLanguage,BundledTheme>")}(createHighlighter)`);
66
+ exports.push(...shorthandFunctions);
67
+ }
68
+ lines.unshift(Object.entries(imports).map(([module, imports]) => {
69
+ return `import { ${imports.sort().join(", ")} } from '${module}'`;
70
+ }).join("\n"));
71
+ if (typescript) lines.unshift(Object.entries(typeImports).map(([module, types]) => {
72
+ return `import type { ${types.sort().join(", ")} } from '${module}'`;
73
+ }).join("\n"));
74
+ lines.push("", `export { ${exports.sort().join(", ")} }`);
75
+ if (typescript) lines.push(`export type { ${typeExports.sort().join(", ")} }`);
76
+ lines.unshift(header);
77
+ let code = lines.join("\n");
78
+ if (_format) {
79
+ const { format } = await import("prettier");
80
+ const prettierOptions = {
81
+ parser: typescript ? "typescript" : "babel",
82
+ semi: false,
83
+ tabWidth: 2,
84
+ useTabs: false,
85
+ singleQuote: true,
86
+ trailingComma: "all",
87
+ ..._format === true ? {} : _format
88
+ };
89
+ code = await format(code, prettierOptions);
90
+ }
91
+ return { code };
150
92
  }
151
93
 
152
- export { codegen };
94
+ //#endregion
95
+ export { codegen };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "shiki-codegen",
3
3
  "type": "module",
4
- "version": "3.22.0",
4
+ "version": "4.0.0",
5
5
  "description": "Codegen for fine-grained Shiki bundles.",
6
6
  "author": "Anthony Fu <anthonyfu117@hotmail.com>",
7
7
  "license": "MIT",
@@ -31,14 +31,17 @@
31
31
  "bin.mjs",
32
32
  "dist"
33
33
  ],
34
+ "engines": {
35
+ "node": ">=20"
36
+ },
34
37
  "dependencies": {
35
38
  "cac": "^6.7.14",
36
39
  "prettier": "^3.8.1",
37
- "shiki": "3.22.0"
40
+ "shiki": "4.0.0"
38
41
  },
39
42
  "scripts": {
40
- "build": "unbuild",
41
- "dev": "unbuild --stub",
43
+ "build": "tsdown",
44
+ "dev": "tsdown --watch",
42
45
  "test": "vitest"
43
46
  }
44
47
  }