@slidev/cli 0.48.0-beta.17 → 0.48.0-beta.18

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.
@@ -0,0 +1,2101 @@
1
+ import {
2
+ loadSetups
3
+ } from "./chunk-O6TYYGU6.mjs";
4
+ import {
5
+ resolveImportPath,
6
+ toAtFS
7
+ } from "./chunk-NOI2WLJK.mjs";
8
+
9
+ // package.json
10
+ var version = "0.48.0-beta.18";
11
+
12
+ // node/common.ts
13
+ import { existsSync, promises as fs } from "node:fs";
14
+ import { join } from "node:path";
15
+ import { loadConfigFromFile, mergeConfig, resolveConfig } from "vite";
16
+
17
+ // node/utils.ts
18
+ import { satisfies } from "semver";
19
+ function stringifyMarkdownTokens(tokens) {
20
+ return tokens.map((token) => token.children?.filter((t) => ["text", "code_inline"].includes(t.type) && !t.content.match(/^\s*$/)).map((t) => t.content.trim()).join(" ")).filter(Boolean).join(" ");
21
+ }
22
+ function generateGoogleFontsUrl(options) {
23
+ const weights = options.weights.flatMap((i) => options.italic ? [`0,${i}`, `1,${i}`] : [`${i}`]).sort().join(";");
24
+ const fonts = options.webfonts.map((i) => `family=${i.replace(/^(['"])(.*)\1$/, "$1").replace(/\s+/g, "+")}:${options.italic ? "ital," : ""}wght@${weights}`).join("&");
25
+ return `https://fonts.googleapis.com/css2?${fonts}&display=swap`;
26
+ }
27
+ function checkEngine(name, engines = {}) {
28
+ if (engines.slidev && !satisfies(version, engines.slidev, { includePrerelease: true }))
29
+ throw new Error(`[slidev] addon "${name}" requires Slidev version range "${engines.slidev}" but found "${version}"`);
30
+ }
31
+
32
+ // node/common.ts
33
+ async function getIndexHtml({ clientRoot, roots, data }) {
34
+ let main = await fs.readFile(join(clientRoot, "index.html"), "utf-8");
35
+ let head = "";
36
+ let body = "";
37
+ head += `<link rel="icon" href="${data.config.favicon}">`;
38
+ for (const root of roots) {
39
+ const path2 = join(root, "index.html");
40
+ if (!existsSync(path2))
41
+ continue;
42
+ const index = await fs.readFile(path2, "utf-8");
43
+ head += `
44
+ ${(index.match(/<head>([\s\S]*?)<\/head>/im)?.[1] || "").trim()}`;
45
+ body += `
46
+ ${(index.match(/<body>([\s\S]*?)<\/body>/im)?.[1] || "").trim()}`;
47
+ }
48
+ if (data.features.tweet)
49
+ body += '\n<script async src="https://platform.twitter.com/widgets.js"></script>';
50
+ if (data.config.fonts.webfonts.length && data.config.fonts.provider !== "none")
51
+ head += `
52
+ <link rel="stylesheet" href="${generateGoogleFontsUrl(data.config.fonts)}" type="text/css">`;
53
+ main = main.replace("__ENTRY__", toAtFS(join(clientRoot, "main.ts"))).replace("<!-- head -->", head).replace("<!-- body -->", body);
54
+ return main;
55
+ }
56
+ async function mergeViteConfigs({ roots, entry }, viteConfig, config, command) {
57
+ const configEnv = {
58
+ mode: "development",
59
+ command
60
+ };
61
+ const files = roots.map((i) => join(i, "vite.config.ts"));
62
+ for await (const file of files) {
63
+ if (!existsSync(file))
64
+ continue;
65
+ const viteConfig2 = await loadConfigFromFile(configEnv, file);
66
+ if (!viteConfig2?.config)
67
+ continue;
68
+ config = mergeConfig(config, viteConfig2.config);
69
+ }
70
+ config = mergeConfig(config, viteConfig);
71
+ const localConfig = await resolveConfig({}, command, entry);
72
+ config = mergeConfig(config, { slidev: localConfig.slidev || {} });
73
+ return config;
74
+ }
75
+
76
+ // node/plugins/preset.ts
77
+ import { join as join6 } from "node:path";
78
+ import { existsSync as existsSync3 } from "node:fs";
79
+ import process from "node:process";
80
+ import { fileURLToPath } from "node:url";
81
+ import Vue from "@vitejs/plugin-vue";
82
+ import VueJsx from "@vitejs/plugin-vue-jsx";
83
+ import Icons from "unplugin-icons/vite";
84
+ import IconsResolver from "unplugin-icons/resolver";
85
+ import Components from "unplugin-vue-components/vite";
86
+ import ServerRef from "vite-plugin-vue-server-ref";
87
+ import { notNullish as notNullish2 } from "@antfu/utils";
88
+
89
+ // node/drawings.ts
90
+ import { basename, dirname, join as join2, resolve } from "node:path";
91
+ import fs2 from "fs-extra";
92
+ import fg from "fast-glob";
93
+ function resolveDrawingsDir(options) {
94
+ return options.data.config.drawings.persist ? resolve(
95
+ dirname(options.entry),
96
+ options.data.config.drawings.persist
97
+ ) : void 0;
98
+ }
99
+ async function loadDrawings(options) {
100
+ const dir = resolveDrawingsDir(options);
101
+ if (!dir || !fs2.existsSync(dir))
102
+ return {};
103
+ const files = await fg("*.svg", {
104
+ onlyFiles: true,
105
+ cwd: dir,
106
+ absolute: true,
107
+ suppressErrors: true
108
+ });
109
+ const obj = {};
110
+ await Promise.all(files.map(async (path2) => {
111
+ const num = +basename(path2, ".svg");
112
+ if (Number.isNaN(num))
113
+ return;
114
+ const content = await fs2.readFile(path2, "utf8");
115
+ const lines = content.split(/\n/g);
116
+ obj[num.toString()] = lines.slice(1, -1).join("\n");
117
+ }));
118
+ return obj;
119
+ }
120
+ async function writeDrawings(options, drawing) {
121
+ const dir = resolveDrawingsDir(options);
122
+ if (!dir)
123
+ return;
124
+ const width = options.data.config.canvasWidth;
125
+ const height = Math.round(width / options.data.config.aspectRatio);
126
+ const SVG_HEAD = `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">`;
127
+ await fs2.ensureDir(dir);
128
+ return Promise.all(
129
+ Object.entries(drawing).map(async ([key, value]) => {
130
+ if (!value)
131
+ return;
132
+ const svg = `${SVG_HEAD}
133
+ ${value}
134
+ </svg>`;
135
+ await fs2.writeFile(join2(dir, `${key}.svg`), svg, "utf-8");
136
+ })
137
+ );
138
+ }
139
+
140
+ // node/plugins/extendConfig.ts
141
+ import { join as join3 } from "node:path";
142
+ import { mergeConfig as mergeConfig2 } from "vite";
143
+ import isInstalledGlobally from "is-installed-globally";
144
+ import { uniq } from "@antfu/utils";
145
+
146
+ // ../client/package.json
147
+ var dependencies = {
148
+ "@antfu/utils": "^0.7.7",
149
+ "@iconify-json/carbon": "^1.1.30",
150
+ "@iconify-json/ph": "^1.1.11",
151
+ "@shikijs/monaco": "^1.1.7",
152
+ "@shikijs/vitepress-twoslash": "^1.1.7",
153
+ "@slidev/parser": "workspace:*",
154
+ "@slidev/rough-notation": "^0.1.0",
155
+ "@slidev/types": "workspace:*",
156
+ "@typescript/ata": "^0.9.4",
157
+ "@unhead/vue": "^1.8.10",
158
+ "@unocss/reset": "^0.58.5",
159
+ "@vueuse/core": "^10.8.0",
160
+ "@vueuse/math": "^10.8.0",
161
+ "@vueuse/motion": "^2.1.0",
162
+ codemirror: "^5.65.16",
163
+ drauu: "^0.4.0",
164
+ "file-saver": "^2.0.5",
165
+ "floating-vue": "^5.2.2",
166
+ "fuse.js": "^7.0.0",
167
+ "js-yaml": "^4.1.0",
168
+ katex: "^0.16.9",
169
+ "lz-string": "^1.5.0",
170
+ mermaid: "^10.8.0",
171
+ "monaco-editor": "^0.46.0",
172
+ prettier: "^3.2.5",
173
+ recordrtc: "^5.6.2",
174
+ shiki: "^1.1.7",
175
+ "shiki-magic-move": "^0.1.0",
176
+ unocss: "^0.58.5",
177
+ vue: "^3.4.20",
178
+ "vue-router": "^4.3.0"
179
+ };
180
+
181
+ // node/plugins/extendConfig.ts
182
+ var EXCLUDE = [
183
+ "@slidev/shared",
184
+ "@slidev/types",
185
+ "@slidev/client",
186
+ "@slidev/client/constants",
187
+ "@slidev/client/logic/dark",
188
+ "@vueuse/core",
189
+ "@vueuse/shared",
190
+ "@unocss/reset",
191
+ "unocss",
192
+ "mermaid",
193
+ "vue-demi",
194
+ "vue",
195
+ "shiki"
196
+ ];
197
+ var ASYNC_MODULES = [
198
+ "file-saver",
199
+ "vue",
200
+ "@vue"
201
+ ];
202
+ function createConfigPlugin(options) {
203
+ return {
204
+ name: "slidev:config",
205
+ async config(config) {
206
+ const injection = {
207
+ define: getDefine(options),
208
+ resolve: {
209
+ alias: {
210
+ "@slidev/client/": `${toAtFS(options.clientRoot)}/`,
211
+ "#slidev/": "/@slidev/",
212
+ "vue": await resolveImportPath("vue/dist/vue.esm-browser.js", true)
213
+ },
214
+ dedupe: ["vue"]
215
+ },
216
+ optimizeDeps: {
217
+ exclude: EXCLUDE,
218
+ include: Object.keys(dependencies).filter((i) => !EXCLUDE.includes(i)).map((i) => `@slidev/cli > @slidev/client > ${i}`)
219
+ },
220
+ css: options.data.config.css === "unocss" ? {
221
+ postcss: {
222
+ plugins: [
223
+ await import("postcss-nested").then((r) => (r.default || r)())
224
+ ]
225
+ }
226
+ } : {},
227
+ server: {
228
+ fs: {
229
+ strict: true,
230
+ allow: uniq([
231
+ options.userWorkspaceRoot,
232
+ options.cliRoot,
233
+ options.clientRoot,
234
+ ...options.roots
235
+ ])
236
+ }
237
+ },
238
+ publicDir: join3(options.userRoot, "public"),
239
+ build: {
240
+ rollupOptions: {
241
+ output: {
242
+ chunkFileNames(chunkInfo) {
243
+ const DEFAULT = "assets/[name]-[hash].js";
244
+ if (chunkInfo.name.includes("/"))
245
+ return DEFAULT;
246
+ if (chunkInfo.moduleIds.filter((i) => isSlidevClient(i)).length > chunkInfo.moduleIds.length * 0.6)
247
+ return "assets/slidev/[name]-[hash].js";
248
+ if (chunkInfo.moduleIds.filter((i) => i.match(/\/monaco-editor(-core)?\//)).length > chunkInfo.moduleIds.length * 0.6)
249
+ return "assets/monaco/[name]-[hash].js";
250
+ return DEFAULT;
251
+ },
252
+ manualChunks(id) {
253
+ if (id.startsWith("/@slidev-monaco-types/") || id.includes("/@slidev/monaco-types") || id.endsWith("?monaco-types&raw"))
254
+ return "monaco/bundled-types";
255
+ if (id.includes("/shiki/") || id.includes("/@shikijs/"))
256
+ return `modules/shiki`;
257
+ if (id.startsWith("~icons/"))
258
+ return "modules/unplugin-icons";
259
+ const matchedAsyncModule = ASYNC_MODULES.find((i) => id.includes(`/node_modules/${i}`));
260
+ if (matchedAsyncModule)
261
+ return `modules/${matchedAsyncModule.replace("@", "").replace("/", "-")}`;
262
+ }
263
+ }
264
+ }
265
+ }
266
+ };
267
+ function isSlidevClient(id) {
268
+ return id.includes("/@slidev/") || id.includes("/slidev/packages/client/") || id.includes("/@vueuse/");
269
+ }
270
+ if (isInstalledGlobally) {
271
+ injection.cacheDir = join3(options.cliRoot, "node_modules/.vite");
272
+ injection.root = options.cliRoot;
273
+ }
274
+ return mergeConfig2(injection, config);
275
+ },
276
+ configureServer(server) {
277
+ return () => {
278
+ server.middlewares.use(async (req, res, next) => {
279
+ if (req.url.endsWith(".html")) {
280
+ res.setHeader("Content-Type", "text/html");
281
+ res.statusCode = 200;
282
+ res.end(await getIndexHtml(options));
283
+ return;
284
+ }
285
+ next();
286
+ });
287
+ };
288
+ }
289
+ };
290
+ }
291
+ function getDefine(options) {
292
+ return {
293
+ __DEV__: options.mode === "dev" ? "true" : "false",
294
+ __SLIDEV_CLIENT_ROOT__: JSON.stringify(toAtFS(options.clientRoot)),
295
+ __SLIDEV_HASH_ROUTE__: JSON.stringify(options.data.config.routerMode === "hash"),
296
+ __SLIDEV_FEATURE_DRAWINGS__: JSON.stringify(options.data.config.drawings.enabled === true || options.data.config.drawings.enabled === options.mode),
297
+ __SLIDEV_FEATURE_EDITOR__: JSON.stringify(options.mode === "dev" && options.data.config.editor !== false),
298
+ __SLIDEV_FEATURE_DRAWINGS_PERSIST__: JSON.stringify(!!options.data.config.drawings.persist === true),
299
+ __SLIDEV_FEATURE_RECORD__: JSON.stringify(options.data.config.record === true || options.data.config.record === options.mode),
300
+ __SLIDEV_FEATURE_PRESENTER__: JSON.stringify(options.data.config.presenter === true || options.data.config.presenter === options.mode),
301
+ __SLIDEV_HAS_SERVER__: options.mode !== "build" ? "true" : "false"
302
+ };
303
+ }
304
+
305
+ // node/plugins/loaders.ts
306
+ import { basename as basename2, join as join4, resolve as resolve2 } from "node:path";
307
+ import { builtinModules } from "node:module";
308
+ import { isString, isTruthy as isTruthy2, notNullish, objectMap, range, uniq as uniq2 } from "@antfu/utils";
309
+ import fg2 from "fast-glob";
310
+ import fs5 from "fs-extra";
311
+ import Markdown2 from "markdown-it";
312
+ import { bold, gray, red, yellow } from "kolorist";
313
+ import mila2 from "markdown-it-link-attributes";
314
+ import * as parser from "@slidev/parser/fs";
315
+ import equal from "fast-deep-equal";
316
+
317
+ // node/plugins/markdown.ts
318
+ import fs4 from "node:fs/promises";
319
+ import Markdown from "unplugin-vue-markdown/vite";
320
+ import { isTruthy, slash } from "@antfu/utils";
321
+
322
+ // ../../node_modules/.pnpm/@hedgedoc+markdown-it-plugins@2.1.4_patch_hash=tuyuxytl56b2vxulpkzt2wf4o4_markdown-it@14.0.0/node_modules/@hedgedoc/markdown-it-plugins/dist/esm/image-size/specialCharacters.js
323
+ var SpecialCharacters;
324
+ (function(SpecialCharacters2) {
325
+ SpecialCharacters2[SpecialCharacters2["EXCLAMATION_MARK"] = 33] = "EXCLAMATION_MARK";
326
+ SpecialCharacters2[SpecialCharacters2["OPENING_BRACKET"] = 91] = "OPENING_BRACKET";
327
+ SpecialCharacters2[SpecialCharacters2["OPENING_PARENTHESIS"] = 40] = "OPENING_PARENTHESIS";
328
+ SpecialCharacters2[SpecialCharacters2["WHITESPACE"] = 32] = "WHITESPACE";
329
+ SpecialCharacters2[SpecialCharacters2["NEW_LINE"] = 10] = "NEW_LINE";
330
+ SpecialCharacters2[SpecialCharacters2["EQUALS"] = 61] = "EQUALS";
331
+ SpecialCharacters2[SpecialCharacters2["LOWER_CASE_X"] = 120] = "LOWER_CASE_X";
332
+ SpecialCharacters2[SpecialCharacters2["NUMBER_ZERO"] = 48] = "NUMBER_ZERO";
333
+ SpecialCharacters2[SpecialCharacters2["NUMBER_NINE"] = 57] = "NUMBER_NINE";
334
+ SpecialCharacters2[SpecialCharacters2["PERCENTAGE"] = 37] = "PERCENTAGE";
335
+ SpecialCharacters2[SpecialCharacters2["CLOSING_PARENTHESIS"] = 41] = "CLOSING_PARENTHESIS";
336
+ })(SpecialCharacters || (SpecialCharacters = {}));
337
+
338
+ // ../../node_modules/.pnpm/@hedgedoc+markdown-it-plugins@2.1.4_patch_hash=tuyuxytl56b2vxulpkzt2wf4o4_markdown-it@14.0.0/node_modules/@hedgedoc/markdown-it-plugins/dist/esm/task-lists/index.js
339
+ import Token from "markdown-it/lib/token.mjs";
340
+ var checkboxRegex = /^ *\[([\sx])] /i;
341
+ function taskLists(md2, options = { enabled: false, label: false, lineNumber: false }) {
342
+ md2.core.ruler.after("inline", "task-lists", (state) => processToken(state, options));
343
+ md2.renderer.rules.taskListItemCheckbox = (tokens) => {
344
+ const token = tokens[0];
345
+ const checkedAttribute = token.attrGet("checked") ? 'checked="" ' : "";
346
+ const disabledAttribute = token.attrGet("disabled") ? 'disabled="" ' : "";
347
+ const line = token.attrGet("line");
348
+ const idAttribute = `id="${token.attrGet("id")}" `;
349
+ const dataLineAttribute = line && options.lineNumber ? `data-line="${line}" ` : "";
350
+ return `<input class="task-list-item-checkbox" type="checkbox" ${checkedAttribute}${disabledAttribute}${dataLineAttribute}${idAttribute}/>`;
351
+ };
352
+ md2.renderer.rules.taskListItemLabel_close = () => {
353
+ return "</label>";
354
+ };
355
+ md2.renderer.rules.taskListItemLabel_open = (tokens) => {
356
+ const token = tokens[0];
357
+ const id = token.attrGet("id");
358
+ return `<label for="${id}">`;
359
+ };
360
+ }
361
+ function processToken(state, options) {
362
+ const allTokens = state.tokens;
363
+ for (let i = 2; i < allTokens.length; i++) {
364
+ if (!isTodoItem(allTokens, i)) {
365
+ continue;
366
+ }
367
+ todoify(allTokens[i], options);
368
+ allTokens[i - 2].attrJoin("class", `task-list-item ${options.enabled ? " enabled" : ""}`);
369
+ const parentToken = findParentToken(allTokens, i - 2);
370
+ if (parentToken) {
371
+ const classes = parentToken.attrGet("class") ?? "";
372
+ if (!classes.match(/(^| )contains-task-list/)) {
373
+ parentToken.attrJoin("class", "contains-task-list");
374
+ }
375
+ }
376
+ }
377
+ return false;
378
+ }
379
+ function findParentToken(tokens, index) {
380
+ const targetLevel = tokens[index].level - 1;
381
+ for (let currentTokenIndex = index - 1; currentTokenIndex >= 0; currentTokenIndex--) {
382
+ if (tokens[currentTokenIndex].level === targetLevel) {
383
+ return tokens[currentTokenIndex];
384
+ }
385
+ }
386
+ return void 0;
387
+ }
388
+ function isTodoItem(tokens, index) {
389
+ return isInline(tokens[index]) && isParagraph(tokens[index - 1]) && isListItem(tokens[index - 2]) && startsWithTodoMarkdown(tokens[index]);
390
+ }
391
+ function todoify(token, options) {
392
+ if (token.children == null) {
393
+ return;
394
+ }
395
+ const id = generateIdForToken(token);
396
+ token.children.splice(0, 0, createCheckboxToken(token, options.enabled, id));
397
+ token.children[1].content = token.children[1].content.replace(checkboxRegex, "");
398
+ if (options.label) {
399
+ token.children.splice(1, 0, createLabelBeginToken(id));
400
+ token.children.push(createLabelEndToken());
401
+ }
402
+ }
403
+ function generateIdForToken(token) {
404
+ if (token.map) {
405
+ return `task-item-${token.map[0]}`;
406
+ } else {
407
+ return `task-item-${Math.ceil(Math.random() * (1e4 * 1e3) - 1e3)}`;
408
+ }
409
+ }
410
+ function createCheckboxToken(token, enabled, id) {
411
+ const checkbox = new Token("taskListItemCheckbox", "", 0);
412
+ if (!enabled) {
413
+ checkbox.attrSet("disabled", "true");
414
+ }
415
+ if (token.map) {
416
+ checkbox.attrSet("line", token.map[0].toString());
417
+ }
418
+ checkbox.attrSet("id", id);
419
+ const checkboxRegexResult = checkboxRegex.exec(token.content);
420
+ const isChecked = checkboxRegexResult?.[1].toLowerCase() === "x";
421
+ if (isChecked) {
422
+ checkbox.attrSet("checked", "true");
423
+ }
424
+ return checkbox;
425
+ }
426
+ function createLabelBeginToken(id) {
427
+ const labelBeginToken = new Token("taskListItemLabel_open", "", 1);
428
+ labelBeginToken.attrSet("id", id);
429
+ return labelBeginToken;
430
+ }
431
+ function createLabelEndToken() {
432
+ return new Token("taskListItemLabel_close", "", -1);
433
+ }
434
+ function isInline(token) {
435
+ return token.type === "inline";
436
+ }
437
+ function isParagraph(token) {
438
+ return token.type === "paragraph_open";
439
+ }
440
+ function isListItem(token) {
441
+ return token.type === "list_item_open";
442
+ }
443
+ function startsWithTodoMarkdown(token) {
444
+ return checkboxRegex.test(token.content);
445
+ }
446
+
447
+ // ../../node_modules/.pnpm/@hedgedoc+markdown-it-plugins@2.1.4_patch_hash=tuyuxytl56b2vxulpkzt2wf4o4_markdown-it@14.0.0/node_modules/@hedgedoc/markdown-it-plugins/dist/esm/toc/plugin.js
448
+ import { Optional } from "@mrdrogdrog/optional";
449
+
450
+ // node/plugins/markdown.ts
451
+ import { encode as encodePlantUml } from "plantuml-encoder";
452
+ import Mdc from "markdown-it-mdc";
453
+ import { codeToKeyedTokens, createMagicMoveMachine } from "shiki-magic-move/core";
454
+ import mila from "markdown-it-link-attributes";
455
+ import mif from "markdown-it-footnote";
456
+ import lz from "lz-string";
457
+
458
+ // node/plugins/markdown-it-katex.ts
459
+ import katex from "katex";
460
+ function isValidDelim(state, pos) {
461
+ const max = state.posMax;
462
+ let can_open = true;
463
+ let can_close = true;
464
+ const prevChar = pos > 0 ? state.src.charCodeAt(pos - 1) : -1;
465
+ const nextChar = pos + 1 <= max ? state.src.charCodeAt(pos + 1) : -1;
466
+ if (prevChar === 32 || prevChar === 9 || /* \t */
467
+ nextChar >= 48 && nextChar <= 57)
468
+ can_close = false;
469
+ if (nextChar === 32 || nextChar === 9)
470
+ can_open = false;
471
+ return {
472
+ can_open,
473
+ can_close
474
+ };
475
+ }
476
+ function math_inline(state, silent) {
477
+ let match, token, res, pos;
478
+ if (state.src[state.pos] !== "$")
479
+ return false;
480
+ res = isValidDelim(state, state.pos);
481
+ if (!res.can_open) {
482
+ if (!silent)
483
+ state.pending += "$";
484
+ state.pos += 1;
485
+ return true;
486
+ }
487
+ const start = state.pos + 1;
488
+ match = start;
489
+ while ((match = state.src.indexOf("$", match)) !== -1) {
490
+ pos = match - 1;
491
+ while (state.src[pos] === "\\")
492
+ pos -= 1;
493
+ if ((match - pos) % 2 === 1)
494
+ break;
495
+ match += 1;
496
+ }
497
+ if (match === -1) {
498
+ if (!silent)
499
+ state.pending += "$";
500
+ state.pos = start;
501
+ return true;
502
+ }
503
+ if (match - start === 0) {
504
+ if (!silent)
505
+ state.pending += "$$";
506
+ state.pos = start + 1;
507
+ return true;
508
+ }
509
+ res = isValidDelim(state, match);
510
+ if (!res.can_close) {
511
+ if (!silent)
512
+ state.pending += "$";
513
+ state.pos = start;
514
+ return true;
515
+ }
516
+ if (!silent) {
517
+ token = state.push("math_inline", "math", 0);
518
+ token.markup = "$";
519
+ token.content = state.src.slice(start, match);
520
+ }
521
+ state.pos = match + 1;
522
+ return true;
523
+ }
524
+ function math_block(state, start, end, silent) {
525
+ let firstLine;
526
+ let lastLine;
527
+ let next;
528
+ let lastPos;
529
+ let found = false;
530
+ let pos = state.bMarks[start] + state.tShift[start];
531
+ let max = state.eMarks[start];
532
+ if (pos + 2 > max)
533
+ return false;
534
+ if (state.src.slice(pos, pos + 2) !== "$$")
535
+ return false;
536
+ pos += 2;
537
+ firstLine = state.src.slice(pos, max);
538
+ if (silent)
539
+ return true;
540
+ if (firstLine.trim().slice(-2) === "$$") {
541
+ firstLine = firstLine.trim().slice(0, -2);
542
+ found = true;
543
+ }
544
+ for (next = start; !found; ) {
545
+ next++;
546
+ if (next >= end)
547
+ break;
548
+ pos = state.bMarks[next] + state.tShift[next];
549
+ max = state.eMarks[next];
550
+ if (pos < max && state.tShift[next] < state.blkIndent) {
551
+ break;
552
+ }
553
+ if (state.src.slice(pos, max).trim().slice(-2) === "$$") {
554
+ lastPos = state.src.slice(0, max).lastIndexOf("$$");
555
+ lastLine = state.src.slice(pos, lastPos);
556
+ found = true;
557
+ }
558
+ }
559
+ state.line = next + 1;
560
+ const token = state.push("math_block", "math", 0);
561
+ token.block = true;
562
+ token.content = (firstLine && firstLine.trim() ? `${firstLine}
563
+ ` : "") + state.getLines(start + 1, next, state.tShift[start], true) + (lastLine && lastLine.trim() ? lastLine : "");
564
+ token.map = [start, state.line];
565
+ token.markup = "$$";
566
+ return true;
567
+ }
568
+ function math_plugin(md2, options) {
569
+ options = options || {};
570
+ const katexInline = function(latex) {
571
+ options.displayMode = false;
572
+ try {
573
+ return katex.renderToString(latex, options);
574
+ } catch (error) {
575
+ if (options.throwOnError)
576
+ console.warn(error);
577
+ return latex;
578
+ }
579
+ };
580
+ const inlineRenderer = function(tokens, idx) {
581
+ return katexInline(tokens[idx].content);
582
+ };
583
+ const katexBlock = function(latex) {
584
+ options.displayMode = true;
585
+ try {
586
+ return `<p>${katex.renderToString(latex, options)}</p>`;
587
+ } catch (error) {
588
+ if (options.throwOnError)
589
+ console.warn(error);
590
+ return latex;
591
+ }
592
+ };
593
+ const blockRenderer = function(tokens, idx) {
594
+ return `${katexBlock(tokens[idx].content)}
595
+ `;
596
+ };
597
+ md2.inline.ruler.after("escape", "math_inline", math_inline);
598
+ md2.block.ruler.after("blockquote", "math_block", math_block, {
599
+ alt: ["paragraph", "reference", "blockquote", "list"]
600
+ });
601
+ md2.renderer.rules.math_inline = inlineRenderer;
602
+ md2.renderer.rules.math_block = blockRenderer;
603
+ }
604
+
605
+ // node/plugins/markdown-it-prism.ts
606
+ import { createRequire } from "node:module";
607
+ import Prism from "prismjs";
608
+ import loadLanguages from "prismjs/components/index.js";
609
+ import * as htmlparser2 from "htmlparser2";
610
+ var require2 = createRequire(import.meta.url);
611
+ var Tag = class {
612
+ tagname;
613
+ attributes;
614
+ constructor(tagname, attributes) {
615
+ this.tagname = tagname;
616
+ this.attributes = attributes;
617
+ }
618
+ asOpen() {
619
+ return `<${this.tagname} ${Object.entries(this.attributes).map(([key, value]) => `${key}="${value}"`).join(" ")}>`;
620
+ }
621
+ asClosed() {
622
+ return `</${this.tagname}>`;
623
+ }
624
+ };
625
+ var DEFAULTS = {
626
+ plugins: [],
627
+ init: () => {
628
+ },
629
+ defaultLanguageForUnknown: void 0,
630
+ defaultLanguageForUnspecified: void 0,
631
+ defaultLanguage: void 0
632
+ };
633
+ function loadPrismLang(lang) {
634
+ if (!lang)
635
+ return void 0;
636
+ let langObject = Prism.languages[lang];
637
+ if (langObject === void 0) {
638
+ loadLanguages([lang]);
639
+ langObject = Prism.languages[lang];
640
+ }
641
+ return langObject;
642
+ }
643
+ function loadPrismPlugin(name) {
644
+ try {
645
+ require2(`prismjs/plugins/${name}/prism-${name}`);
646
+ } catch (e) {
647
+ throw new Error(`Cannot load Prism plugin "${name}". Please check the spelling.`);
648
+ }
649
+ }
650
+ function selectLanguage(options, lang) {
651
+ let langToUse = lang;
652
+ if (langToUse === "" && options.defaultLanguageForUnspecified !== void 0)
653
+ langToUse = options.defaultLanguageForUnspecified;
654
+ let prismLang = loadPrismLang(langToUse);
655
+ if (prismLang === void 0 && options.defaultLanguageForUnknown !== void 0) {
656
+ langToUse = options.defaultLanguageForUnknown;
657
+ prismLang = loadPrismLang(langToUse);
658
+ }
659
+ return [langToUse, prismLang];
660
+ }
661
+ function highlight(markdownit, options, text, lang) {
662
+ const [langToUse, prismLang] = selectLanguage(options, lang);
663
+ let code = text.trimEnd();
664
+ code = prismLang ? highlightPrism(code, prismLang, langToUse) : markdownit.utils.escapeHtml(code);
665
+ code = code.split(/\r?\n/g).map((line) => `<span class="line">${line}</span>`).join("\n");
666
+ const classAttribute = langToUse ? ` class="slidev-code ${markdownit.options.langPrefix}${markdownit.utils.escapeHtml(langToUse)}"` : "";
667
+ return escapeVueInCode(`<pre${classAttribute}><code>${code}</code></pre>`);
668
+ }
669
+ function highlightPrism(code, prismLang, langToUse) {
670
+ const openTags = [];
671
+ const parser2 = new htmlparser2.Parser({
672
+ onopentag(tagname, attributes) {
673
+ openTags.push(new Tag(tagname, attributes));
674
+ },
675
+ onclosetag() {
676
+ openTags.pop();
677
+ }
678
+ });
679
+ code = Prism.highlight(code, prismLang, langToUse);
680
+ code = code.split(/\r?\n/g).map((line) => {
681
+ const prefix = openTags.map((tag) => tag.asOpen()).join("");
682
+ parser2.write(line);
683
+ const postfix = openTags.reverse().map((tag) => tag.asClosed()).join("");
684
+ return prefix + line + postfix;
685
+ }).join("\n");
686
+ parser2.end();
687
+ return code;
688
+ }
689
+ function checkLanguageOption(options, optionName) {
690
+ const language = options[optionName];
691
+ if (language !== void 0 && loadPrismLang(language) === void 0)
692
+ throw new Error(`Bad option ${optionName}: There is no Prism language '${language}'.`);
693
+ }
694
+ function markdownItPrism(markdownit, useroptions) {
695
+ const options = Object.assign({}, DEFAULTS, useroptions);
696
+ checkLanguageOption(options, "defaultLanguage");
697
+ checkLanguageOption(options, "defaultLanguageForUnknown");
698
+ checkLanguageOption(options, "defaultLanguageForUnspecified");
699
+ options.defaultLanguageForUnknown = options.defaultLanguageForUnknown || options.defaultLanguage;
700
+ options.defaultLanguageForUnspecified = options.defaultLanguageForUnspecified || options.defaultLanguage;
701
+ options.plugins.forEach(loadPrismPlugin);
702
+ options.init(Prism);
703
+ markdownit.options.highlight = (text, lang) => highlight(markdownit, options, text, lang);
704
+ }
705
+
706
+ // node/plugins/transformSnippet.ts
707
+ import path from "node:path";
708
+ import fs3 from "fs-extra";
709
+ function dedent(text) {
710
+ const lines = text.split("\n");
711
+ const minIndentLength = lines.reduce((acc, line) => {
712
+ for (let i = 0; i < line.length; i++) {
713
+ if (line[i] !== " " && line[i] !== " ")
714
+ return Math.min(i, acc);
715
+ }
716
+ return acc;
717
+ }, Number.POSITIVE_INFINITY);
718
+ if (minIndentLength < Number.POSITIVE_INFINITY)
719
+ return lines.map((x) => x.slice(minIndentLength)).join("\n");
720
+ return text;
721
+ }
722
+ function testLine(line, regexp, regionName, end = false) {
723
+ const [full, tag, name] = regexp.exec(line.trim()) || [];
724
+ return full && tag && name === regionName && tag.match(end ? /^[Ee]nd ?[rR]egion$/ : /^[rR]egion$/);
725
+ }
726
+ function findRegion(lines, regionName) {
727
+ const regionRegexps = [
728
+ /^\/\/ ?#?((?:end)?region) ([\w*-]+)$/,
729
+ // javascript, typescript, java
730
+ /^\/\* ?#((?:end)?region) ([\w*-]+) ?\*\/$/,
731
+ // css, less, scss
732
+ /^#pragma ((?:end)?region) ([\w*-]+)$/,
733
+ // C, C++
734
+ /^<!-- #?((?:end)?region) ([\w*-]+) -->$/,
735
+ // HTML, markdown
736
+ /^#((?:End )Region) ([\w*-]+)$/,
737
+ // Visual Basic
738
+ /^::#((?:end)region) ([\w*-]+)$/,
739
+ // Bat
740
+ /^# ?((?:end)?region) ([\w*-]+)$/
741
+ // C#, PHP, Powershell, Python, perl & misc
742
+ ];
743
+ let regexp = null;
744
+ let start = -1;
745
+ for (const [lineId, line] of lines.entries()) {
746
+ if (regexp === null) {
747
+ for (const reg of regionRegexps) {
748
+ if (testLine(line, reg, regionName)) {
749
+ start = lineId + 1;
750
+ regexp = reg;
751
+ break;
752
+ }
753
+ }
754
+ } else if (testLine(line, regexp, regionName, true)) {
755
+ return { start, end: lineId, regexp };
756
+ }
757
+ }
758
+ return null;
759
+ }
760
+ function transformSnippet(md2, options, id) {
761
+ const slideId = id.match(/(\d+)\.md$/)?.[1];
762
+ if (!slideId)
763
+ return md2;
764
+ const data = options.data;
765
+ const slideInfo = data.slides[+slideId - 1];
766
+ const dir = path.dirname(slideInfo.source?.filepath ?? options.entry ?? options.userRoot);
767
+ return md2.replace(
768
+ /^<<< *(.+?)(#[\w-]+)? *(?: (\S+?))? *(\{.*)?$/mg,
769
+ (full, filepath = "", regionName = "", lang = "", meta = "") => {
770
+ const firstLine = `\`\`\`${lang || path.extname(filepath).slice(1)} ${meta}`;
771
+ const src = /^\@[\/]/.test(filepath) ? path.resolve(options.userRoot, filepath.slice(2)) : path.resolve(dir, filepath);
772
+ data.watchFiles.push(src);
773
+ const isAFile = fs3.statSync(src).isFile();
774
+ if (!fs3.existsSync(src) || !isAFile) {
775
+ throw new Error(isAFile ? `Code snippet path not found: ${src}` : `Invalid code snippet option`);
776
+ }
777
+ let content = fs3.readFileSync(src, "utf8");
778
+ slideInfo.snippetsUsed ??= {};
779
+ slideInfo.snippetsUsed[src] = content;
780
+ if (regionName) {
781
+ const lines = content.split(/\r?\n/);
782
+ const region = findRegion(lines, regionName.slice(1));
783
+ if (region) {
784
+ content = dedent(
785
+ lines.slice(region.start, region.end).filter((line) => !region.regexp.test(line.trim())).join("\n")
786
+ );
787
+ }
788
+ }
789
+ return `${firstLine}
790
+ ${content}
791
+ \`\`\``;
792
+ }
793
+ );
794
+ }
795
+
796
+ // node/plugins/markdown.ts
797
+ var shiki;
798
+ var shikiOptions;
799
+ async function createMarkdownPlugin(options, { markdown: mdOptions }) {
800
+ const { data: { config }, roots, mode, entry, clientRoot } = options;
801
+ const setups = [];
802
+ const entryPath = slash(entry);
803
+ if (config.highlighter === "shiki") {
804
+ const [
805
+ options2,
806
+ { getHighlighter, bundledLanguages },
807
+ markdownItShiki,
808
+ transformerTwoslash
809
+ ] = await Promise.all([
810
+ loadShikiSetups(clientRoot, roots),
811
+ import("shiki").then(({ getHighlighter: getHighlighter2, bundledLanguages: bundledLanguages2 }) => ({ bundledLanguages: bundledLanguages2, getHighlighter: getHighlighter2 })),
812
+ import("@shikijs/markdown-it/core").then(({ fromHighlighter }) => fromHighlighter),
813
+ import("@shikijs/vitepress-twoslash").then(({ transformerTwoslash: transformerTwoslash2 }) => transformerTwoslash2)
814
+ ]);
815
+ shikiOptions = options2;
816
+ shiki = await getHighlighter({
817
+ ...options2,
818
+ langs: options2.langs ?? Object.keys(bundledLanguages),
819
+ themes: "themes" in options2 ? Object.values(options2.themes) : [options2.theme]
820
+ });
821
+ const transformers = [
822
+ ...options2.transformers || [],
823
+ transformerTwoslash({
824
+ explicitTrigger: true,
825
+ twoslashOptions: {
826
+ handbookOptions: {
827
+ noErrorValidation: true
828
+ }
829
+ }
830
+ }),
831
+ {
832
+ pre(pre) {
833
+ this.addClassToHast(pre, "slidev-code");
834
+ delete pre.properties.tabindex;
835
+ },
836
+ postprocess(code) {
837
+ return escapeVueInCode(code);
838
+ }
839
+ }
840
+ ];
841
+ const plugin = markdownItShiki(shiki, {
842
+ ...options2,
843
+ transformers
844
+ });
845
+ setups.push((md2) => md2.use(plugin));
846
+ } else {
847
+ setups.push((md2) => md2.use(markdownItPrism));
848
+ }
849
+ if (config.mdc)
850
+ setups.push((md2) => md2.use(Mdc));
851
+ const KatexOptions = await loadSetups(options.clientRoot, roots, "katex.ts", {}, { strict: false }, false);
852
+ return Markdown({
853
+ include: [/\.md$/],
854
+ wrapperClasses: "",
855
+ headEnabled: false,
856
+ frontmatter: false,
857
+ escapeCodeTagInterpolation: false,
858
+ markdownItOptions: {
859
+ quotes: `""''`,
860
+ html: true,
861
+ xhtmlOut: true,
862
+ linkify: true,
863
+ ...mdOptions?.markdownItOptions
864
+ },
865
+ ...mdOptions,
866
+ markdownItSetup(md2) {
867
+ md2.use(mila, {
868
+ attrs: {
869
+ target: "_blank",
870
+ rel: "noopener"
871
+ }
872
+ });
873
+ md2.use(mif);
874
+ md2.use(taskLists, { enabled: true, lineNumber: true, label: true });
875
+ md2.use(math_plugin, KatexOptions);
876
+ setups.forEach((i) => i(md2));
877
+ mdOptions?.markdownItSetup?.(md2);
878
+ },
879
+ transforms: {
880
+ before(code, id) {
881
+ if (id === entryPath)
882
+ return "";
883
+ const monaco = config.monaco === true || config.monaco === mode ? transformMarkdownMonaco : truncateMancoMark;
884
+ if (config.highlighter === "shiki")
885
+ code = transformMagicMove(code, shiki, shikiOptions);
886
+ code = transformSlotSugar(code);
887
+ code = transformSnippet(code, options, id);
888
+ code = transformMermaid(code);
889
+ code = transformPlantUml(code, config.plantUmlServer);
890
+ code = monaco(code);
891
+ code = transformHighlighter(code);
892
+ code = transformPageCSS(code, id);
893
+ code = transformKaTex(code);
894
+ return code;
895
+ }
896
+ }
897
+ });
898
+ }
899
+ function transformKaTex(md2) {
900
+ return md2.replace(
901
+ /^\$\$(?:\s*{([\d\w*,\|-]+)}\s*?({.*?})?\s*?)?\n([\s\S]+?)^\$\$/mg,
902
+ (full, rangeStr = "", options = "", code) => {
903
+ const ranges = !rangeStr.trim() ? [] : rangeStr.trim().split(/\|/g).map((i) => i.trim());
904
+ code = code.trimEnd();
905
+ options = options.trim() || "{}";
906
+ return `<KaTexBlockWrapper v-bind="${options}" :ranges='${JSON.stringify(ranges)}'>
907
+
908
+ $$
909
+ ${code}
910
+ $$
911
+ </KaTexBlockWrapper>
912
+ `;
913
+ }
914
+ );
915
+ }
916
+ function transformMarkdownMonaco(md2) {
917
+ md2 = md2.replace(
918
+ /^```(\w+?)\s*{monaco-diff}\s*?({.*?})?\s*?\n([\s\S]+?)^~~~\s*?\n([\s\S]+?)^```/mg,
919
+ (full, lang = "ts", options = "{}", code, diff) => {
920
+ lang = lang.trim();
921
+ options = options.trim() || "{}";
922
+ const encoded = lz.compressToBase64(code);
923
+ const encodedDiff = lz.compressToBase64(diff);
924
+ return `<Monaco code-lz="${encoded}" diff-lz="${encodedDiff}" lang="${lang}" v-bind="${options}" />`;
925
+ }
926
+ );
927
+ md2 = md2.replace(
928
+ /^```(\w+?)\s*{monaco}\s*?({.*?})?\s*?\n([\s\S]+?)^```/mg,
929
+ (full, lang = "ts", options = "{}", code) => {
930
+ lang = lang.trim();
931
+ options = options.trim() || "{}";
932
+ const encoded = lz.compressToBase64(code);
933
+ return `<Monaco code-lz="${encoded}" lang="${lang}" v-bind="${options}" />`;
934
+ }
935
+ );
936
+ return md2;
937
+ }
938
+ function scanMonacoModules(md2) {
939
+ const typeModules = /* @__PURE__ */ new Set();
940
+ md2.replace(
941
+ /^```(\w+?)\s*{monaco([\w:,-]*)}[\s\n]*([\s\S]+?)^```/mg,
942
+ (full, lang = "ts", options, code) => {
943
+ options = options || "";
944
+ lang = lang.trim();
945
+ if (lang === "ts" || lang === "typescript") {
946
+ Array.from(code.matchAll(/\s+from\s+(["'])([\/\w@-]+)\1/g)).map((i) => i[2]).filter(isTruthy).map((i) => typeModules.add(i));
947
+ }
948
+ return "";
949
+ }
950
+ );
951
+ return Array.from(typeModules);
952
+ }
953
+ function truncateMancoMark(md2) {
954
+ return md2.replace(/{monaco.*?}/g, "");
955
+ }
956
+ function transformSlotSugar(md2) {
957
+ const lines = md2.split(/\r?\n/g);
958
+ let prevSlot = false;
959
+ const { isLineInsideCodeblocks } = getCodeBlocks(md2);
960
+ lines.forEach((line, idx) => {
961
+ if (isLineInsideCodeblocks(idx))
962
+ return;
963
+ const match = line.trimEnd().match(/^::\s*([\w\.\-\:]+)\s*::$/);
964
+ if (match) {
965
+ lines[idx] = `${prevSlot ? "\n\n</template>\n" : "\n"}<template v-slot:${match[1]}="slotProps">
966
+ `;
967
+ prevSlot = true;
968
+ }
969
+ });
970
+ if (prevSlot)
971
+ lines[lines.length - 1] += "\n\n</template>";
972
+ return lines.join("\n");
973
+ }
974
+ var reMagicMoveBlock = /^````(?:md|markdown) magic-move(?:[ ]*?({.*?})?([^\n]*?))?\n([\s\S]+?)^````$/mg;
975
+ var reCodeBlock = /^```(\w+?)(?:\s*{([\d\w*,\|-]+)}\s*?({.*?})?(.*?))?\n([\s\S]+?)^```$/mg;
976
+ function transformMagicMove(md2, shiki2, shikiOptions2) {
977
+ return md2.replace(
978
+ reMagicMoveBlock,
979
+ (full, _options = "", _attrs = "", body) => {
980
+ if (!shiki2 || !shikiOptions2)
981
+ throw new Error("Shiki is required for Magic Move. You may need to set `highlighter: shiki` in your Slidev config.");
982
+ const matches = Array.from(body.matchAll(reCodeBlock));
983
+ if (!matches.length)
984
+ throw new Error("Magic Move block must contain at least one code block");
985
+ const langs = new Set(matches.map((i) => i[1]));
986
+ if (langs.size > 1)
987
+ throw new Error(`Magic Move block must contain code blocks with the same language, got ${Array.from(langs).join(", ")}`);
988
+ const lang = Array.from(langs)[0];
989
+ const magicMove = createMagicMoveMachine(
990
+ (code) => codeToKeyedTokens(shiki2, code, {
991
+ ...shikiOptions2,
992
+ lang
993
+ })
994
+ );
995
+ const steps = matches.map((i) => magicMove.commit((i[5] || "").trimEnd()));
996
+ const compressed = lz.compressToBase64(JSON.stringify(steps));
997
+ return `<ShikiMagicMove steps-lz="${compressed}" />`;
998
+ }
999
+ );
1000
+ }
1001
+ function transformHighlighter(md2) {
1002
+ return md2.replace(
1003
+ reCodeBlock,
1004
+ (full, lang = "", rangeStr = "", options = "", attrs = "", code) => {
1005
+ const ranges = !rangeStr.trim() ? [] : rangeStr.trim().split(/\|/g).map((i) => i.trim());
1006
+ code = code.trimEnd();
1007
+ options = options.trim() || "{}";
1008
+ return `
1009
+ <CodeBlockWrapper v-bind="${options}" :ranges='${JSON.stringify(ranges)}'>
1010
+
1011
+ \`\`\`${lang}${attrs}
1012
+ ${code}
1013
+ \`\`\`
1014
+
1015
+ </CodeBlockWrapper>`;
1016
+ }
1017
+ );
1018
+ }
1019
+ function getCodeBlocks(md2) {
1020
+ const codeblocks = Array.from(md2.matchAll(/^```[\s\S]*?^```/mg)).map((m) => {
1021
+ const start = m.index;
1022
+ const end = m.index + m[0].length;
1023
+ const startLine = md2.slice(0, start).match(/\n/g)?.length || 0;
1024
+ const endLine = md2.slice(0, end).match(/\n/g)?.length || 0;
1025
+ return [start, end, startLine, endLine];
1026
+ });
1027
+ return {
1028
+ codeblocks,
1029
+ isInsideCodeblocks(idx) {
1030
+ return codeblocks.some(([s, e]) => s <= idx && idx <= e);
1031
+ },
1032
+ isLineInsideCodeblocks(line) {
1033
+ return codeblocks.some(([, , s, e]) => s <= line && line <= e);
1034
+ }
1035
+ };
1036
+ }
1037
+ function transformPageCSS(md2, id) {
1038
+ const page = id.match(/(\d+)\.md$/)?.[1];
1039
+ if (!page)
1040
+ return md2;
1041
+ const { isInsideCodeblocks } = getCodeBlocks(md2);
1042
+ const result = md2.replace(
1043
+ /(\n<style[^>]*?>)([\s\S]+?)(<\/style>)/g,
1044
+ (full, start, css, end, index) => {
1045
+ if (index < 0 || isInsideCodeblocks(index))
1046
+ return full;
1047
+ if (!start.includes("scoped"))
1048
+ start = start.replace("<style", "<style scoped");
1049
+ return `${start}
1050
+ ${css}${end}`;
1051
+ }
1052
+ );
1053
+ return result;
1054
+ }
1055
+ function transformMermaid(md2) {
1056
+ return md2.replace(/^```mermaid\s*?({.*?})?\n([\s\S]+?)\n```/mg, (full, options = "", code = "") => {
1057
+ code = code.trim();
1058
+ options = options.trim() || "{}";
1059
+ const encoded = lz.compressToBase64(code);
1060
+ return `<Mermaid code-lz="${encoded}" v-bind="${options}" />`;
1061
+ });
1062
+ }
1063
+ function transformPlantUml(md2, server) {
1064
+ return md2.replace(/^```plantuml\s*?({.*?})?\n([\s\S]+?)\n```/mg, (full, options = "", content = "") => {
1065
+ const code = encodePlantUml(content.trim());
1066
+ options = options.trim() || "{}";
1067
+ return `<PlantUml :code="'${code}'" :server="'${server}'" v-bind="${options}" />`;
1068
+ });
1069
+ }
1070
+ function escapeVueInCode(md2) {
1071
+ return md2.replace(/{{/g, "&lbrace;&lbrace;");
1072
+ }
1073
+ async function loadShikiSetups(clientRoot, roots) {
1074
+ const result = await loadSetups(
1075
+ clientRoot,
1076
+ roots,
1077
+ "shiki.ts",
1078
+ {
1079
+ /** @deprecated */
1080
+ async loadTheme(path2) {
1081
+ console.warn("[slidev] `loadTheme` in `setup/shiki.ts` is deprecated. Pass directly the theme name it's supported by Shiki. For custom themes, load it manually via `JSON.parse(fs.readFileSync(path, 'utf-8'))` and pass the raw JSON object instead.");
1082
+ return JSON.parse(await fs4.readFile(path2, "utf-8"));
1083
+ }
1084
+ },
1085
+ {},
1086
+ false
1087
+ );
1088
+ if ("theme" in result && "themes" in result)
1089
+ delete result.theme;
1090
+ if (result.theme && typeof result.theme !== "string" && !result.theme.name && !result.theme.tokenColors) {
1091
+ result.themes = result.theme;
1092
+ delete result.theme;
1093
+ }
1094
+ if (!result.theme && !result.themes) {
1095
+ result.themes = {
1096
+ dark: "vitesse-dark",
1097
+ light: "vitesse-light"
1098
+ };
1099
+ }
1100
+ if (result.themes)
1101
+ result.defaultColor = false;
1102
+ return result;
1103
+ }
1104
+
1105
+ // node/plugins/loaders.ts
1106
+ var regexId = /^\/\@slidev\/slide\/(\d+)\.(md|json)(?:\?import)?$/;
1107
+ var regexIdQuery = /(\d+?)\.(md|json|frontmatter)$/;
1108
+ var templateInjectionMarker = "/* @slidev-injection */";
1109
+ var templateImportContextUtils = `import {
1110
+ useSlideContext,
1111
+ provideFrontmatter as _provideFrontmatter,
1112
+ frontmatterToProps as _frontmatterToProps,
1113
+ } from "@slidev/client/context.ts"`.replace(/\n\s*/g, " ");
1114
+ var templateInitContext = `const { $slidev, $nav, $clicksContext, $clicks, $page, $renderContext, $frontmatter } = useSlideContext()`;
1115
+ function getBodyJson(req) {
1116
+ return new Promise((resolve5, reject) => {
1117
+ let body = "";
1118
+ req.on("data", (chunk) => body += chunk);
1119
+ req.on("error", reject);
1120
+ req.on("end", () => {
1121
+ try {
1122
+ resolve5(JSON.parse(body) || {});
1123
+ } catch (e) {
1124
+ reject(e);
1125
+ }
1126
+ });
1127
+ });
1128
+ }
1129
+ var md = Markdown2({ html: true });
1130
+ md.use(mila2, {
1131
+ attrs: {
1132
+ target: "_blank",
1133
+ rel: "noopener"
1134
+ }
1135
+ });
1136
+ function renderNote(text = "") {
1137
+ let clickCount = 0;
1138
+ const html = md.render(
1139
+ text.replace(/\[click(?::(\d+))?\]/gi, (_, count = 1) => {
1140
+ clickCount += Number(count);
1141
+ return `<span class="slidev-note-click-mark" data-clicks="${clickCount}"></span>`;
1142
+ })
1143
+ );
1144
+ return html;
1145
+ }
1146
+ function withRenderedNote(data) {
1147
+ return {
1148
+ ...data,
1149
+ noteHTML: renderNote(data?.note)
1150
+ };
1151
+ }
1152
+ function createSlidesLoader({ data, clientRoot, roots, remote, mode, userRoot }, pluginOptions, serverOptions) {
1153
+ const slidePrefix = "/@slidev/slides/";
1154
+ const hmrPages = /* @__PURE__ */ new Set();
1155
+ let server;
1156
+ let _layouts_cache_time = 0;
1157
+ let _layouts_cache = {};
1158
+ return [
1159
+ {
1160
+ name: "slidev:loader",
1161
+ configureServer(_server) {
1162
+ server = _server;
1163
+ updateServerWatcher();
1164
+ server.middlewares.use(async (req, res, next) => {
1165
+ const match = req.url?.match(regexId);
1166
+ if (!match)
1167
+ return next();
1168
+ const [, no, type] = match;
1169
+ const idx = Number.parseInt(no);
1170
+ if (type === "json" && req.method === "GET") {
1171
+ res.write(JSON.stringify(withRenderedNote(data.slides[idx])));
1172
+ return res.end();
1173
+ }
1174
+ if (type === "json" && req.method === "POST") {
1175
+ const body = await getBodyJson(req);
1176
+ const slide = data.slides[idx];
1177
+ if (body.content && body.content !== slide.source.content)
1178
+ hmrPages.add(idx);
1179
+ Object.assign(slide.source, body);
1180
+ parser.prettifySlide(slide.source);
1181
+ await parser.save(data.markdownFiles[slide.source.filepath]);
1182
+ res.statusCode = 200;
1183
+ res.write(JSON.stringify(withRenderedNote(slide)));
1184
+ return res.end();
1185
+ }
1186
+ next();
1187
+ });
1188
+ },
1189
+ async handleHotUpdate(ctx) {
1190
+ if (!data.watchFiles.includes(ctx.file))
1191
+ return;
1192
+ await ctx.read();
1193
+ const newData = await serverOptions.loadData?.();
1194
+ if (!newData)
1195
+ return [];
1196
+ const moduleIds = /* @__PURE__ */ new Set();
1197
+ if (data.slides.length !== newData.slides.length) {
1198
+ moduleIds.add("/@slidev/routes");
1199
+ range(newData.slides.length).map((i) => hmrPages.add(i));
1200
+ }
1201
+ if (!equal(data.headmatter.defaults, newData.headmatter.defaults)) {
1202
+ moduleIds.add("/@slidev/routes");
1203
+ range(data.slides.length).map((i) => hmrPages.add(i));
1204
+ }
1205
+ if (!equal(data.config, newData.config))
1206
+ moduleIds.add("/@slidev/configs");
1207
+ if (!equal(data.features, newData.features)) {
1208
+ setTimeout(() => {
1209
+ ctx.server.ws.send({ type: "full-reload" });
1210
+ }, 1);
1211
+ }
1212
+ const length = Math.max(data.slides.length, newData.slides.length);
1213
+ for (let i = 0; i < length; i++) {
1214
+ const a = data.slides[i];
1215
+ const b = newData.slides[i];
1216
+ if (a?.content.trim() === b?.content.trim() && a?.title?.trim() === b?.title?.trim() && equal(a.frontmatter, b.frontmatter) && Object.entries(a.snippetsUsed ?? {}).every(([file, oldContent]) => {
1217
+ try {
1218
+ const newContent = fs5.readFileSync(file, "utf-8");
1219
+ return oldContent === newContent;
1220
+ } catch {
1221
+ return false;
1222
+ }
1223
+ })) {
1224
+ if (a?.note !== b?.note) {
1225
+ ctx.server.ws.send({
1226
+ type: "custom",
1227
+ event: "slidev-update-note",
1228
+ data: {
1229
+ id: i,
1230
+ note: b.note || "",
1231
+ noteHTML: renderNote(b.note || "")
1232
+ }
1233
+ });
1234
+ }
1235
+ continue;
1236
+ }
1237
+ ctx.server.ws.send({
1238
+ type: "custom",
1239
+ event: "slidev-update",
1240
+ data: {
1241
+ id: i,
1242
+ data: withRenderedNote(newData.slides[i])
1243
+ }
1244
+ });
1245
+ hmrPages.add(i);
1246
+ }
1247
+ Object.assign(data, newData);
1248
+ if (hmrPages.size > 0)
1249
+ moduleIds.add("/@slidev/titles.md");
1250
+ const vueModules = Array.from(hmrPages).flatMap((i) => [
1251
+ ctx.server.moduleGraph.getModuleById(`${slidePrefix}${i + 1}.frontmatter`),
1252
+ ctx.server.moduleGraph.getModuleById(`${slidePrefix}${i + 1}.md`)
1253
+ ]);
1254
+ hmrPages.clear();
1255
+ const moduleEntries = [
1256
+ ...vueModules,
1257
+ ...Array.from(moduleIds).map((id) => ctx.server.moduleGraph.getModuleById(id))
1258
+ ].filter(notNullish).filter((i) => !i.id?.startsWith("/@id/@vite-icons"));
1259
+ updateServerWatcher();
1260
+ return moduleEntries;
1261
+ },
1262
+ resolveId(id) {
1263
+ if (id.startsWith(slidePrefix) || id.startsWith("/@slidev/"))
1264
+ return id;
1265
+ return null;
1266
+ },
1267
+ load(id) {
1268
+ if (id === "/@slidev/routes")
1269
+ return generateRoutes();
1270
+ if (id === "/@slidev/layouts")
1271
+ return generateLayouts();
1272
+ if (id === "/@slidev/styles")
1273
+ return generateUserStyles();
1274
+ if (id === "/@slidev/monaco-types")
1275
+ return generateMonacoTypes();
1276
+ if (id === "/@slidev/configs")
1277
+ return generateConfigs();
1278
+ if (id === "/@slidev/global-components/top")
1279
+ return generateGlobalComponents("top");
1280
+ if (id === "/@slidev/global-components/bottom")
1281
+ return generateGlobalComponents("bottom");
1282
+ if (id === "/@slidev/custom-nav-controls")
1283
+ return generateCustomNavControls();
1284
+ if (id === "/@slidev/shiki")
1285
+ return generteShikiBundle();
1286
+ if (id === "/@slidev/titles.md") {
1287
+ return {
1288
+ code: data.slides.map(({ title }, i) => `<template ${i === 0 ? "v-if" : "v-else-if"}="+no === ${i + 1}">
1289
+
1290
+ ${title}
1291
+
1292
+ </template>`).join(""),
1293
+ map: { mappings: "" }
1294
+ };
1295
+ }
1296
+ if (id.startsWith(slidePrefix)) {
1297
+ const remaning = id.slice(slidePrefix.length);
1298
+ const match = remaning.match(regexIdQuery);
1299
+ if (match) {
1300
+ const [, no, type] = match;
1301
+ const pageNo = Number.parseInt(no) - 1;
1302
+ const slide = data.slides[pageNo];
1303
+ if (!slide)
1304
+ return;
1305
+ if (type === "md") {
1306
+ return {
1307
+ code: slide?.content,
1308
+ map: { mappings: "" }
1309
+ };
1310
+ } else if (type === "frontmatter") {
1311
+ const slideBase = {
1312
+ ...withRenderedNote(slide),
1313
+ frontmatter: void 0,
1314
+ source: void 0,
1315
+ // remove raw content in build, optimize the bundle size
1316
+ ...mode === "build" ? { raw: "", content: "", note: "" } : {}
1317
+ };
1318
+ const fontmatter = getFrontmatter(pageNo);
1319
+ return {
1320
+ code: [
1321
+ "// @unocss-include",
1322
+ 'import { reactive, computed } from "vue"',
1323
+ `export const frontmatter = reactive(${JSON.stringify(fontmatter)})`,
1324
+ `export const meta = reactive({
1325
+ layout: computed(() => frontmatter.layout),
1326
+ transition: computed(() => frontmatter.transition),
1327
+ class: computed(() => frontmatter.class),
1328
+ clicks: computed(() => frontmatter.clicks),
1329
+ name: computed(() => frontmatter.name),
1330
+ preload: computed(() => frontmatter.preload),
1331
+ slide: {
1332
+ ...(${JSON.stringify(slideBase)}),
1333
+ frontmatter,
1334
+ filepath: ${JSON.stringify(slide.source.filepath)},
1335
+ start: ${JSON.stringify(slide.source.start)},
1336
+ id: ${pageNo},
1337
+ no: ${no},
1338
+ },
1339
+ __clicksContext: null,
1340
+ __preloaded: false,
1341
+ })`,
1342
+ "export default frontmatter",
1343
+ // handle HMR, update frontmatter with update
1344
+ "if (import.meta.hot) {",
1345
+ " import.meta.hot.accept(({ frontmatter: update }) => {",
1346
+ " if(!update) return",
1347
+ " Object.keys(frontmatter).forEach(key => {",
1348
+ " if (!(key in update)) delete frontmatter[key]",
1349
+ " })",
1350
+ " Object.assign(frontmatter, update)",
1351
+ " })",
1352
+ "}"
1353
+ ].join("\n"),
1354
+ map: { mappings: "" }
1355
+ };
1356
+ }
1357
+ }
1358
+ return {
1359
+ code: "",
1360
+ map: { mappings: "" }
1361
+ };
1362
+ }
1363
+ }
1364
+ },
1365
+ {
1366
+ name: "slidev:layout-transform:pre",
1367
+ enforce: "pre",
1368
+ async transform(code, id) {
1369
+ if (!id.startsWith(slidePrefix))
1370
+ return;
1371
+ const remaning = id.slice(slidePrefix.length);
1372
+ const match = remaning.match(regexIdQuery);
1373
+ if (!match)
1374
+ return;
1375
+ const [, no, type] = match;
1376
+ if (type !== "md")
1377
+ return;
1378
+ const pageNo = Number.parseInt(no) - 1;
1379
+ return transformMarkdown(code, pageNo);
1380
+ }
1381
+ },
1382
+ {
1383
+ name: "slidev:context-transform:pre",
1384
+ enforce: "pre",
1385
+ async transform(code, id) {
1386
+ if (!id.endsWith(".vue") || id.includes("/@slidev/client/") || id.includes("/packages/client/"))
1387
+ return;
1388
+ return transformVue(code);
1389
+ }
1390
+ },
1391
+ {
1392
+ name: "slidev:title-transform:pre",
1393
+ enforce: "pre",
1394
+ transform(code, id) {
1395
+ if (id !== "/@slidev/titles.md")
1396
+ return;
1397
+ return transformTitles(code);
1398
+ }
1399
+ },
1400
+ {
1401
+ name: "slidev:slide-transform:post",
1402
+ enforce: "post",
1403
+ transform(code, id) {
1404
+ if (!id.match(/\/@slidev\/slides\/\d+\.md($|\?)/))
1405
+ return;
1406
+ const replaced = code.replace("if (_rerender_only)", "if (false)");
1407
+ if (replaced !== code)
1408
+ return replaced;
1409
+ }
1410
+ },
1411
+ {
1412
+ name: "slidev:index-html-transform",
1413
+ transformIndexHtml() {
1414
+ const { info, author, keywords } = data.headmatter;
1415
+ return [
1416
+ {
1417
+ tag: "title",
1418
+ children: getTitle()
1419
+ },
1420
+ info && {
1421
+ tag: "meta",
1422
+ attrs: {
1423
+ name: "description",
1424
+ content: info
1425
+ }
1426
+ },
1427
+ author && {
1428
+ tag: "meta",
1429
+ attrs: {
1430
+ name: "author",
1431
+ content: author
1432
+ }
1433
+ },
1434
+ keywords && {
1435
+ tag: "meta",
1436
+ attrs: {
1437
+ name: "keywords",
1438
+ content: Array.isArray(keywords) ? keywords.join(", ") : keywords
1439
+ }
1440
+ }
1441
+ ].filter(isTruthy2);
1442
+ }
1443
+ }
1444
+ ];
1445
+ function updateServerWatcher() {
1446
+ if (!server)
1447
+ return;
1448
+ server.watcher.add(data.watchFiles);
1449
+ }
1450
+ function getFrontmatter(pageNo) {
1451
+ return {
1452
+ ...data.headmatter?.defaults || {},
1453
+ ...data.slides[pageNo]?.frontmatter || {}
1454
+ };
1455
+ }
1456
+ async function transformMarkdown(code, pageNo) {
1457
+ const layouts = await getLayouts();
1458
+ const frontmatter = getFrontmatter(pageNo);
1459
+ let layoutName = frontmatter?.layout || (pageNo === 0 ? "cover" : "default");
1460
+ if (!layouts[layoutName]) {
1461
+ console.error(red(`
1462
+ Unknown layout "${bold(layoutName)}".${yellow(" Available layouts are:")}`) + Object.keys(layouts).map((i, idx) => (idx % 3 === 0 ? "\n " : "") + gray(i.padEnd(15, " "))).join(" "));
1463
+ console.error();
1464
+ layoutName = "default";
1465
+ }
1466
+ delete frontmatter.title;
1467
+ const imports = [
1468
+ `import InjectedLayout from "${toAtFS(layouts[layoutName])}"`,
1469
+ `import frontmatter from "${toAtFS(`${slidePrefix + (pageNo + 1)}.frontmatter`)}"`,
1470
+ templateImportContextUtils,
1471
+ "_provideFrontmatter(frontmatter)",
1472
+ templateInitContext,
1473
+ templateInjectionMarker
1474
+ ];
1475
+ code = code.replace(/(<script setup.*>)/g, `$1
1476
+ ${imports.join("\n")}
1477
+ `);
1478
+ const injectA = code.indexOf("<template>") + "<template>".length;
1479
+ const injectB = code.lastIndexOf("</template>");
1480
+ let body = code.slice(injectA, injectB).trim();
1481
+ if (body.startsWith("<div>") && body.endsWith("</div>"))
1482
+ body = body.slice(5, -6);
1483
+ code = `${code.slice(0, injectA)}
1484
+ <InjectedLayout v-bind="_frontmatterToProps(frontmatter,${pageNo})">
1485
+ ${body}
1486
+ </InjectedLayout>
1487
+ ${code.slice(injectB)}`;
1488
+ return code;
1489
+ }
1490
+ function transformVue(code) {
1491
+ if (code.includes(templateInjectionMarker) || code.includes("useSlideContext()"))
1492
+ return code;
1493
+ const imports = [
1494
+ templateImportContextUtils,
1495
+ templateInitContext,
1496
+ templateInjectionMarker
1497
+ ];
1498
+ const matchScript = code.match(/<script((?!setup).)*(setup)?.*>/);
1499
+ if (matchScript && matchScript[2]) {
1500
+ return code.replace(/(<script.*>)/g, `$1
1501
+ ${imports.join("\n")}
1502
+ `);
1503
+ } else if (matchScript && !matchScript[2]) {
1504
+ const matchExport = code.match(/export\s+default\s+{/);
1505
+ if (matchExport) {
1506
+ const exportIndex = (matchExport.index || 0) + matchExport[0].length;
1507
+ let component = code.slice(exportIndex);
1508
+ component = component.slice(0, component.indexOf("</script>"));
1509
+ const scriptIndex = (matchScript.index || 0) + matchScript[0].length;
1510
+ const provideImport = '\nimport { injectionSlidevContext } from "@slidev/client/constants.ts"\n';
1511
+ code = `${code.slice(0, scriptIndex)}${provideImport}${code.slice(scriptIndex)}`;
1512
+ let injectIndex = exportIndex + provideImport.length;
1513
+ let injectObject = "$slidev: { from: injectionSlidevContext },";
1514
+ const matchInject = component.match(/.*inject\s*:\s*([\[{])/);
1515
+ if (matchInject) {
1516
+ injectIndex += (matchInject.index || 0) + matchInject[0].length;
1517
+ if (matchInject[1] === "[") {
1518
+ let injects = component.slice((matchInject.index || 0) + matchInject[0].length);
1519
+ const injectEndIndex = injects.indexOf("]");
1520
+ injects = injects.slice(0, injectEndIndex);
1521
+ injectObject += injects.split(",").map((inject) => `${inject}: {from: ${inject}}`).join(",");
1522
+ return `${code.slice(0, injectIndex - 1)}{
1523
+ ${injectObject}
1524
+ }${code.slice(injectIndex + injectEndIndex + 1)}`;
1525
+ } else {
1526
+ return `${code.slice(0, injectIndex)}
1527
+ ${injectObject}
1528
+ ${code.slice(injectIndex)}`;
1529
+ }
1530
+ }
1531
+ return `${code.slice(0, injectIndex)}
1532
+ inject: { ${injectObject} },
1533
+ ${code.slice(injectIndex)}`;
1534
+ }
1535
+ }
1536
+ return `<script setup>
1537
+ ${imports.join("\n")}
1538
+ </script>
1539
+ ${code}`;
1540
+ }
1541
+ function transformTitles(code) {
1542
+ return code.replace(/<template>\s*<div>\s*<p>/, "<template>").replace(/<\/p>\s*<\/div>\s*<\/template>/, "</template>").replace(/<script\ssetup>/, `<script setup lang="ts">
1543
+ defineProps<{ no: number | string }>()`);
1544
+ }
1545
+ async function getLayouts() {
1546
+ const now = Date.now();
1547
+ if (now - _layouts_cache_time < 2e3)
1548
+ return _layouts_cache;
1549
+ const layouts = {};
1550
+ for (const root of [...roots, clientRoot]) {
1551
+ const layoutPaths = await fg2("layouts/**/*.{vue,ts}", {
1552
+ cwd: root,
1553
+ absolute: true,
1554
+ suppressErrors: true
1555
+ });
1556
+ for (const layoutPath of layoutPaths) {
1557
+ const layout = basename2(layoutPath).replace(/\.\w+$/, "");
1558
+ if (layouts[layout])
1559
+ continue;
1560
+ layouts[layout] = layoutPath;
1561
+ }
1562
+ }
1563
+ _layouts_cache_time = now;
1564
+ _layouts_cache = layouts;
1565
+ return layouts;
1566
+ }
1567
+ async function resolveUrl(id) {
1568
+ return toAtFS(await resolveImportPath(id, true));
1569
+ }
1570
+ function resolveUrlOfClient(name) {
1571
+ return toAtFS(join4(clientRoot, name));
1572
+ }
1573
+ async function generateUserStyles() {
1574
+ const imports = [
1575
+ `import "${resolveUrlOfClient("styles/vars.css")}"`,
1576
+ `import "${resolveUrlOfClient("styles/index.css")}"`,
1577
+ `import "${resolveUrlOfClient("styles/code.css")}"`,
1578
+ `import "${resolveUrlOfClient("styles/katex.css")}"`,
1579
+ `import "${resolveUrlOfClient("styles/transitions.css")}"`,
1580
+ `import "${resolveUrlOfClient("styles/monaco.css")}"`
1581
+ ];
1582
+ for (const root of roots) {
1583
+ const styles = [
1584
+ join4(root, "styles", "index.ts"),
1585
+ join4(root, "styles", "index.js"),
1586
+ join4(root, "styles", "index.css"),
1587
+ join4(root, "styles.css"),
1588
+ join4(root, "style.css")
1589
+ ];
1590
+ for (const style of styles) {
1591
+ if (fs5.existsSync(style)) {
1592
+ imports.push(`import "${toAtFS(style)}"`);
1593
+ continue;
1594
+ }
1595
+ }
1596
+ }
1597
+ if (data.features.katex)
1598
+ imports.push(`import "${await resolveUrl("katex/dist/katex.min.css")}"`);
1599
+ if (data.config.highlighter === "shiki") {
1600
+ imports.push(
1601
+ `import "${await resolveUrl("@shikijs/vitepress-twoslash/style.css")}"`,
1602
+ `import "${resolveUrlOfClient("styles/shiki-twoslash.css")}"`
1603
+ );
1604
+ }
1605
+ if (data.config.css === "unocss") {
1606
+ imports.unshift(
1607
+ `import "${await resolveUrl("@unocss/reset/tailwind.css")}"`,
1608
+ 'import "uno:preflights.css"',
1609
+ 'import "uno:typography.css"',
1610
+ 'import "uno:shortcuts.css"'
1611
+ );
1612
+ imports.push('import "uno.css"');
1613
+ }
1614
+ return imports.join("\n");
1615
+ }
1616
+ async function generateMonacoTypes() {
1617
+ const typesRoot = join4(userRoot, "snippets");
1618
+ const files = await fg2(["**/*.ts", "**/*.mts", "**/*.cts"], { cwd: typesRoot });
1619
+ let result = [
1620
+ 'import * as monaco from "monaco-editor"',
1621
+ "async function addFile(mod, path) {",
1622
+ " const code = (await mod).default",
1623
+ ' monaco.languages.typescript.typescriptDefaults.addExtraLib(code, "file:///" + path)',
1624
+ ' monaco.editor.createModel(code, "javascript", monaco.Uri.file(path))',
1625
+ "}"
1626
+ ].join("\n");
1627
+ for (const file of files) {
1628
+ const url = `${toAtFS(resolve2(typesRoot, file))}?monaco-types&raw`;
1629
+ result += `addFile(import(${JSON.stringify(url)}), ${JSON.stringify(file)})
1630
+ `;
1631
+ }
1632
+ const deps = data.config.monacoTypesAdditionalPackages;
1633
+ if (data.config.monacoTypesSource === "local")
1634
+ deps.push(...scanMonacoModules(data.slides.map((s) => s.source.raw).join()));
1635
+ function mapModuleNameToModule(moduleSpecifier) {
1636
+ if (moduleSpecifier.startsWith("node:"))
1637
+ return "node";
1638
+ if (builtinModules.includes(moduleSpecifier))
1639
+ return "node";
1640
+ const mainPackageName = moduleSpecifier.split("/")[0];
1641
+ if (builtinModules.includes(mainPackageName) && !mainPackageName.startsWith("@"))
1642
+ return "node";
1643
+ const [a = "", b = ""] = moduleSpecifier.split("/");
1644
+ const moduleName = a.startsWith("@") ? `${a}/${b}` : a;
1645
+ return moduleName;
1646
+ }
1647
+ for (const specifier of uniq2(deps)) {
1648
+ if (specifier[0] === ".")
1649
+ continue;
1650
+ const moduleName = mapModuleNameToModule(specifier);
1651
+ result += `import(${JSON.stringify(`/@slidev-monaco-types/resolve?pkg=${moduleName}`)})
1652
+ `;
1653
+ }
1654
+ return result;
1655
+ }
1656
+ async function generateLayouts() {
1657
+ const imports = [];
1658
+ const layouts = objectMap(
1659
+ await getLayouts(),
1660
+ (k, v) => {
1661
+ imports.push(`import __layout_${k} from "${toAtFS(v)}"`);
1662
+ return [k, `__layout_${k}`];
1663
+ }
1664
+ );
1665
+ return [
1666
+ imports.join("\n"),
1667
+ `export default {
1668
+ ${Object.entries(layouts).map(([k, v]) => `"${k}": ${v}`).join(",\n")}
1669
+ }`
1670
+ ].join("\n\n");
1671
+ }
1672
+ async function generateRoutes() {
1673
+ const imports = [];
1674
+ const redirects = [];
1675
+ const layouts = await getLayouts();
1676
+ imports.push(
1677
+ `import { markRaw } from 'vue'`,
1678
+ `import __layout__end from '${layouts.end}'`
1679
+ );
1680
+ let no = 1;
1681
+ const routes = data.slides.map((i, idx) => {
1682
+ imports.push(`import n${no} from '${slidePrefix}${idx + 1}.md'`);
1683
+ imports.push(`import { meta as f${no} } from '${slidePrefix}${idx + 1}.frontmatter'`);
1684
+ const route = `{ path: '${no}', name: 'page-${no}', component: n${no}, meta: f${no} }`;
1685
+ if (i.frontmatter?.routeAlias)
1686
+ redirects.push(`{ path: '${i.frontmatter?.routeAlias}', redirect: { path: '${no}' } }`);
1687
+ no += 1;
1688
+ return route;
1689
+ });
1690
+ const routesStr = `export const rawRoutes = [
1691
+ ${routes.join(",\n")}
1692
+ ].map(markRaw)`;
1693
+ const redirectsStr = `export const redirects = [
1694
+ ${redirects.join(",\n")}
1695
+ ].map(markRaw)`;
1696
+ return [...imports, routesStr, redirectsStr].join("\n");
1697
+ }
1698
+ function getTitle() {
1699
+ if (isString(data.config.title)) {
1700
+ const tokens = md.parseInline(data.config.title, {});
1701
+ return stringifyMarkdownTokens(tokens);
1702
+ }
1703
+ return data.config.title;
1704
+ }
1705
+ function generateConfigs() {
1706
+ const config = {
1707
+ ...data.config,
1708
+ remote,
1709
+ title: getTitle()
1710
+ };
1711
+ if (isString(config.info))
1712
+ config.info = md.render(config.info);
1713
+ return `export default ${JSON.stringify(config)}`;
1714
+ }
1715
+ async function generateGlobalComponents(layer) {
1716
+ const components = roots.flatMap((root) => {
1717
+ if (layer === "top") {
1718
+ return [
1719
+ join4(root, "global.vue"),
1720
+ join4(root, "global-top.vue"),
1721
+ join4(root, "GlobalTop.vue")
1722
+ ];
1723
+ } else {
1724
+ return [
1725
+ join4(root, "global-bottom.vue"),
1726
+ join4(root, "GlobalBottom.vue")
1727
+ ];
1728
+ }
1729
+ }).filter((i) => fs5.existsSync(i));
1730
+ const imports = components.map((i, idx) => `import __n${idx} from '${toAtFS(i)}'`).join("\n");
1731
+ const render = components.map((i, idx) => `h(__n${idx})`).join(",");
1732
+ return `
1733
+ ${imports}
1734
+ import { h } from 'vue'
1735
+ export default {
1736
+ render() {
1737
+ return [${render}]
1738
+ }
1739
+ }
1740
+ `;
1741
+ }
1742
+ async function generateCustomNavControls() {
1743
+ const components = roots.flatMap((root) => {
1744
+ return [
1745
+ join4(root, "custom-nav-controls.vue"),
1746
+ join4(root, "CustomNavControls.vue")
1747
+ ];
1748
+ }).filter((i) => fs5.existsSync(i));
1749
+ const imports = components.map((i, idx) => `import __n${idx} from '${toAtFS(i)}'`).join("\n");
1750
+ const render = components.map((i, idx) => `h(__n${idx})`).join(",");
1751
+ return `
1752
+ ${imports}
1753
+ import { h } from 'vue'
1754
+ export default {
1755
+ render() {
1756
+ return [${render}]
1757
+ }
1758
+ }
1759
+ `;
1760
+ }
1761
+ async function generteShikiBundle() {
1762
+ const options = await loadShikiSetups(clientRoot, roots);
1763
+ const langs = await resolveLangs(options.langs || ["javascript", "typescript", "html", "css"]);
1764
+ const resolvedThemeOptions = "themes" in options ? {
1765
+ themes: Object.fromEntries(await Promise.all(
1766
+ Object.entries(options.themes).map(async ([name, value]) => [name, await resolveTheme(value)])
1767
+ ))
1768
+ } : {
1769
+ theme: await resolveTheme(options.theme || "vitesse-dark")
1770
+ };
1771
+ const themes = resolvedThemeOptions.themes ? Object.values(resolvedThemeOptions.themes) : [resolvedThemeOptions.theme];
1772
+ const themeOptionsNames = resolvedThemeOptions.themes ? { themes: Object.fromEntries(Object.entries(resolvedThemeOptions.themes).map(([name, value]) => [name, typeof value === "string" ? value : value.name])) } : { theme: typeof resolvedThemeOptions.theme === "string" ? resolvedThemeOptions.theme : resolvedThemeOptions.theme.name };
1773
+ async function normalizeGetter(p) {
1774
+ return Promise.resolve(typeof p === "function" ? p() : p).then((r) => r.default || r);
1775
+ }
1776
+ async function resolveLangs(langs2) {
1777
+ return Array.from(new Set((await Promise.all(
1778
+ langs2.map(async (lang) => await normalizeGetter(lang).then((r) => Array.isArray(r) ? r : [r]))
1779
+ )).flat()));
1780
+ }
1781
+ async function resolveTheme(theme) {
1782
+ return typeof theme === "string" ? theme : await normalizeGetter(theme);
1783
+ }
1784
+ const langsInit = await Promise.all(
1785
+ langs.map(async (lang) => typeof lang === "string" ? `import('${await resolveUrl(`shiki/langs/${lang}.mjs`)}')` : JSON.stringify(lang))
1786
+ );
1787
+ const themesInit = await Promise.all(themes.map(async (theme) => typeof theme === "string" ? `import('${await resolveUrl(`shiki/themes/${theme}.mjs`)}')` : JSON.stringify(theme)));
1788
+ const langNames = langs.flatMap((lang) => typeof lang === "string" ? lang : lang.name);
1789
+ const lines = [];
1790
+ lines.push(
1791
+ `import { getHighlighterCore } from "${await resolveUrl("shiki/core")}"`,
1792
+ `export { shikiToMonaco } from "${await resolveUrl("@shikijs/monaco")}"`,
1793
+ `export const languages = ${JSON.stringify(langNames)}`,
1794
+ `export const themes = ${JSON.stringify(themeOptionsNames.themes || themeOptionsNames.theme)}`,
1795
+ "export const shiki = getHighlighterCore({",
1796
+ ` themes: [${themesInit.join(",")}],`,
1797
+ ` langs: [${langsInit.join(",")}],`,
1798
+ ` loadWasm: import('${await resolveUrl("shiki/wasm")}'),`,
1799
+ "})"
1800
+ );
1801
+ return lines.join("\n");
1802
+ }
1803
+ }
1804
+
1805
+ // node/plugins/setupClient.ts
1806
+ import { existsSync as existsSync2 } from "node:fs";
1807
+ import { join as join5, resolve as resolve3 } from "node:path";
1808
+ import { slash as slash2, uniq as uniq3 } from "@antfu/utils";
1809
+ function createClientSetupPlugin({ themeRoots, addonRoots, userRoot, clientRoot }) {
1810
+ const setupEntry = slash2(resolve3(clientRoot, "setup"));
1811
+ return {
1812
+ name: "slidev:setup",
1813
+ enforce: "pre",
1814
+ async transform(code, id) {
1815
+ if (id.startsWith(setupEntry)) {
1816
+ let getInjections2 = function(isAwait = false, isChained = false) {
1817
+ return injections.join("\n").replace(/:AWAIT:/g, isAwait ? "await " : "").replace(/(,\s*)?:LAST:/g, isChained ? "$1injection_return" : "");
1818
+ };
1819
+ var getInjections = getInjections2;
1820
+ const name = id.slice(setupEntry.length + 1).replace(/\?.*$/, "");
1821
+ const imports = [];
1822
+ const injections = [];
1823
+ const setups = uniq3([
1824
+ ...themeRoots,
1825
+ ...addonRoots,
1826
+ userRoot
1827
+ ]).map((i) => join5(i, "setup", name));
1828
+ setups.forEach((path2, idx) => {
1829
+ if (!existsSync2(path2))
1830
+ return;
1831
+ imports.push(`import __n${idx} from '${toAtFS(path2)}'`);
1832
+ let fn = `:AWAIT:__n${idx}`;
1833
+ if (/\binjection_return\b/g.test(code))
1834
+ fn = `injection_return = ${fn}`;
1835
+ if (/\binjection_arg\b/g.test(code)) {
1836
+ fn += "(";
1837
+ const matches = Array.from(code.matchAll(/\binjection_arg(_\d+)?\b/g));
1838
+ const dedupedMatches = Array.from(new Set(matches.map((m) => m[0])));
1839
+ fn += dedupedMatches.join(", ");
1840
+ fn += ", :LAST:)";
1841
+ } else {
1842
+ fn += "(:LAST:)";
1843
+ }
1844
+ injections.push(
1845
+ `// ${path2}`,
1846
+ fn
1847
+ );
1848
+ });
1849
+ code = code.replace("/* __imports__ */", imports.join("\n"));
1850
+ code = code.replace("/* __injections__ */", getInjections2());
1851
+ code = code.replace("/* __async_injections__ */", getInjections2(true));
1852
+ code = code.replace("/* __chained_injections__ */", getInjections2(false, true));
1853
+ code = code.replace("/* __chained_async_injections__ */", getInjections2(true, true));
1854
+ return code;
1855
+ }
1856
+ return null;
1857
+ }
1858
+ };
1859
+ }
1860
+
1861
+ // node/plugins/patchTransform.ts
1862
+ import { objectEntries } from "@antfu/utils";
1863
+ function createFixPlugins(options) {
1864
+ const define = objectEntries(getDefine(options));
1865
+ return [
1866
+ {
1867
+ name: "slidev:flags",
1868
+ enforce: "pre",
1869
+ transform(code, id) {
1870
+ if (id.match(/\.vue($|\?)/)) {
1871
+ const original = code;
1872
+ define.forEach(([from, to]) => {
1873
+ code = code.replace(new RegExp(from, "g"), to);
1874
+ });
1875
+ if (original !== code)
1876
+ return code;
1877
+ }
1878
+ }
1879
+ }
1880
+ ];
1881
+ }
1882
+
1883
+ // node/plugins/monacoTypes.ts
1884
+ import fs6 from "node:fs/promises";
1885
+ import { dirname as dirname2, resolve as resolve4 } from "node:path";
1886
+ import { slash as slash3 } from "@antfu/utils";
1887
+ import fg3 from "fast-glob";
1888
+ import { findDepPkgJsonPath } from "vitefu";
1889
+ function createMonacoTypesLoader({ userRoot }) {
1890
+ const resolvedDepsMap = {};
1891
+ return {
1892
+ name: "slidev:monaco-types-loader",
1893
+ resolveId(id) {
1894
+ if (id.startsWith("/@slidev-monaco-types/"))
1895
+ return id;
1896
+ return null;
1897
+ },
1898
+ async load(id) {
1899
+ const matchResolve = id.match(/^\/\@slidev-monaco-types\/resolve\?pkg=(.*?)(?:&importer=(.*))?$/);
1900
+ if (matchResolve) {
1901
+ const [_, pkg, importer = userRoot] = matchResolve;
1902
+ const resolvedDeps = resolvedDepsMap[importer] ??= /* @__PURE__ */ new Set();
1903
+ if (resolvedDeps.has(pkg))
1904
+ return "";
1905
+ resolvedDeps.add(pkg);
1906
+ const pkgJsonPath = await findDepPkgJsonPath(pkg, importer);
1907
+ if (!pkgJsonPath)
1908
+ throw new Error(`Package "${pkg}" not found in "${importer}"`);
1909
+ const root = dirname2(pkgJsonPath);
1910
+ const pkgJson = JSON.parse(await fs6.readFile(pkgJsonPath, "utf-8"));
1911
+ const deps = pkgJson.dependencies ?? {};
1912
+ return [
1913
+ `import "/@slidev-monaco-types/load?root=${slash3(root)}&name=${pkgJson.name}"`,
1914
+ ...Object.keys(deps).map((dep) => `import "/@slidev-monaco-types/resolve?pkg=${dep}&importer=${slash3(root)}"`)
1915
+ ].join("\n");
1916
+ }
1917
+ const matchLoad = id.match(/^\/\@slidev-monaco-types\/load\?root=(.*?)&name=(.*)$/);
1918
+ if (matchLoad) {
1919
+ const [_, root, name] = matchLoad;
1920
+ const files = await fg3(
1921
+ [
1922
+ "**/*.ts",
1923
+ "**/*.mts",
1924
+ "**/*.cts",
1925
+ "package.json"
1926
+ ],
1927
+ {
1928
+ cwd: root,
1929
+ followSymbolicLinks: true,
1930
+ ignore: ["**/node_modules/**"]
1931
+ }
1932
+ );
1933
+ if (!files.length)
1934
+ return "";
1935
+ return [
1936
+ "import * as monaco from 'monaco-editor'",
1937
+ "async function addFile(mod, subPath) {",
1938
+ " const code = (await mod).default",
1939
+ ` const path = ${JSON.stringify(`/node_modules/${name}/`)} + subPath`,
1940
+ ' monaco.languages.typescript.typescriptDefaults.addExtraLib(code, "file://" + path)',
1941
+ ' monaco.editor.createModel(code, "javascript", monaco.Uri.file(path))',
1942
+ "}",
1943
+ ...files.map((file) => `addFile(import(${JSON.stringify(`${toAtFS(resolve4(root, file))}?monaco-types&raw`)}), ${JSON.stringify(file)})`)
1944
+ ].join("\n");
1945
+ }
1946
+ }
1947
+ };
1948
+ }
1949
+
1950
+ // node/plugins/preset.ts
1951
+ var customElements = /* @__PURE__ */ new Set([
1952
+ // katex
1953
+ "annotation",
1954
+ "math",
1955
+ "menclose",
1956
+ "mfrac",
1957
+ "mglyph",
1958
+ "mi",
1959
+ "mlabeledtr",
1960
+ "mn",
1961
+ "mo",
1962
+ "mover",
1963
+ "mpadded",
1964
+ "mphantom",
1965
+ "mroot",
1966
+ "mrow",
1967
+ "mspace",
1968
+ "msqrt",
1969
+ "mstyle",
1970
+ "msub",
1971
+ "msubsup",
1972
+ "msup",
1973
+ "mtable",
1974
+ "mtd",
1975
+ "mtext",
1976
+ "mtr",
1977
+ "munder",
1978
+ "munderover",
1979
+ "semantics"
1980
+ ]);
1981
+ async function ViteSlidevPlugin(options, pluginOptions, serverOptions = {}) {
1982
+ const {
1983
+ vue: vueOptions = {},
1984
+ vuejsx: vuejsxOptions = {},
1985
+ components: componentsOptions = {},
1986
+ icons: iconsOptions = {},
1987
+ remoteAssets: remoteAssetsOptions = {},
1988
+ serverRef: serverRefOptions = {}
1989
+ } = pluginOptions;
1990
+ const {
1991
+ mode,
1992
+ themeRoots,
1993
+ addonRoots,
1994
+ roots,
1995
+ data: { config }
1996
+ } = options;
1997
+ const VuePlugin = Vue({
1998
+ include: [/\.vue$/, /\.md$/],
1999
+ exclude: [],
2000
+ template: {
2001
+ compilerOptions: {
2002
+ isCustomElement(tag) {
2003
+ return customElements.has(tag);
2004
+ }
2005
+ },
2006
+ ...vueOptions?.template
2007
+ },
2008
+ ...vueOptions
2009
+ });
2010
+ const VueJsxPlugin = VueJsx(vuejsxOptions);
2011
+ const MarkdownPlugin = await createMarkdownPlugin(options, pluginOptions);
2012
+ const drawingData = await loadDrawings(options);
2013
+ const publicRoots = [...themeRoots, ...addonRoots].map((i) => join6(i, "public")).filter(existsSync3);
2014
+ const plugins = [
2015
+ MarkdownPlugin,
2016
+ VueJsxPlugin,
2017
+ VuePlugin,
2018
+ createSlidesLoader(options, pluginOptions, serverOptions),
2019
+ Components({
2020
+ extensions: ["vue", "md", "js", "ts", "jsx", "tsx"],
2021
+ dirs: [
2022
+ join6(options.clientRoot, "builtin"),
2023
+ ...roots.map((i) => join6(i, "components")),
2024
+ "src/components",
2025
+ "components",
2026
+ join6(process.cwd(), "components")
2027
+ ],
2028
+ include: [/\.vue$/, /\.vue\?vue/, /\.vue\?v=/, /\.md$/, /\.md\?vue/],
2029
+ exclude: [],
2030
+ resolvers: [
2031
+ IconsResolver({
2032
+ prefix: "",
2033
+ customCollections: Object.keys(iconsOptions.customCollections || [])
2034
+ })
2035
+ ],
2036
+ dts: false,
2037
+ ...componentsOptions
2038
+ }),
2039
+ Icons({
2040
+ defaultClass: "slidev-icon",
2041
+ collectionsNodeResolvePath: fileURLToPath(import.meta.url),
2042
+ ...iconsOptions
2043
+ }),
2044
+ config.remoteAssets === true || config.remoteAssets === mode ? import("vite-plugin-remote-assets").then((r) => r.VitePluginRemoteAssets({
2045
+ rules: [
2046
+ ...r.DefaultRules,
2047
+ {
2048
+ match: /\b(https?:\/\/image.unsplash\.com.*?)(?=[`'")\]])/ig,
2049
+ ext: ".png"
2050
+ }
2051
+ ],
2052
+ resolveMode: (id) => id.endsWith("index.html") ? "relative" : "@fs",
2053
+ awaitDownload: mode === "build",
2054
+ ...remoteAssetsOptions
2055
+ })) : null,
2056
+ ServerRef({
2057
+ debug: process.env.NODE_ENV === "development",
2058
+ state: {
2059
+ sync: false,
2060
+ nav: {
2061
+ page: 0,
2062
+ clicks: 0
2063
+ },
2064
+ drawings: drawingData,
2065
+ ...serverRefOptions.state
2066
+ },
2067
+ onChanged(key, data, patch, timestamp) {
2068
+ serverRefOptions.onChanged && serverRefOptions.onChanged(key, data, patch, timestamp);
2069
+ if (!options.data.config.drawings.persist)
2070
+ return;
2071
+ if (key === "drawings")
2072
+ writeDrawings(options, patch ?? data);
2073
+ }
2074
+ }),
2075
+ createConfigPlugin(options),
2076
+ createClientSetupPlugin(options),
2077
+ createMonacoTypesLoader(options),
2078
+ createFixPlugins(options),
2079
+ publicRoots.length ? import("vite-plugin-static-copy").then((r) => r.viteStaticCopy({
2080
+ silent: true,
2081
+ targets: publicRoots.map((r2) => ({
2082
+ src: `${r2}/*`,
2083
+ dest: "theme"
2084
+ }))
2085
+ })) : null,
2086
+ options.inspect ? import("vite-plugin-inspect").then((r) => (r.default || r)({
2087
+ dev: true,
2088
+ build: true
2089
+ })) : null,
2090
+ config.css === "none" ? null : import("./unocss-M5KPNI4Z.mjs").then((r) => r.createUnocssPlugin(options, pluginOptions))
2091
+ ];
2092
+ return (await Promise.all(plugins)).flat().filter(notNullish2);
2093
+ }
2094
+
2095
+ export {
2096
+ version,
2097
+ checkEngine,
2098
+ getIndexHtml,
2099
+ mergeViteConfigs,
2100
+ ViteSlidevPlugin
2101
+ };