volute 0.40.1 → 0.41.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.
Files changed (155) hide show
  1. package/README.md +2 -2
  2. package/dist/{accept-IVHOHXQS.js → accept-AHAOUFBK.js} +1 -1
  3. package/dist/{activity-events-DS4QRWBY.js → activity-events-EQGBUEZ7.js} +4 -4
  4. package/dist/{ai-service-AUWIPWLP.js → ai-service-ZHEPFC3U.js} +5 -5
  5. package/dist/{api-client-NFM6GX2N.js → api-client-LC5YRA32.js} +1 -1
  6. package/dist/{archive-UDHFZN4G.js → archive-LJAXDDEY.js} +4 -4
  7. package/dist/{auth-X6ZITZ7D.js → auth-VYW2ECCE.js} +5 -5
  8. package/dist/{bridge-MSZC4HUT.js → bridge-F3ZJEKDN.js} +1 -1
  9. package/dist/{chat-JD3TJINV.js → chat-FO722GU2.js} +9 -9
  10. package/dist/{chunk-4UMXOMZ6.js → chunk-2I7OKOYV.js} +2 -2
  11. package/dist/{chunk-3Y7UDHO7.js → chunk-2R4JIZCB.js} +3 -3
  12. package/dist/{chunk-QYI65HCL.js → chunk-2RQIIKFC.js} +2 -2
  13. package/dist/{chunk-6SYHHEQ7.js → chunk-4ED2DBNC.js} +1 -1
  14. package/dist/{chunk-E25SO3QW.js → chunk-6TPRURK5.js} +3 -3
  15. package/dist/{chunk-ITH5ZLZJ.js → chunk-6ZAT5PYV.js} +1 -1
  16. package/dist/{chunk-LZ6CQYRO.js → chunk-AXNAK3HT.js} +10 -8
  17. package/dist/{chunk-PKGA23XM.js → chunk-CYUNO4BM.js} +1 -1
  18. package/dist/{chunk-MNUXL4XN.js → chunk-FEQPNCXB.js} +1 -1
  19. package/dist/{chunk-5EVW4KOD.js → chunk-FU5YDH6Q.js} +3 -3
  20. package/dist/{chunk-NERYUSER.js → chunk-GMFCSXWB.js} +1 -1
  21. package/dist/{chunk-YHWGN4FX.js → chunk-GSOEUMVO.js} +1 -1
  22. package/dist/{chunk-QV7P3TYO.js → chunk-JIGVTFIR.js} +5 -5
  23. package/dist/chunk-K3NQKI34.js +10 -0
  24. package/dist/{chunk-2HZRJ35V.js → chunk-MHFAWJCC.js} +1 -1
  25. package/dist/{chunk-I57LLNAQ.js → chunk-MU2B7A3L.js} +1 -1
  26. package/dist/{chunk-DNU6XLE2.js → chunk-N64Q7FMP.js} +1 -1
  27. package/dist/{chunk-SVXOBKQY.js → chunk-OQ7UEW67.js} +2 -2
  28. package/dist/{chunk-ANSTTB55.js → chunk-PP5CGT2P.js} +20 -21
  29. package/dist/{chunk-TOANT6FD.js → chunk-SWY4DJ67.js} +2 -2
  30. package/dist/{chunk-KMHC36CA.js → chunk-U7UASV36.js} +1 -1
  31. package/dist/{chunk-KAB6UGOL.js → chunk-UU3Q65US.js} +1 -1
  32. package/dist/{chunk-JYQQDI3M.js → chunk-V67XMNGP.js} +2 -2
  33. package/dist/{chunk-B4WPXYPI.js → chunk-VDODEQSJ.js} +6 -1
  34. package/dist/{chunk-S4SXBQ7F.js → chunk-VK2YD7VJ.js} +43 -35
  35. package/dist/{chunk-BLAXARBZ.js → chunk-W5Z2H3LU.js} +194 -1313
  36. package/dist/{chunk-46DYYHN6.js → chunk-WSRGS4XP.js} +34 -0
  37. package/dist/{chunk-AEAZRTEV.js → chunk-Y2XLASFJ.js} +1 -1
  38. package/dist/chunk-YATR5BXD.js +1212 -0
  39. package/dist/{chunk-YTNBO7S6.js → chunk-YN6ISG7A.js} +11 -11
  40. package/dist/cli.js +24 -24
  41. package/dist/{clock-YLDJUKBW.js → clock-BMLJ2TR6.js} +3 -3
  42. package/dist/{cloud-sync-MAQCJEFJ.js → cloud-sync-GV6O2HN2.js} +19 -18
  43. package/dist/{config-PO4EZLIK.js → config-QB7W3Z7P.js} +4 -4
  44. package/dist/connectors/discord-bridge.js +1 -1
  45. package/dist/connectors/slack-bridge.js +1 -1
  46. package/dist/connectors/telegram-bridge.js +1 -1
  47. package/dist/{conversations-AYLXPOGC.js → conversations-KW7IYESK.js} +5 -5
  48. package/dist/{create-ZMTGINV3.js → create-C3BBFYV7.js} +1 -1
  49. package/dist/{create-T4UJ64WB.js → create-CTPXWFTL.js} +5 -5
  50. package/dist/{daemon-client-H6MEKK2W.js → daemon-client-2MIPKY3E.js} +1 -1
  51. package/dist/{daemon-restart-LP2DR24J.js → daemon-restart-W47YDE5E.js} +9 -9
  52. package/dist/daemon.js +155 -111
  53. package/dist/db-D4FVCA5I.js +9 -0
  54. package/dist/{db-FSYOTHSN.js → db-IJL6B26S.js} +1 -1
  55. package/dist/{delete-TXVOH2OC.js → delete-NLXES2C7.js} +3 -3
  56. package/dist/delivery-manager-EB52CQ5X.js +33 -0
  57. package/dist/{delivery-router-T6CYTS3M.js → delivery-router-Y66OXJPM.js} +4 -4
  58. package/dist/down-JVHNXOFU.js +17 -0
  59. package/dist/echo-text-QVPS6QDM.js +32 -0
  60. package/dist/{env-77IOWG4U.js → env-IQ6Q2333.js} +1 -1
  61. package/dist/exec-R2WWZ6FH.js +17 -0
  62. package/dist/{export-TZKOCSCE.js → export-ZZ5WWBUH.js} +6 -6
  63. package/dist/{extension-35NB6GHW.js → extension-LZYHBNLV.js} +1 -1
  64. package/dist/{extensions-LQX2N7TI.js → extensions-AGANCIQA.js} +19 -18
  65. package/dist/{files-WNNVJWJB.js → files-Q2Z4LQZP.js} +4 -4
  66. package/dist/{import-BNNFCQ7U.js → import-MFYCBS4K.js} +11 -11
  67. package/dist/{isolation-4Q4P7HRV.js → isolation-7F3MA4G7.js} +4 -4
  68. package/dist/{join-E2EJEXZO.js → join-6SZCA5FX.js} +3 -3
  69. package/dist/{list-BYCEDASJ.js → list-KHJZJPEJ.js} +1 -1
  70. package/dist/{login-JNSIYFVH.js → login-GYTH67ES.js} +1 -1
  71. package/dist/{login-Y6UAYQVO.js → login-WY3DADVB.js} +3 -3
  72. package/dist/{logout-VHGWVH63.js → logout-TFZHWNVL.js} +3 -3
  73. package/dist/{logout-M6FI62BL.js → logout-YHQLOFLR.js} +1 -1
  74. package/dist/message-delivery-X4CZE2L6.js +41 -0
  75. package/dist/{mind-ELPD6VBP.js → mind-XIKEPJNS.js} +19 -19
  76. package/dist/{mind-activity-tracker-XFRVGXFS.js → mind-activity-tracker-RSIWUUJK.js} +5 -5
  77. package/dist/{mind-history-W4JPTPTV.js → mind-history-WHCNZ6I5.js} +1 -1
  78. package/dist/{mind-list-QROHCLGT.js → mind-list-H3HC2ZRG.js} +1 -1
  79. package/dist/mind-manager-VU3RGCXD.js +31 -0
  80. package/dist/{mind-profile-3LNKXNPA.js → mind-profile-7VYRJGFZ.js} +2 -2
  81. package/dist/mind-service-L7LMMDYJ.js +37 -0
  82. package/dist/{mind-sleep-PVCMLTAH.js → mind-sleep-ZL5ZXFTM.js} +1 -1
  83. package/dist/{mind-status-RAJFLRCN.js → mind-status-ZWULKOUO.js} +1 -1
  84. package/dist/{mind-wake-HZUOVE7J.js → mind-wake-HK5ORGUK.js} +1 -1
  85. package/dist/{package-GO3PHHUF.js → package-2X7UNSTQ.js} +6 -5
  86. package/dist/{read-OOINVR2H.js → read-CP7MYMJQ.js} +1 -1
  87. package/dist/{read-stdin-P6HCZUAA.js → read-stdin-4B5UYPPM.js} +1 -1
  88. package/dist/{register-ISOH34RF.js → register-XOBFEMI4.js} +1 -1
  89. package/dist/{registry-GV35XFT7.js → registry-RAXNFN7K.js} +5 -3
  90. package/dist/{reject-ZBWP62X5.js → reject-43AGXB6B.js} +1 -1
  91. package/dist/{restart-QBJV5455.js → restart-O5QIYQJT.js} +1 -1
  92. package/dist/{sandbox-5R32QKWQ.js → sandbox-O3GZTS7J.js} +5 -5
  93. package/dist/scheduler-SXELVRWO.js +31 -0
  94. package/dist/{schema-LYQUDL7G.js → schema-HHYJDG7B.js} +2 -2
  95. package/dist/{seed-MO2C7CWC.js → seed-I4CNKTKZ.js} +2 -2
  96. package/dist/{seed-check-3WXXRHTC.js → seed-check-HZPVFJKZ.js} +2 -2
  97. package/dist/{seed-cmd-ETIF4WD6.js → seed-cmd-YTQYWCZF.js} +4 -4
  98. package/dist/{seed-create-BPQC2IOR.js → seed-create-MDBTVADS.js} +7 -7
  99. package/dist/{seed-sprout-TX72K33T.js → seed-sprout-N6O5FBPY.js} +11 -11
  100. package/dist/{send-WO3CVG73.js → send-5XA7LRNB.js} +4 -4
  101. package/dist/{service-WMV6R6VJ.js → service-AY5TGWJX.js} +6 -6
  102. package/dist/service-install-NLGAVTQS.js +17 -0
  103. package/dist/{setup-OTEC3ZPM.js → setup-3434PQ5Q.js} +4 -4
  104. package/dist/{setup-ZTW4FVMQ.js → setup-47NBOCZL.js} +9 -9
  105. package/dist/{skill-QHACP7EU.js → skill-ICN6Y2ZF.js} +1 -1
  106. package/dist/{skills-JEWMHIIE.js → skills-YTLBAF32.js} +7 -7
  107. package/dist/sleep-manager-T3AXQB3R.js +35 -0
  108. package/dist/spirit-KTBHLULO.js +24 -0
  109. package/dist/{split-7AO4IO42.js → split-5YBEQTBF.js} +3 -3
  110. package/dist/{sprout-NFJZKYEW.js → sprout-4ZUJUNDQ.js} +2 -2
  111. package/dist/src-4LFGGNW7.js +2201 -0
  112. package/dist/{src-XNUXP2FP.js → src-O4PRLMKM.js} +1 -1
  113. package/dist/{src-2IMB3V27.js → src-OYWRPLC6.js} +1 -1
  114. package/dist/{start-2U57BBK7.js → start-LMXXRR3X.js} +1 -1
  115. package/dist/{status-BRYYYO7C.js → status-VMOZUIZ2.js} +7 -7
  116. package/dist/{stop-QILBDUAR.js → stop-TWDKVEUX.js} +1 -1
  117. package/dist/system-chat-HCPHUQGI.js +35 -0
  118. package/dist/{systems-3XTAHA35.js → systems-Y2WZV2K4.js} +4 -4
  119. package/dist/{tailscale-X4HRKRTW.js → tailscale-PK3AI5EV.js} +3 -3
  120. package/dist/template-hash-JARTCRGS.js +9 -0
  121. package/dist/turn-tracker-SZBSL7LK.js +35 -0
  122. package/dist/up-VGVPOB6J.js +19 -0
  123. package/dist/{update-OY2JYXYK.js → update-3ANTQO54.js} +7 -7
  124. package/dist/{update-check-IUB7QHAF.js → update-check-4O6DKUOF.js} +4 -4
  125. package/dist/{upgrade-25J6AE47.js → upgrade-RXFZR5FI.js} +3 -3
  126. package/dist/{variant-5LQOPCQA.js → variant-HHDTW74J.js} +1 -1
  127. package/dist/{version-notify-N37N2C4G.js → version-notify-SSNAWZMX.js} +21 -20
  128. package/dist/{volute-config-7FO6QKWU.js → volute-config-TS62GS6A.js} +1 -1
  129. package/package.json +5 -4
  130. package/templates/claude/package.json.tmpl +1 -1
  131. package/templates/codex/package.json.tmpl +1 -1
  132. package/templates/pi/package.json.tmpl +2 -1
  133. package/templates/pi/src/agent.ts +1 -1
  134. package/templates/pi/src/lib/content.ts +1 -1
  135. package/templates/pi/src/lib/event-handler.ts +1 -1
  136. package/templates/pi/src/lib/reply-instructions-extension.ts +1 -1
  137. package/templates/pi/src/lib/resolve-model.ts +4 -4
  138. package/templates/pi/src/lib/subagents.ts +2 -2
  139. package/dist/chunk-LMMQX4CK.js +0 -49
  140. package/dist/db-ZEPKEJJD.js +0 -9
  141. package/dist/delivery-manager-VNHLQTTO.js +0 -30
  142. package/dist/down-6DYO2QV7.js +0 -17
  143. package/dist/echo-text-QFCH3H6G.js +0 -31
  144. package/dist/exec-5DGKQ5V3.js +0 -17
  145. package/dist/message-delivery-7BCYJLH2.js +0 -40
  146. package/dist/mind-manager-EDCLALBF.js +0 -30
  147. package/dist/mind-service-WTOFVNLW.js +0 -36
  148. package/dist/scheduler-GQBDCGLU.js +0 -30
  149. package/dist/service-install-W3FQXJKB.js +0 -17
  150. package/dist/sleep-manager-5277OBHI.js +0 -34
  151. package/dist/spirit-NVXWSVKM.js +0 -24
  152. package/dist/src-OS75U2O7.js +0 -241910
  153. package/dist/system-chat-LQSJVY55.js +0 -34
  154. package/dist/template-hash-DMHSLRDX.js +0 -9
  155. package/dist/up-4H7TL6WB.js +0 -19
@@ -0,0 +1,2201 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ getAllSites,
4
+ getPublishedPages,
5
+ getRecentPages,
6
+ getSystemPages,
7
+ initDb,
8
+ syncPublishedPages,
9
+ syncSystemPages
10
+ } from "./chunk-QHG4OMZL.js";
11
+ import {
12
+ createExtension
13
+ } from "./chunk-RG5TOL4O.js";
14
+ import "./chunk-K3NQKI34.js";
15
+
16
+ // packages/extensions/pages/src/index.ts
17
+ import { resolve as resolve5 } from "path";
18
+
19
+ // packages/extensions/pages/src/commands.ts
20
+ import { cpSync, existsSync as existsSync2, readdirSync as readdirSync2, readFileSync as readFileSync2, rmSync as rmSync2, statSync as statSync2 } from "fs";
21
+ import { relative as relative2, resolve as resolve2 } from "path";
22
+
23
+ // packages/extensions/pages/src/shared-pages.ts
24
+ import { execFile as execFileCb } from "child_process";
25
+ import {
26
+ chmodSync,
27
+ existsSync,
28
+ mkdirSync,
29
+ readdirSync,
30
+ readFileSync,
31
+ rmSync,
32
+ statSync,
33
+ writeFileSync
34
+ } from "fs";
35
+ import { relative, resolve } from "path";
36
+ function isolationFrom(ctx) {
37
+ return { isIsolationEnabled: ctx.isIsolationEnabled, getMindUser: ctx.getMindUser };
38
+ }
39
+ function execAsync(cmd, args) {
40
+ return new Promise((resolve6, reject) => {
41
+ execFileCb(cmd, args, (err) => {
42
+ if (err) reject(err);
43
+ else resolve6();
44
+ });
45
+ });
46
+ }
47
+ function gitExec(args, opts, isolation) {
48
+ const fullArgs = isolation?.isIsolationEnabled() ? ["-c", "safe.directory=*", ...args] : args;
49
+ return new Promise((resolve6, reject) => {
50
+ execFileCb("git", fullArgs, { cwd: opts.cwd }, (err, stdout, stderr) => {
51
+ if (err) {
52
+ const e = err;
53
+ e.stderr = stderr;
54
+ e.stdout = stdout;
55
+ reject(err);
56
+ } else {
57
+ resolve6(stdout);
58
+ }
59
+ });
60
+ });
61
+ }
62
+ function readWorktreeGitDir(worktreePath2) {
63
+ const dotGit = resolve(worktreePath2, ".git");
64
+ if (!existsSync(dotGit)) return null;
65
+ try {
66
+ const content = readFileSync(dotGit, "utf-8").trim();
67
+ const match = content.match(/^gitdir:\s*(.+)$/);
68
+ return match ? match[1] : null;
69
+ } catch (err) {
70
+ console.warn(`[pages] failed to read .git file at ${dotGit}: ${err.message}`);
71
+ return null;
72
+ }
73
+ }
74
+ function pagesRepoDir(dataDir) {
75
+ return resolve(dataDir, "repo");
76
+ }
77
+ function worktreePath(mindDir) {
78
+ return resolve(mindDir, "home", "pages", "_system");
79
+ }
80
+ async function ensurePagesRepo(dataDir, isolation) {
81
+ const dir = pagesRepoDir(dataDir);
82
+ mkdirSync(dir, { recursive: true });
83
+ if (existsSync(resolve(dir, ".git"))) {
84
+ try {
85
+ await gitExec(["rev-parse", "HEAD"], { cwd: dir }, isolation);
86
+ return;
87
+ } catch (err) {
88
+ const msg = err instanceof Error ? err.message : String(err);
89
+ if (msg.includes("unknown revision") || msg.includes("bad default revision")) {
90
+ console.warn("[pages] repo has no commits, re-initializing");
91
+ rmSync(resolve(dir, ".git"), { recursive: true, force: true });
92
+ } else {
93
+ throw err;
94
+ }
95
+ }
96
+ }
97
+ const isIso = isolation?.isIsolationEnabled() ?? false;
98
+ const initArgs = isIso ? ["init", "--shared=group"] : ["init"];
99
+ await gitExec(initArgs, { cwd: dir }, isolation);
100
+ await gitExec(["checkout", "-b", "main"], { cwd: dir }, isolation);
101
+ writeFileSync(resolve(dir, ".gitkeep"), "");
102
+ await gitExec(["add", "-A"], { cwd: dir }, isolation);
103
+ await gitExec(["commit", "-m", "init pages repo"], { cwd: dir }, isolation);
104
+ if (isIso) {
105
+ try {
106
+ await execAsync("chgrp", ["-R", "volute", dir]);
107
+ } catch {
108
+ console.warn("[pages] failed to chgrp pages repo to volute group");
109
+ }
110
+ chmodSync(dir, 1533);
111
+ }
112
+ }
113
+ async function addPagesWorktree(mindName, mindDir, dataDir, isolation) {
114
+ const dir = pagesRepoDir(dataDir);
115
+ if (!existsSync(resolve(dir, ".git"))) return;
116
+ const wt = worktreePath(mindDir);
117
+ if (existsSync(wt)) return;
118
+ mkdirSync(resolve(mindDir, "home", "pages"), { recursive: true });
119
+ let branchExists = false;
120
+ try {
121
+ await gitExec(["rev-parse", "--verify", mindName], { cwd: dir }, isolation);
122
+ branchExists = true;
123
+ } catch {
124
+ }
125
+ if (branchExists) {
126
+ await gitExec(["worktree", "add", wt, mindName], { cwd: dir }, isolation);
127
+ } else {
128
+ await gitExec(["worktree", "add", "-b", mindName, wt], { cwd: dir }, isolation);
129
+ }
130
+ if (isolation?.isIsolationEnabled()) {
131
+ const user = isolation.getMindUser(mindName);
132
+ try {
133
+ await execAsync("chown", ["-R", `${user}:volute`, wt]);
134
+ } catch {
135
+ console.warn(`[pages] failed to chown worktree for ${mindName}`);
136
+ }
137
+ const wtGitDir = readWorktreeGitDir(wt);
138
+ if (wtGitDir) {
139
+ try {
140
+ await execAsync("chown", ["-R", `${user}:volute`, wtGitDir]);
141
+ } catch {
142
+ console.warn(`[pages] failed to chown worktree git dir for ${mindName}`);
143
+ }
144
+ }
145
+ }
146
+ }
147
+ var pagesLock = Promise.resolve();
148
+ async function withPagesLock(fn) {
149
+ const prev = pagesLock;
150
+ let resolve_;
151
+ pagesLock = new Promise((r) => {
152
+ resolve_ = r;
153
+ });
154
+ await prev;
155
+ try {
156
+ return await fn();
157
+ } finally {
158
+ resolve_();
159
+ }
160
+ }
161
+ async function pagesPull(mindName, mindDir, isolation) {
162
+ return withPagesLock(async () => {
163
+ const wt = worktreePath(mindDir);
164
+ const status = (await gitExec(["status", "--porcelain"], { cwd: wt }, isolation)).trim();
165
+ if (status) {
166
+ await gitExec(["add", "-A"], { cwd: wt }, isolation);
167
+ await gitExec(
168
+ ["commit", "--author", `${mindName} <${mindName}@volute>`, "-m", `wip: ${mindName}`],
169
+ { cwd: wt },
170
+ isolation
171
+ );
172
+ }
173
+ try {
174
+ await gitExec(["rebase", "main"], { cwd: wt }, isolation);
175
+ } catch (err) {
176
+ const errMsg = err instanceof Error ? err.message : String(err);
177
+ const isConflict = errMsg.includes("CONFLICT") || errMsg.includes("could not apply") || errMsg.includes("merge conflict");
178
+ try {
179
+ await gitExec(["rebase", "--abort"], { cwd: wt }, isolation);
180
+ } catch (abortErr) {
181
+ console.error("[pages] rebase abort failed", abortErr);
182
+ }
183
+ if (isConflict) {
184
+ return {
185
+ ok: false,
186
+ conflicts: true,
187
+ message: "Pull conflicts detected \u2014 your changes conflict with main. Reconcile the conflicting files, commit, and pull again."
188
+ };
189
+ }
190
+ console.error("[pages] pull rebase failed", err);
191
+ return { ok: false, message: `Pull failed: ${errMsg}` };
192
+ }
193
+ if (isolation?.isIsolationEnabled()) {
194
+ try {
195
+ await execAsync("chown", ["-R", `${isolation.getMindUser(mindName)}:volute`, wt]);
196
+ } catch {
197
+ }
198
+ }
199
+ return { ok: true, message: "Pulled latest shared changes." };
200
+ });
201
+ }
202
+ async function pagesPullAndMerge(mindName, mindDir, dataDir, message, isolation) {
203
+ return withPagesLock(async () => {
204
+ const wt = worktreePath(mindDir);
205
+ const dir = pagesRepoDir(dataDir);
206
+ const status = (await gitExec(["status", "--porcelain"], { cwd: wt }, isolation)).trim();
207
+ if (status) {
208
+ await gitExec(["add", "-A"], { cwd: wt }, isolation);
209
+ await gitExec(
210
+ ["commit", "--author", `${mindName} <${mindName}@volute>`, "-m", `wip: ${mindName}`],
211
+ { cwd: wt },
212
+ isolation
213
+ );
214
+ }
215
+ try {
216
+ await gitExec(["rebase", "main"], { cwd: wt }, isolation);
217
+ } catch (err) {
218
+ const errMsg = err instanceof Error ? err.message : String(err);
219
+ const isConflict = errMsg.includes("CONFLICT") || errMsg.includes("could not apply") || errMsg.includes("merge conflict");
220
+ try {
221
+ await gitExec(["rebase", "--abort"], { cwd: wt }, isolation);
222
+ } catch (abortErr) {
223
+ console.error("[pages] rebase abort failed", abortErr);
224
+ }
225
+ if (isConflict) {
226
+ return {
227
+ ok: false,
228
+ conflicts: true,
229
+ message: "Pull conflicts detected \u2014 your changes conflict with main. Reconcile the conflicting files, commit, and try again."
230
+ };
231
+ }
232
+ return { ok: false, message: `Pull failed: ${errMsg}` };
233
+ }
234
+ const diff = (await gitExec(["diff", `main...${mindName}`, "--stat"], { cwd: dir }, isolation)).trim();
235
+ if (!diff) {
236
+ return { ok: true, message: "Nothing to publish" };
237
+ }
238
+ try {
239
+ await gitExec(["merge", "--squash", mindName], { cwd: dir }, isolation);
240
+ } catch (err) {
241
+ const errOutput = [
242
+ err.message,
243
+ err.stderr ?? "",
244
+ err.stdout ?? ""
245
+ ].join("\n");
246
+ const isConflict = errOutput.includes("CONFLICT") || errOutput.includes("could not apply");
247
+ try {
248
+ await gitExec(["reset", "--hard", "HEAD"], { cwd: dir }, isolation);
249
+ } catch (resetErr) {
250
+ console.error("[pages] reset after squash conflict failed", resetErr);
251
+ }
252
+ if (isConflict) {
253
+ return { ok: false, conflicts: true, message: "Merge conflicts detected" };
254
+ }
255
+ return { ok: false, message: `Merge failed: ${err.message}` };
256
+ }
257
+ await gitExec(
258
+ ["commit", "--author", `${mindName} <${mindName}@volute>`, "-m", message],
259
+ { cwd: dir },
260
+ isolation
261
+ );
262
+ try {
263
+ await gitExec(["reset", "--hard", "main"], { cwd: wt }, isolation);
264
+ } catch (err) {
265
+ console.error(`[pages] branch reset failed for ${mindName}`, err);
266
+ return {
267
+ ok: true,
268
+ message: "Published to main, but branch reset failed \u2014 run 'volute pages pull' to sync"
269
+ };
270
+ }
271
+ if (isolation?.isIsolationEnabled()) {
272
+ try {
273
+ await execAsync("chown", ["-R", `${isolation.getMindUser(mindName)}:volute`, wt]);
274
+ } catch {
275
+ }
276
+ }
277
+ return { ok: true };
278
+ });
279
+ }
280
+ function collectHtmlFiles(dir) {
281
+ const files = [];
282
+ function walk(d2) {
283
+ let items;
284
+ try {
285
+ items = readdirSync(d2);
286
+ } catch (err) {
287
+ if (err?.code === "ENOENT") return;
288
+ throw err;
289
+ }
290
+ for (const item of items) {
291
+ if (item.startsWith(".")) continue;
292
+ const full = resolve(d2, item);
293
+ try {
294
+ const s = statSync(full);
295
+ if (s.isFile() && item.endsWith(".html")) {
296
+ files.push(relative(dir, full));
297
+ } else if (s.isDirectory()) {
298
+ walk(full);
299
+ }
300
+ } catch (err) {
301
+ if (err?.code === "ENOENT" || err?.code === "EACCES") continue;
302
+ throw err;
303
+ }
304
+ }
305
+ }
306
+ walk(dir);
307
+ return files.sort();
308
+ }
309
+ async function pagesStatus(mindDir, isolation) {
310
+ const wt = worktreePath(mindDir);
311
+ const errors = [];
312
+ const [mainFiles, branchFiles, uncommitted] = await Promise.all([
313
+ gitExec(["ls-tree", "-r", "--name-only", "main"], { cwd: wt }, isolation).then((s) => s.trim().split("\n").filter(Boolean)).catch((err) => {
314
+ errors.push(err);
315
+ return [];
316
+ }),
317
+ gitExec(["ls-tree", "-r", "--name-only", "HEAD"], { cwd: wt }, isolation).then((s) => s.trim().split("\n").filter(Boolean)).catch((err) => {
318
+ errors.push(err);
319
+ return [];
320
+ }),
321
+ gitExec(["status", "--porcelain"], { cwd: wt }, isolation).then((s) => s.trim()).catch((err) => {
322
+ errors.push(err);
323
+ return "";
324
+ })
325
+ ]);
326
+ if (errors.length === 3) {
327
+ throw new Error(`Shared pages git error: ${errors[0].message}`);
328
+ }
329
+ const uncommittedFiles = /* @__PURE__ */ new Set();
330
+ if (uncommitted) {
331
+ for (const line of uncommitted.split("\n")) {
332
+ const match = line.match(/^.{2}\s+(.+)$/);
333
+ if (match) uncommittedFiles.add(match[1]);
334
+ }
335
+ }
336
+ const mainSet = new Set(mainFiles.filter((f) => f.endsWith(".html")));
337
+ const allHtml = /* @__PURE__ */ new Set([
338
+ ...mainFiles.filter((f) => f.endsWith(".html")),
339
+ ...branchFiles.filter((f) => f.endsWith(".html")),
340
+ ...[...uncommittedFiles].filter((f) => f.endsWith(".html"))
341
+ ]);
342
+ if (allHtml.size === 0) return "No shared pages found.";
343
+ const lines = [...allHtml].sort().map((file) => {
344
+ const onMain = mainSet.has(file);
345
+ const isUncommitted = uncommittedFiles.has(file);
346
+ let status;
347
+ if (isUncommitted) {
348
+ status = "uncommitted";
349
+ } else if (onMain) {
350
+ status = "published";
351
+ } else {
352
+ status = "draft";
353
+ }
354
+ return `${status.padEnd(13)} ${file}`;
355
+ });
356
+ return lines.join("\n");
357
+ }
358
+ async function pagesLog(mindDir, limit = 20, isolation) {
359
+ const wt = worktreePath(mindDir);
360
+ const output = (await gitExec(["log", "--oneline", "main", `-${limit}`], { cwd: wt }, isolation)).trim();
361
+ return output || "No history.";
362
+ }
363
+
364
+ // packages/extensions/pages/src/commands.ts
365
+ function createCommands() {
366
+ return {
367
+ publish: {
368
+ description: "Publish all pages (copy to public snapshot)",
369
+ args: [{ name: "message", description: "Commit message for shared publish" }],
370
+ flags: {
371
+ remote: { type: "boolean", description: "Also publish to volute.systems" },
372
+ shared: { type: "boolean", description: "Publish to shared pages repository" }
373
+ },
374
+ handler: async ({ args, flags }, ctx) => {
375
+ const mindName = ctx.mindName;
376
+ if (!mindName) return { error: "No mind specified (use --mind or VOLUTE_MIND)" };
377
+ if (flags.shared) {
378
+ const mindDir2 = ctx.getMindDir(mindName);
379
+ if (!mindDir2) return { error: `Mind not found: ${mindName}` };
380
+ const message = args.message?.trim();
381
+ if (!message)
382
+ return { error: 'Usage: volute pages publish --shared "description of changes"' };
383
+ try {
384
+ const result = await pagesPullAndMerge(
385
+ mindName,
386
+ mindDir2,
387
+ ctx.dataDir,
388
+ message,
389
+ isolationFrom(ctx)
390
+ );
391
+ if (!result.ok) {
392
+ return {
393
+ error: result.message || "Merge conflicts detected \u2014 pull, reconcile, and try again."
394
+ };
395
+ }
396
+ let syncWarning = "";
397
+ if (result.ok && ctx.db) {
398
+ const repoDir = resolve2(ctx.dataDir, "repo");
399
+ try {
400
+ syncSystemPages(ctx.db, collectHtmlFiles(repoDir), mindName);
401
+ } catch (err) {
402
+ console.error("[pages] failed to sync system pages to DB:", err);
403
+ syncWarning = "\nWarning: failed to sync pages to dashboard \u2014 they may not appear in the UI until the next daemon restart.";
404
+ }
405
+ }
406
+ return { output: (result.message || "Published shared pages.") + syncWarning };
407
+ } catch (err) {
408
+ return { error: `Shared publish failed: ${err.message}` };
409
+ }
410
+ }
411
+ const remote = flags.remote;
412
+ const mindDir = ctx.getMindDir(mindName);
413
+ if (!mindDir) return { error: `Mind not found: ${mindName}` };
414
+ const sourceDir = resolve2(mindDir, "home", "pages");
415
+ if (!existsSync2(sourceDir)) return { error: "No pages directory found (home/pages/)" };
416
+ const db = ctx.db;
417
+ if (!db) return { error: "Database not available" };
418
+ const snapshotDir = resolve2(ctx.dataDir, "sites", mindName);
419
+ try {
420
+ if (existsSync2(snapshotDir)) rmSync2(snapshotDir, { recursive: true });
421
+ cpSync(sourceDir, snapshotDir, {
422
+ recursive: true,
423
+ filter: (src) => !src.endsWith("/_system") && !src.includes("/_system/")
424
+ });
425
+ } catch (err) {
426
+ return { error: `Failed to publish snapshot: ${err.message}` };
427
+ }
428
+ const pageFiles = collectFiles(snapshotDir, snapshotDir, [".html", ".md"]);
429
+ let diff;
430
+ try {
431
+ diff = syncPublishedPages(db, mindName, pageFiles);
432
+ } catch (err) {
433
+ return { error: `Failed to update page database: ${err.message}` };
434
+ }
435
+ for (const file of diff.added) {
436
+ ctx.publishActivity({
437
+ type: "page_published",
438
+ mind: mindName,
439
+ summary: `${mindName} published ${file}`,
440
+ metadata: { file, iframeUrl: `/ext/pages/public/${mindName}/${file}` }
441
+ });
442
+ }
443
+ for (const file of diff.removed) {
444
+ ctx.publishActivity({
445
+ type: "page_removed",
446
+ mind: mindName,
447
+ summary: `${mindName} removed ${file}`,
448
+ metadata: { file }
449
+ });
450
+ }
451
+ let output = `Published ${pageFiles.length} files`;
452
+ const parts = [];
453
+ if (diff.added.length > 0) parts.push(`${diff.added.length} new`);
454
+ if (diff.updated.length > 0) parts.push(`${diff.updated.length} updated`);
455
+ if (diff.removed.length > 0) parts.push(`${diff.removed.length} removed`);
456
+ if (parts.length > 0) output += ` (${parts.join(", ")})`;
457
+ if (remote) {
458
+ const config = ctx.getSystemsConfig();
459
+ if (!config)
460
+ return {
461
+ error: "Not connected to volute.systems. Run volute systems register or login first."
462
+ };
463
+ const allFiles = collectFiles(snapshotDir, snapshotDir);
464
+ const files = {};
465
+ for (const f of allFiles) {
466
+ const fp = resolve2(snapshotDir, f);
467
+ files[f] = readFileSync2(fp).toString("base64");
468
+ }
469
+ try {
470
+ const res = await fetch(`${config.apiUrl}/api/pages/publish/${mindName}`, {
471
+ method: "PUT",
472
+ headers: {
473
+ "Content-Type": "application/json",
474
+ Authorization: `Bearer ${config.apiKey}`
475
+ },
476
+ body: JSON.stringify({ files })
477
+ });
478
+ const data = await res.json().catch(() => ({}));
479
+ if (!res.ok) {
480
+ const errMsg = data.error || `HTTP ${res.status}`;
481
+ output += `
482
+ Warning: remote publish failed: ${errMsg}`;
483
+ } else if (data.url) {
484
+ output += `
485
+ Remote: ${data.url}`;
486
+ }
487
+ } catch (err) {
488
+ output += `
489
+ Warning: remote publish failed: ${err.message}`;
490
+ }
491
+ }
492
+ return { output };
493
+ }
494
+ },
495
+ list: {
496
+ description: "List pages with publish status",
497
+ flags: {
498
+ all: { type: "boolean", description: "Show pages from all minds" },
499
+ shared: { type: "boolean", description: "Show shared pages status" }
500
+ },
501
+ handler: async ({ flags }, ctx) => {
502
+ const db = ctx.db;
503
+ if (!db) return { error: "Database not available" };
504
+ const allFlag = flags.all;
505
+ const port = process.env.VOLUTE_DAEMON_PORT || "1618";
506
+ if (allFlag) {
507
+ const { getAllSites: getAllSites2, getSystemPages: getSystemPages2 } = await import("./db-IJL6B26S.js");
508
+ const sites = getAllSites2(db);
509
+ const system = getSystemPages2(db);
510
+ const lines2 = [];
511
+ if (system) {
512
+ for (const f of system.files) {
513
+ const url = `http://localhost:${port}/ext/pages/public/_system/${f.file}`;
514
+ const author = f.author ? ` (${f.author})` : "";
515
+ lines2.push(`_system${author.padStart(10)} ${f.file.padEnd(25)} ${url}`);
516
+ }
517
+ }
518
+ for (const site of sites) {
519
+ for (const f of site.files) {
520
+ const url = `http://localhost:${port}/ext/pages/public/${site.mind}/${f.file}`;
521
+ lines2.push(`${site.mind.padEnd(15)} ${f.file.padEnd(25)} ${url}`);
522
+ }
523
+ }
524
+ return { output: lines2.length > 0 ? lines2.join("\n") : "No published pages found." };
525
+ }
526
+ const mindName = ctx.mindName;
527
+ if (!mindName) return { error: "No mind specified (use --mind or VOLUTE_MIND)" };
528
+ if (flags.shared) {
529
+ const mindDir2 = ctx.getMindDir(mindName);
530
+ if (!mindDir2) return { error: `Mind not found: ${mindName}` };
531
+ try {
532
+ const status = await pagesStatus(mindDir2, isolationFrom(ctx));
533
+ return { output: status };
534
+ } catch (err) {
535
+ return { error: `Failed to check shared status: ${err.message}` };
536
+ }
537
+ }
538
+ const mindDir = ctx.getMindDir(mindName);
539
+ if (!mindDir) return { error: `Mind not found: ${mindName}` };
540
+ const sourceDir = resolve2(mindDir, "home", "pages");
541
+ const published = new Set(getPublishedPages(db, mindName).map((p) => p.file));
542
+ const draftFiles = existsSync2(sourceDir) ? collectFiles(sourceDir, sourceDir, [".html", ".md"]) : [];
543
+ const allFiles = /* @__PURE__ */ new Set([...published, ...draftFiles]);
544
+ if (allFiles.size === 0) return { output: "No pages found." };
545
+ const lines = [...allFiles].sort().map((file) => {
546
+ const isPublished = published.has(file);
547
+ const status = isPublished ? "published" : "draft";
548
+ const url = isPublished ? `http://localhost:${port}/ext/pages/public/${mindName}/${file}` : "";
549
+ return `${status.padEnd(11)} ${file.padEnd(25)} ${url}`;
550
+ });
551
+ return { output: lines.join("\n") };
552
+ }
553
+ },
554
+ pull: {
555
+ description: "Pull latest shared page changes from other minds",
556
+ handler: async (_parsed, ctx) => {
557
+ const mindName = ctx.mindName;
558
+ if (!mindName) return { error: "No mind specified (use --mind or VOLUTE_MIND)" };
559
+ const mindDir = ctx.getMindDir(mindName);
560
+ if (!mindDir) return { error: `Mind not found: ${mindName}` };
561
+ try {
562
+ const result = await pagesPull(mindName, mindDir, isolationFrom(ctx));
563
+ if (!result.ok) {
564
+ return { error: result.message || "Pull failed." };
565
+ }
566
+ return { output: result.message || "Pulled latest shared changes." };
567
+ } catch (err) {
568
+ return { error: `Pull failed: ${err.message}` };
569
+ }
570
+ }
571
+ },
572
+ log: {
573
+ description: "View shared pages commit history",
574
+ flags: {
575
+ limit: { type: "number", description: "Max number of entries to show (default: 20)" }
576
+ },
577
+ handler: async ({ flags }, ctx) => {
578
+ const mindName = ctx.mindName;
579
+ if (!mindName) return { error: "No mind specified (use --mind or VOLUTE_MIND)" };
580
+ const mindDir = ctx.getMindDir(mindName);
581
+ if (!mindDir) return { error: `Mind not found: ${mindName}` };
582
+ const limit = flags.limit ?? 20;
583
+ try {
584
+ const output = await pagesLog(mindDir, limit, isolationFrom(ctx));
585
+ return { output };
586
+ } catch (err) {
587
+ return { error: `Failed to read shared log: ${err.message}` };
588
+ }
589
+ }
590
+ }
591
+ };
592
+ }
593
+ function collectFiles(dir, baseDir, ext) {
594
+ const files = [];
595
+ let items;
596
+ try {
597
+ items = readdirSync2(dir);
598
+ } catch (err) {
599
+ console.error(`[pages] failed to read directory ${dir}: ${err.message}`);
600
+ return files;
601
+ }
602
+ for (const item of items) {
603
+ if (item.startsWith(".")) continue;
604
+ const fullPath = resolve2(dir, item);
605
+ try {
606
+ const s = statSync2(fullPath);
607
+ const matchesExt = !ext || (Array.isArray(ext) ? ext.some((e) => item.endsWith(e)) : item.endsWith(ext));
608
+ if (s.isFile() && matchesExt) {
609
+ files.push(relative2(baseDir, fullPath));
610
+ } else if (s.isDirectory()) {
611
+ files.push(...collectFiles(fullPath, baseDir, ext));
612
+ }
613
+ } catch (err) {
614
+ console.error(`[pages] failed to stat ${fullPath}: ${err.message}`);
615
+ }
616
+ }
617
+ return files.sort();
618
+ }
619
+
620
+ // packages/extensions/pages/src/routes.ts
621
+ import { readFile, stat } from "fs/promises";
622
+ import { extname, resolve as resolve4 } from "path";
623
+ import { Hono } from "hono";
624
+
625
+ // packages/extensions/pages/src/cache.ts
626
+ function mapFiles(mind, files) {
627
+ return files.map((f) => ({
628
+ file: f.file,
629
+ modified: f.updated_at,
630
+ url: `/ext/pages/public/${mind}/${f.file}`,
631
+ author: f.author
632
+ }));
633
+ }
634
+ function getSites(db) {
635
+ const sites = getAllSites(db).map((site) => ({
636
+ name: site.mind,
637
+ label: site.mind,
638
+ pages: mapFiles(site.mind, site.files)
639
+ }));
640
+ const system = getSystemPages(db);
641
+ const systemSite = system ? { name: "_system", label: "Shared Pages", pages: mapFiles("_system", system.files) } : null;
642
+ return { sites, systemSite };
643
+ }
644
+ function getRecentPagesList(db, opts) {
645
+ const rows = getRecentPages(db, opts);
646
+ return rows.map((r) => ({
647
+ mind: r.mind,
648
+ file: r.file,
649
+ modified: r.updated_at,
650
+ url: `/ext/pages/public/${r.mind}/${r.file}`,
651
+ author: r.author
652
+ }));
653
+ }
654
+
655
+ // packages/extensions/pages/src/markdown.ts
656
+ import { existsSync as existsSync3 } from "fs";
657
+ import { dirname, relative as relative3, resolve as resolve3 } from "path";
658
+ import DOMPurify from "isomorphic-dompurify";
659
+
660
+ // node_modules/marked/lib/marked.esm.js
661
+ function M() {
662
+ return { async: false, breaks: false, extensions: null, gfm: true, hooks: null, pedantic: false, renderer: null, silent: false, tokenizer: null, walkTokens: null };
663
+ }
664
+ var T = M();
665
+ function N(l3) {
666
+ T = l3;
667
+ }
668
+ var _ = { exec: () => null };
669
+ function E(l3) {
670
+ let e = [];
671
+ return (t) => {
672
+ let n = Math.max(0, Math.min(3, t - 1)), s = e[n];
673
+ return s || (s = l3(n), e[n] = s), s;
674
+ };
675
+ }
676
+ function d(l3, e = "") {
677
+ let t = typeof l3 == "string" ? l3 : l3.source, n = { replace: (s, r) => {
678
+ let i = typeof r == "string" ? r : r.source;
679
+ return i = i.replace(m.caret, "$1"), t = t.replace(s, i), n;
680
+ }, getRegex: () => new RegExp(t, e) };
681
+ return n;
682
+ }
683
+ var Te = ((l3 = "") => {
684
+ try {
685
+ return !!new RegExp("(?<=1)(?<!1)" + l3);
686
+ } catch {
687
+ return false;
688
+ }
689
+ })();
690
+ var m = { codeRemoveIndent: /^(?: {1,4}| {0,3}\t)/gm, outputLinkReplace: /\\([\[\]])/g, indentCodeCompensation: /^(\s+)(?:```)/, beginningSpace: /^\s+/, endingHash: /#$/, startingSpaceChar: /^ /, endingSpaceChar: / $/, nonSpaceChar: /[^ ]/, newLineCharGlobal: /\n/g, tabCharGlobal: /\t/g, multipleSpaceGlobal: /\s+/g, blankLine: /^[ \t]*$/, doubleBlankLine: /\n[ \t]*\n[ \t]*$/, blockquoteStart: /^ {0,3}>/, blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g, blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm, listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g, listIsTask: /^\[[ xX]\] +\S/, listReplaceTask: /^\[[ xX]\] +/, listTaskCheckbox: /\[[ xX]\]/, anyLine: /\n.*\n/, hrefBrackets: /^<(.*)>$/, tableDelimiter: /[:|]/, tableAlignChars: /^\||\| *$/g, tableRowBlankLine: /\n[ \t]*$/, tableAlignRight: /^ *-+: *$/, tableAlignCenter: /^ *:-+: *$/, tableAlignLeft: /^ *:-+ *$/, startATag: /^<a /i, endATag: /^<\/a>/i, startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i, endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i, startAngleBracket: /^</, endAngleBracket: />$/, pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/, unicodeAlphaNumeric: /[\p{L}\p{N}]/u, escapeTest: /[&<>"']/, escapeReplace: /[&<>"']/g, escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/, escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g, caret: /(^|[^\[])\^/g, percentDecode: /%25/g, findPipe: /\|/g, splitPipe: / \|/, slashPipe: /\\\|/g, carriageReturn: /\r\n|\r/g, spaceLine: /^ +$/gm, notSpaceStart: /^\S*/, endingNewline: /\n$/, listItemRegex: (l3) => new RegExp(`^( {0,3}${l3})((?:[ ][^\\n]*)?(?:\\n|$))`), nextBulletRegex: E((l3) => new RegExp(`^ {0,${l3}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)), hrRegex: E((l3) => new RegExp(`^ {0,${l3}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)), fencesBeginRegex: E((l3) => new RegExp(`^ {0,${l3}}(?:\`\`\`|~~~)`)), headingBeginRegex: E((l3) => new RegExp(`^ {0,${l3}}#`)), htmlBeginRegex: E((l3) => new RegExp(`^ {0,${l3}}<(?:[a-z].*>|!--)`, "i")), blockquoteBeginRegex: E((l3) => new RegExp(`^ {0,${l3}}>`)) };
691
+ var Oe = /^(?:[ \t]*(?:\n|$))+/;
692
+ var we = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/;
693
+ var ye = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;
694
+ var B = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;
695
+ var Pe = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;
696
+ var j = / {0,3}(?:[*+-]|\d{1,9}[.)])/;
697
+ var oe = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/;
698
+ var ae = d(oe).replace(/bull/g, j).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/\|table/g, "").getRegex();
699
+ var Se = d(oe).replace(/bull/g, j).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/table/g, / {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex();
700
+ var F = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/;
701
+ var $e = /^[^\n]+/;
702
+ var U = /(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/;
703
+ var Le = d(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label", U).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex();
704
+ var _e = d(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g, j).getRegex();
705
+ var H = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";
706
+ var K = /<!--(?:-?>|[\s\S]*?(?:-->|$))/;
707
+ var ze = d("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))", "i").replace("comment", K).replace("tag", H).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
708
+ var le = d(F).replace("hr", B).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", H).getRegex();
709
+ var Me = d(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", le).getRegex();
710
+ var W = { blockquote: Me, code: we, def: Le, fences: ye, heading: Pe, hr: B, html: ze, lheading: ae, list: _e, newline: Oe, paragraph: le, table: _, text: $e };
711
+ var se = d("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", B).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", "(?: {4}| {0,3} )[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", H).getRegex();
712
+ var Ee = { ...W, lheading: Se, table: se, paragraph: d(F).replace("hr", B).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", se).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", H).getRegex() };
713
+ var Ie = { ...W, html: d(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", K).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(), def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, heading: /^(#{1,6})(.*)(?:\n+|$)/, fences: _, lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, paragraph: d(F).replace("hr", B).replace("heading", ` *#{1,6} *[^
714
+ ]`).replace("lheading", ae).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex() };
715
+ var Ae = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
716
+ var Ce = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
717
+ var ue = /^( {2,}|\\)\n(?!\s*$)/;
718
+ var Be = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/;
719
+ var I = /[\p{P}\p{S}]/u;
720
+ var Z = /[\s\p{P}\p{S}]/u;
721
+ var X = /[^\s\p{P}\p{S}]/u;
722
+ var De = d(/^((?![*_])punctSpace)/, "u").replace(/punctSpace/g, Z).getRegex();
723
+ var pe = /(?!~)[\p{P}\p{S}]/u;
724
+ var qe = /(?!~)[\s\p{P}\p{S}]/u;
725
+ var ve = /(?:[^\s\p{P}\p{S}]|~)/u;
726
+ var He = d(/link|precode-code|html/, "g").replace("link", /\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-", Te ? "(?<!`)()" : "(^^|[^`])").replace("code", /(?<b>`+)[^`]+\k<b>(?!`)/).replace("html", /<(?! )[^<>]*?>/).getRegex();
727
+ var ce = /^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/;
728
+ var Ze = d(ce, "u").replace(/punct/g, I).getRegex();
729
+ var Ge = d(ce, "u").replace(/punct/g, pe).getRegex();
730
+ var he = "^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)";
731
+ var Ne = d(he, "gu").replace(/notPunctSpace/g, X).replace(/punctSpace/g, Z).replace(/punct/g, I).getRegex();
732
+ var Qe = d(he, "gu").replace(/notPunctSpace/g, ve).replace(/punctSpace/g, qe).replace(/punct/g, pe).getRegex();
733
+ var je = d("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)", "gu").replace(/notPunctSpace/g, X).replace(/punctSpace/g, Z).replace(/punct/g, I).getRegex();
734
+ var Fe = d(/^~~?(?:((?!~)punct)|[^\s~])/, "u").replace(/punct/g, I).getRegex();
735
+ var Ue = "^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)";
736
+ var Ke = d(Ue, "gu").replace(/notPunctSpace/g, X).replace(/punctSpace/g, Z).replace(/punct/g, I).getRegex();
737
+ var We = d(/\\(punct)/, "gu").replace(/punct/g, I).getRegex();
738
+ var Xe = d(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email", /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex();
739
+ var Je = d(K).replace("(?:-->|$)", "-->").getRegex();
740
+ var Ve = d("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment", Je).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex();
741
+ var v = /(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/;
742
+ var Ye = d(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label", v).replace("href", /<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex();
743
+ var ke = d(/^!?\[(label)\]\[(ref)\]/).replace("label", v).replace("ref", U).getRegex();
744
+ var de = d(/^!?\[(ref)\](?:\[\])?/).replace("ref", U).getRegex();
745
+ var et = d("reflink|nolink(?!\\()", "g").replace("reflink", ke).replace("nolink", de).getRegex();
746
+ var ie = /[hH][tT][tT][pP][sS]?|[fF][tT][pP]/;
747
+ var J = { _backpedal: _, anyPunctuation: We, autolink: Xe, blockSkip: He, br: ue, code: Ce, del: _, delLDelim: _, delRDelim: _, emStrongLDelim: Ze, emStrongRDelimAst: Ne, emStrongRDelimUnd: je, escape: Ae, link: Ye, nolink: de, punctuation: De, reflink: ke, reflinkSearch: et, tag: Ve, text: Be, url: _ };
748
+ var tt = { ...J, link: d(/^!?\[(label)\]\((.*?)\)/).replace("label", v).getRegex(), reflink: d(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", v).getRegex() };
749
+ var Q = { ...J, emStrongRDelimAst: Qe, emStrongLDelim: Ge, delLDelim: Fe, delRDelim: Ke, url: d(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol", ie).replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(), _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, del: /^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/, text: d(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol", ie).getRegex() };
750
+ var nt = { ...Q, br: d(ue).replace("{2,}", "*").getRegex(), text: d(Q.text).replace("\\b_", "\\b_| {2,}\\n").replace(/\{2,\}/g, "*").getRegex() };
751
+ var D = { normal: W, gfm: Ee, pedantic: Ie };
752
+ var A = { normal: J, gfm: Q, breaks: nt, pedantic: tt };
753
+ var rt = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
754
+ var ge = (l3) => rt[l3];
755
+ function O(l3, e) {
756
+ if (e) {
757
+ if (m.escapeTest.test(l3)) return l3.replace(m.escapeReplace, ge);
758
+ } else if (m.escapeTestNoEncode.test(l3)) return l3.replace(m.escapeReplaceNoEncode, ge);
759
+ return l3;
760
+ }
761
+ function V(l3) {
762
+ try {
763
+ l3 = encodeURI(l3).replace(m.percentDecode, "%");
764
+ } catch {
765
+ return null;
766
+ }
767
+ return l3;
768
+ }
769
+ function Y(l3, e) {
770
+ let t = l3.replace(m.findPipe, (r, i, o) => {
771
+ let u = false, a = i;
772
+ for (; --a >= 0 && o[a] === "\\"; ) u = !u;
773
+ return u ? "|" : " |";
774
+ }), n = t.split(m.splitPipe), s = 0;
775
+ if (n[0].trim() || n.shift(), n.length > 0 && !n.at(-1)?.trim() && n.pop(), e) if (n.length > e) n.splice(e);
776
+ else for (; n.length < e; ) n.push("");
777
+ for (; s < n.length; s++) n[s] = n[s].trim().replace(m.slashPipe, "|");
778
+ return n;
779
+ }
780
+ function $(l3, e, t) {
781
+ let n = l3.length;
782
+ if (n === 0) return "";
783
+ let s = 0;
784
+ for (; s < n; ) {
785
+ let r = l3.charAt(n - s - 1);
786
+ if (r === e && !t) s++;
787
+ else if (r !== e && t) s++;
788
+ else break;
789
+ }
790
+ return l3.slice(0, n - s);
791
+ }
792
+ function ee(l3) {
793
+ let e = l3.split(`
794
+ `), t = e.length - 1;
795
+ for (; t >= 0 && m.blankLine.test(e[t]); ) t--;
796
+ return e.length - t <= 2 ? l3 : e.slice(0, t + 1).join(`
797
+ `);
798
+ }
799
+ function fe(l3, e) {
800
+ if (l3.indexOf(e[1]) === -1) return -1;
801
+ let t = 0;
802
+ for (let n = 0; n < l3.length; n++) if (l3[n] === "\\") n++;
803
+ else if (l3[n] === e[0]) t++;
804
+ else if (l3[n] === e[1] && (t--, t < 0)) return n;
805
+ return t > 0 ? -2 : -1;
806
+ }
807
+ function me(l3, e = 0) {
808
+ let t = e, n = "";
809
+ for (let s of l3) if (s === " ") {
810
+ let r = 4 - t % 4;
811
+ n += " ".repeat(r), t += r;
812
+ } else n += s, t++;
813
+ return n;
814
+ }
815
+ function xe(l3, e, t, n, s) {
816
+ let r = e.href, i = e.title || null, o = l3[1].replace(s.other.outputLinkReplace, "$1");
817
+ n.state.inLink = true;
818
+ let u = { type: l3[0].charAt(0) === "!" ? "image" : "link", raw: t, href: r, title: i, text: o, tokens: n.inlineTokens(o) };
819
+ return n.state.inLink = false, u;
820
+ }
821
+ function st(l3, e, t) {
822
+ let n = l3.match(t.other.indentCodeCompensation);
823
+ if (n === null) return e;
824
+ let s = n[1];
825
+ return e.split(`
826
+ `).map((r) => {
827
+ let i = r.match(t.other.beginningSpace);
828
+ if (i === null) return r;
829
+ let [o] = i;
830
+ return o.length >= s.length ? r.slice(s.length) : r;
831
+ }).join(`
832
+ `);
833
+ }
834
+ var w = class {
835
+ options;
836
+ rules;
837
+ lexer;
838
+ constructor(e) {
839
+ this.options = e || T;
840
+ }
841
+ space(e) {
842
+ let t = this.rules.block.newline.exec(e);
843
+ if (t && t[0].length > 0) return { type: "space", raw: t[0] };
844
+ }
845
+ code(e) {
846
+ let t = this.rules.block.code.exec(e);
847
+ if (t) {
848
+ let n = this.options.pedantic ? t[0] : ee(t[0]), s = n.replace(this.rules.other.codeRemoveIndent, "");
849
+ return { type: "code", raw: n, codeBlockStyle: "indented", text: s };
850
+ }
851
+ }
852
+ fences(e) {
853
+ let t = this.rules.block.fences.exec(e);
854
+ if (t) {
855
+ let n = t[0], s = st(n, t[3] || "", this.rules);
856
+ return { type: "code", raw: n, lang: t[2] ? t[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : t[2], text: s };
857
+ }
858
+ }
859
+ heading(e) {
860
+ let t = this.rules.block.heading.exec(e);
861
+ if (t) {
862
+ let n = t[2].trim();
863
+ if (this.rules.other.endingHash.test(n)) {
864
+ let s = $(n, "#");
865
+ (this.options.pedantic || !s || this.rules.other.endingSpaceChar.test(s)) && (n = s.trim());
866
+ }
867
+ return { type: "heading", raw: $(t[0], `
868
+ `), depth: t[1].length, text: n, tokens: this.lexer.inline(n) };
869
+ }
870
+ }
871
+ hr(e) {
872
+ let t = this.rules.block.hr.exec(e);
873
+ if (t) return { type: "hr", raw: $(t[0], `
874
+ `) };
875
+ }
876
+ blockquote(e) {
877
+ let t = this.rules.block.blockquote.exec(e);
878
+ if (t) {
879
+ let n = $(t[0], `
880
+ `).split(`
881
+ `), s = "", r = "", i = [];
882
+ for (; n.length > 0; ) {
883
+ let o = false, u = [], a;
884
+ for (a = 0; a < n.length; a++) if (this.rules.other.blockquoteStart.test(n[a])) u.push(n[a]), o = true;
885
+ else if (!o) u.push(n[a]);
886
+ else break;
887
+ n = n.slice(a);
888
+ let c = u.join(`
889
+ `), p = c.replace(this.rules.other.blockquoteSetextReplace, `
890
+ $1`).replace(this.rules.other.blockquoteSetextReplace2, "");
891
+ s = s ? `${s}
892
+ ${c}` : c, r = r ? `${r}
893
+ ${p}` : p;
894
+ let k = this.lexer.state.top;
895
+ if (this.lexer.state.top = true, this.lexer.blockTokens(p, i, true), this.lexer.state.top = k, n.length === 0) break;
896
+ let h = i.at(-1);
897
+ if (h?.type === "code") break;
898
+ if (h?.type === "blockquote") {
899
+ let R = h, f = R.raw + `
900
+ ` + n.join(`
901
+ `), S = this.blockquote(f);
902
+ i[i.length - 1] = S, s = s.substring(0, s.length - R.raw.length) + S.raw, r = r.substring(0, r.length - R.text.length) + S.text;
903
+ break;
904
+ } else if (h?.type === "list") {
905
+ let R = h, f = R.raw + `
906
+ ` + n.join(`
907
+ `), S = this.list(f);
908
+ i[i.length - 1] = S, s = s.substring(0, s.length - h.raw.length) + S.raw, r = r.substring(0, r.length - R.raw.length) + S.raw, n = f.substring(i.at(-1).raw.length).split(`
909
+ `);
910
+ continue;
911
+ }
912
+ }
913
+ return { type: "blockquote", raw: s, tokens: i, text: r };
914
+ }
915
+ }
916
+ list(e) {
917
+ let t = this.rules.block.list.exec(e);
918
+ if (t) {
919
+ let n = t[1].trim(), s = n.length > 1, r = { type: "list", raw: "", ordered: s, start: s ? +n.slice(0, -1) : "", loose: false, items: [] };
920
+ n = s ? `\\d{1,9}\\${n.slice(-1)}` : `\\${n}`, this.options.pedantic && (n = s ? n : "[*+-]");
921
+ let i = this.rules.other.listItemRegex(n), o = false;
922
+ for (; e; ) {
923
+ let a = false, c = "", p = "";
924
+ if (!(t = i.exec(e)) || this.rules.block.hr.test(e)) break;
925
+ c = t[0], e = e.substring(c.length);
926
+ let k = me(t[2].split(`
927
+ `, 1)[0], t[1].length), h = e.split(`
928
+ `, 1)[0], R = !k.trim(), f = 0;
929
+ if (this.options.pedantic ? (f = 2, p = k.trimStart()) : R ? f = t[1].length + 1 : (f = k.search(this.rules.other.nonSpaceChar), f = f > 4 ? 1 : f, p = k.slice(f), f += t[1].length), R && this.rules.other.blankLine.test(h) && (c += h + `
930
+ `, e = e.substring(h.length + 1), a = true), !a) {
931
+ let S = this.rules.other.nextBulletRegex(f), te = this.rules.other.hrRegex(f), ne = this.rules.other.fencesBeginRegex(f), re = this.rules.other.headingBeginRegex(f), be = this.rules.other.htmlBeginRegex(f), Re = this.rules.other.blockquoteBeginRegex(f);
932
+ for (; e; ) {
933
+ let G = e.split(`
934
+ `, 1)[0], C;
935
+ if (h = G, this.options.pedantic ? (h = h.replace(this.rules.other.listReplaceNesting, " "), C = h) : C = h.replace(this.rules.other.tabCharGlobal, " "), ne.test(h) || re.test(h) || be.test(h) || Re.test(h) || S.test(h) || te.test(h)) break;
936
+ if (C.search(this.rules.other.nonSpaceChar) >= f || !h.trim()) p += `
937
+ ` + C.slice(f);
938
+ else {
939
+ if (R || k.replace(this.rules.other.tabCharGlobal, " ").search(this.rules.other.nonSpaceChar) >= 4 || ne.test(k) || re.test(k) || te.test(k)) break;
940
+ p += `
941
+ ` + h;
942
+ }
943
+ R = !h.trim(), c += G + `
944
+ `, e = e.substring(G.length + 1), k = C.slice(f);
945
+ }
946
+ }
947
+ r.loose || (o ? r.loose = true : this.rules.other.doubleBlankLine.test(c) && (o = true)), r.items.push({ type: "list_item", raw: c, task: !!this.options.gfm && this.rules.other.listIsTask.test(p), loose: false, text: p, tokens: [] }), r.raw += c;
948
+ }
949
+ let u = r.items.at(-1);
950
+ if (u) u.raw = u.raw.trimEnd(), u.text = u.text.trimEnd();
951
+ else return;
952
+ r.raw = r.raw.trimEnd();
953
+ for (let a of r.items) {
954
+ this.lexer.state.top = false, a.tokens = this.lexer.blockTokens(a.text, []);
955
+ let c = a.tokens[0];
956
+ if (a.task && (c?.type === "text" || c?.type === "paragraph")) {
957
+ a.text = a.text.replace(this.rules.other.listReplaceTask, ""), c.raw = c.raw.replace(this.rules.other.listReplaceTask, ""), c.text = c.text.replace(this.rules.other.listReplaceTask, "");
958
+ for (let k = this.lexer.inlineQueue.length - 1; k >= 0; k--) if (this.rules.other.listIsTask.test(this.lexer.inlineQueue[k].src)) {
959
+ this.lexer.inlineQueue[k].src = this.lexer.inlineQueue[k].src.replace(this.rules.other.listReplaceTask, "");
960
+ break;
961
+ }
962
+ let p = this.rules.other.listTaskCheckbox.exec(a.raw);
963
+ if (p) {
964
+ let k = { type: "checkbox", raw: p[0] + " ", checked: p[0] !== "[ ]" };
965
+ a.checked = k.checked, r.loose ? a.tokens[0] && ["paragraph", "text"].includes(a.tokens[0].type) && "tokens" in a.tokens[0] && a.tokens[0].tokens ? (a.tokens[0].raw = k.raw + a.tokens[0].raw, a.tokens[0].text = k.raw + a.tokens[0].text, a.tokens[0].tokens.unshift(k)) : a.tokens.unshift({ type: "paragraph", raw: k.raw, text: k.raw, tokens: [k] }) : a.tokens.unshift(k);
966
+ }
967
+ } else a.task && (a.task = false);
968
+ if (!r.loose) {
969
+ let p = a.tokens.filter((h) => h.type === "space"), k = p.length > 0 && p.some((h) => this.rules.other.anyLine.test(h.raw));
970
+ r.loose = k;
971
+ }
972
+ }
973
+ if (r.loose) for (let a of r.items) {
974
+ a.loose = true;
975
+ for (let c of a.tokens) c.type === "text" && (c.type = "paragraph");
976
+ }
977
+ return r;
978
+ }
979
+ }
980
+ html(e) {
981
+ let t = this.rules.block.html.exec(e);
982
+ if (t) {
983
+ let n = ee(t[0]);
984
+ return { type: "html", block: true, raw: n, pre: t[1] === "pre" || t[1] === "script" || t[1] === "style", text: n };
985
+ }
986
+ }
987
+ def(e) {
988
+ let t = this.rules.block.def.exec(e);
989
+ if (t) {
990
+ let n = t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, " "), s = t[2] ? t[2].replace(this.rules.other.hrefBrackets, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "", r = t[3] ? t[3].substring(1, t[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : t[3];
991
+ return { type: "def", tag: n, raw: $(t[0], `
992
+ `), href: s, title: r };
993
+ }
994
+ }
995
+ table(e) {
996
+ let t = this.rules.block.table.exec(e);
997
+ if (!t || !this.rules.other.tableDelimiter.test(t[2])) return;
998
+ let n = Y(t[1]), s = t[2].replace(this.rules.other.tableAlignChars, "").split("|"), r = t[3]?.trim() ? t[3].replace(this.rules.other.tableRowBlankLine, "").split(`
999
+ `) : [], i = { type: "table", raw: $(t[0], `
1000
+ `), header: [], align: [], rows: [] };
1001
+ if (n.length === s.length) {
1002
+ for (let o of s) this.rules.other.tableAlignRight.test(o) ? i.align.push("right") : this.rules.other.tableAlignCenter.test(o) ? i.align.push("center") : this.rules.other.tableAlignLeft.test(o) ? i.align.push("left") : i.align.push(null);
1003
+ for (let o = 0; o < n.length; o++) i.header.push({ text: n[o], tokens: this.lexer.inline(n[o]), header: true, align: i.align[o] });
1004
+ for (let o of r) i.rows.push(Y(o, i.header.length).map((u, a) => ({ text: u, tokens: this.lexer.inline(u), header: false, align: i.align[a] })));
1005
+ return i;
1006
+ }
1007
+ }
1008
+ lheading(e) {
1009
+ let t = this.rules.block.lheading.exec(e);
1010
+ if (t) {
1011
+ let n = t[1].trim();
1012
+ return { type: "heading", raw: $(t[0], `
1013
+ `), depth: t[2].charAt(0) === "=" ? 1 : 2, text: n, tokens: this.lexer.inline(n) };
1014
+ }
1015
+ }
1016
+ paragraph(e) {
1017
+ let t = this.rules.block.paragraph.exec(e);
1018
+ if (t) {
1019
+ let n = t[1].charAt(t[1].length - 1) === `
1020
+ ` ? t[1].slice(0, -1) : t[1];
1021
+ return { type: "paragraph", raw: t[0], text: n, tokens: this.lexer.inline(n) };
1022
+ }
1023
+ }
1024
+ text(e) {
1025
+ let t = this.rules.block.text.exec(e);
1026
+ if (t) return { type: "text", raw: t[0], text: t[0], tokens: this.lexer.inline(t[0]) };
1027
+ }
1028
+ escape(e) {
1029
+ let t = this.rules.inline.escape.exec(e);
1030
+ if (t) return { type: "escape", raw: t[0], text: t[1] };
1031
+ }
1032
+ tag(e) {
1033
+ let t = this.rules.inline.tag.exec(e);
1034
+ if (t) return !this.lexer.state.inLink && this.rules.other.startATag.test(t[0]) ? this.lexer.state.inLink = true : this.lexer.state.inLink && this.rules.other.endATag.test(t[0]) && (this.lexer.state.inLink = false), !this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(t[0]) ? this.lexer.state.inRawBlock = true : this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(t[0]) && (this.lexer.state.inRawBlock = false), { type: "html", raw: t[0], inLink: this.lexer.state.inLink, inRawBlock: this.lexer.state.inRawBlock, block: false, text: t[0] };
1035
+ }
1036
+ link(e) {
1037
+ let t = this.rules.inline.link.exec(e);
1038
+ if (t) {
1039
+ let n = t[2].trim();
1040
+ if (!this.options.pedantic && this.rules.other.startAngleBracket.test(n)) {
1041
+ if (!this.rules.other.endAngleBracket.test(n)) return;
1042
+ let i = $(n.slice(0, -1), "\\");
1043
+ if ((n.length - i.length) % 2 === 0) return;
1044
+ } else {
1045
+ let i = fe(t[2], "()");
1046
+ if (i === -2) return;
1047
+ if (i > -1) {
1048
+ let u = (t[0].indexOf("!") === 0 ? 5 : 4) + t[1].length + i;
1049
+ t[2] = t[2].substring(0, i), t[0] = t[0].substring(0, u).trim(), t[3] = "";
1050
+ }
1051
+ }
1052
+ let s = t[2], r = "";
1053
+ if (this.options.pedantic) {
1054
+ let i = this.rules.other.pedanticHrefTitle.exec(s);
1055
+ i && (s = i[1], r = i[3]);
1056
+ } else r = t[3] ? t[3].slice(1, -1) : "";
1057
+ return s = s.trim(), this.rules.other.startAngleBracket.test(s) && (this.options.pedantic && !this.rules.other.endAngleBracket.test(n) ? s = s.slice(1) : s = s.slice(1, -1)), xe(t, { href: s && s.replace(this.rules.inline.anyPunctuation, "$1"), title: r && r.replace(this.rules.inline.anyPunctuation, "$1") }, t[0], this.lexer, this.rules);
1058
+ }
1059
+ }
1060
+ reflink(e, t) {
1061
+ let n;
1062
+ if ((n = this.rules.inline.reflink.exec(e)) || (n = this.rules.inline.nolink.exec(e))) {
1063
+ let s = (n[2] || n[1]).replace(this.rules.other.multipleSpaceGlobal, " "), r = t[s.toLowerCase()];
1064
+ if (!r) {
1065
+ let i = n[0].charAt(0);
1066
+ return { type: "text", raw: i, text: i };
1067
+ }
1068
+ return xe(n, r, n[0], this.lexer, this.rules);
1069
+ }
1070
+ }
1071
+ emStrong(e, t, n = "") {
1072
+ let s = this.rules.inline.emStrongLDelim.exec(e);
1073
+ if (!s || !s[1] && !s[2] && !s[3] && !s[4] || s[4] && n.match(this.rules.other.unicodeAlphaNumeric)) return;
1074
+ if (!(s[1] || s[3] || "") || !n || this.rules.inline.punctuation.exec(n)) {
1075
+ let i = [...s[0]].length - 1, o, u, a = i, c = 0, p = s[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
1076
+ for (p.lastIndex = 0, t = t.slice(-1 * e.length + i); (s = p.exec(t)) !== null; ) {
1077
+ if (o = s[1] || s[2] || s[3] || s[4] || s[5] || s[6], !o) continue;
1078
+ if (u = [...o].length, s[3] || s[4]) {
1079
+ a += u;
1080
+ continue;
1081
+ } else if ((s[5] || s[6]) && i % 3 && !((i + u) % 3)) {
1082
+ c += u;
1083
+ continue;
1084
+ }
1085
+ if (a -= u, a > 0) continue;
1086
+ u = Math.min(u, u + a + c);
1087
+ let k = [...s[0]][0].length, h = e.slice(0, i + s.index + k + u);
1088
+ if (Math.min(i, u) % 2) {
1089
+ let f = h.slice(1, -1);
1090
+ return { type: "em", raw: h, text: f, tokens: this.lexer.inlineTokens(f) };
1091
+ }
1092
+ let R = h.slice(2, -2);
1093
+ return { type: "strong", raw: h, text: R, tokens: this.lexer.inlineTokens(R) };
1094
+ }
1095
+ }
1096
+ }
1097
+ codespan(e) {
1098
+ let t = this.rules.inline.code.exec(e);
1099
+ if (t) {
1100
+ let n = t[2].replace(this.rules.other.newLineCharGlobal, " "), s = this.rules.other.nonSpaceChar.test(n), r = this.rules.other.startingSpaceChar.test(n) && this.rules.other.endingSpaceChar.test(n);
1101
+ return s && r && (n = n.substring(1, n.length - 1)), { type: "codespan", raw: t[0], text: n };
1102
+ }
1103
+ }
1104
+ br(e) {
1105
+ let t = this.rules.inline.br.exec(e);
1106
+ if (t) return { type: "br", raw: t[0] };
1107
+ }
1108
+ del(e, t, n = "") {
1109
+ let s = this.rules.inline.delLDelim.exec(e);
1110
+ if (!s) return;
1111
+ if (!(s[1] || "") || !n || this.rules.inline.punctuation.exec(n)) {
1112
+ let i = [...s[0]].length - 1, o, u, a = i, c = this.rules.inline.delRDelim;
1113
+ for (c.lastIndex = 0, t = t.slice(-1 * e.length + i); (s = c.exec(t)) !== null; ) {
1114
+ if (o = s[1] || s[2] || s[3] || s[4] || s[5] || s[6], !o || (u = [...o].length, u !== i)) continue;
1115
+ if (s[3] || s[4]) {
1116
+ a += u;
1117
+ continue;
1118
+ }
1119
+ if (a -= u, a > 0) continue;
1120
+ u = Math.min(u, u + a);
1121
+ let p = [...s[0]][0].length, k = e.slice(0, i + s.index + p + u), h = k.slice(i, -i);
1122
+ return { type: "del", raw: k, text: h, tokens: this.lexer.inlineTokens(h) };
1123
+ }
1124
+ }
1125
+ }
1126
+ autolink(e) {
1127
+ let t = this.rules.inline.autolink.exec(e);
1128
+ if (t) {
1129
+ let n, s;
1130
+ return t[2] === "@" ? (n = t[1], s = "mailto:" + n) : (n = t[1], s = n), { type: "link", raw: t[0], text: n, href: s, tokens: [{ type: "text", raw: n, text: n }] };
1131
+ }
1132
+ }
1133
+ url(e) {
1134
+ let t;
1135
+ if (t = this.rules.inline.url.exec(e)) {
1136
+ let n, s;
1137
+ if (t[2] === "@") n = t[0], s = "mailto:" + n;
1138
+ else {
1139
+ let r;
1140
+ do
1141
+ r = t[0], t[0] = this.rules.inline._backpedal.exec(t[0])?.[0] ?? "";
1142
+ while (r !== t[0]);
1143
+ n = t[0], t[1] === "www." ? s = "http://" + t[0] : s = t[0];
1144
+ }
1145
+ return { type: "link", raw: t[0], text: n, href: s, tokens: [{ type: "text", raw: n, text: n }] };
1146
+ }
1147
+ }
1148
+ inlineText(e) {
1149
+ let t = this.rules.inline.text.exec(e);
1150
+ if (t) {
1151
+ let n = this.lexer.state.inRawBlock;
1152
+ return { type: "text", raw: t[0], text: t[0], escaped: n };
1153
+ }
1154
+ }
1155
+ };
1156
+ var x = class l {
1157
+ tokens;
1158
+ options;
1159
+ state;
1160
+ inlineQueue;
1161
+ tokenizer;
1162
+ constructor(e) {
1163
+ this.tokens = [], this.tokens.links = /* @__PURE__ */ Object.create(null), this.options = e || T, this.options.tokenizer = this.options.tokenizer || new w(), this.tokenizer = this.options.tokenizer, this.tokenizer.options = this.options, this.tokenizer.lexer = this, this.inlineQueue = [], this.state = { inLink: false, inRawBlock: false, top: true };
1164
+ let t = { other: m, block: D.normal, inline: A.normal };
1165
+ this.options.pedantic ? (t.block = D.pedantic, t.inline = A.pedantic) : this.options.gfm && (t.block = D.gfm, this.options.breaks ? t.inline = A.breaks : t.inline = A.gfm), this.tokenizer.rules = t;
1166
+ }
1167
+ static get rules() {
1168
+ return { block: D, inline: A };
1169
+ }
1170
+ static lex(e, t) {
1171
+ return new l(t).lex(e);
1172
+ }
1173
+ static lexInline(e, t) {
1174
+ return new l(t).inlineTokens(e);
1175
+ }
1176
+ lex(e) {
1177
+ e = e.replace(m.carriageReturn, `
1178
+ `), this.blockTokens(e, this.tokens);
1179
+ for (let t = 0; t < this.inlineQueue.length; t++) {
1180
+ let n = this.inlineQueue[t];
1181
+ this.inlineTokens(n.src, n.tokens);
1182
+ }
1183
+ return this.inlineQueue = [], this.tokens;
1184
+ }
1185
+ blockTokens(e, t = [], n = false) {
1186
+ this.tokenizer.lexer = this, this.options.pedantic && (e = e.replace(m.tabCharGlobal, " ").replace(m.spaceLine, ""));
1187
+ let s = 1 / 0;
1188
+ for (; e; ) {
1189
+ if (e.length < s) s = e.length;
1190
+ else {
1191
+ this.infiniteLoopError(e.charCodeAt(0));
1192
+ break;
1193
+ }
1194
+ let r;
1195
+ if (this.options.extensions?.block?.some((o) => (r = o.call({ lexer: this }, e, t)) ? (e = e.substring(r.raw.length), t.push(r), true) : false)) continue;
1196
+ if (r = this.tokenizer.space(e)) {
1197
+ e = e.substring(r.raw.length);
1198
+ let o = t.at(-1);
1199
+ r.raw.length === 1 && o !== void 0 ? o.raw += `
1200
+ ` : t.push(r);
1201
+ continue;
1202
+ }
1203
+ if (r = this.tokenizer.code(e)) {
1204
+ e = e.substring(r.raw.length);
1205
+ let o = t.at(-1);
1206
+ o?.type === "paragraph" || o?.type === "text" ? (o.raw += (o.raw.endsWith(`
1207
+ `) ? "" : `
1208
+ `) + r.raw, o.text += `
1209
+ ` + r.text, this.inlineQueue.at(-1).src = o.text) : t.push(r);
1210
+ continue;
1211
+ }
1212
+ if (r = this.tokenizer.fences(e)) {
1213
+ e = e.substring(r.raw.length), t.push(r);
1214
+ continue;
1215
+ }
1216
+ if (r = this.tokenizer.heading(e)) {
1217
+ e = e.substring(r.raw.length), t.push(r);
1218
+ continue;
1219
+ }
1220
+ if (r = this.tokenizer.hr(e)) {
1221
+ e = e.substring(r.raw.length), t.push(r);
1222
+ continue;
1223
+ }
1224
+ if (r = this.tokenizer.blockquote(e)) {
1225
+ e = e.substring(r.raw.length), t.push(r);
1226
+ continue;
1227
+ }
1228
+ if (r = this.tokenizer.list(e)) {
1229
+ e = e.substring(r.raw.length), t.push(r);
1230
+ continue;
1231
+ }
1232
+ if (r = this.tokenizer.html(e)) {
1233
+ e = e.substring(r.raw.length), t.push(r);
1234
+ continue;
1235
+ }
1236
+ if (r = this.tokenizer.def(e)) {
1237
+ e = e.substring(r.raw.length);
1238
+ let o = t.at(-1);
1239
+ o?.type === "paragraph" || o?.type === "text" ? (o.raw += (o.raw.endsWith(`
1240
+ `) ? "" : `
1241
+ `) + r.raw, o.text += `
1242
+ ` + r.raw, this.inlineQueue.at(-1).src = o.text) : this.tokens.links[r.tag] || (this.tokens.links[r.tag] = { href: r.href, title: r.title }, t.push(r));
1243
+ continue;
1244
+ }
1245
+ if (r = this.tokenizer.table(e)) {
1246
+ e = e.substring(r.raw.length), t.push(r);
1247
+ continue;
1248
+ }
1249
+ if (r = this.tokenizer.lheading(e)) {
1250
+ e = e.substring(r.raw.length), t.push(r);
1251
+ continue;
1252
+ }
1253
+ let i = e;
1254
+ if (this.options.extensions?.startBlock) {
1255
+ let o = 1 / 0, u = e.slice(1), a;
1256
+ this.options.extensions.startBlock.forEach((c) => {
1257
+ a = c.call({ lexer: this }, u), typeof a == "number" && a >= 0 && (o = Math.min(o, a));
1258
+ }), o < 1 / 0 && o >= 0 && (i = e.substring(0, o + 1));
1259
+ }
1260
+ if (this.state.top && (r = this.tokenizer.paragraph(i))) {
1261
+ let o = t.at(-1);
1262
+ n && o?.type === "paragraph" ? (o.raw += (o.raw.endsWith(`
1263
+ `) ? "" : `
1264
+ `) + r.raw, o.text += `
1265
+ ` + r.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = o.text) : t.push(r), n = i.length !== e.length, e = e.substring(r.raw.length);
1266
+ continue;
1267
+ }
1268
+ if (r = this.tokenizer.text(e)) {
1269
+ e = e.substring(r.raw.length);
1270
+ let o = t.at(-1);
1271
+ o?.type === "text" ? (o.raw += (o.raw.endsWith(`
1272
+ `) ? "" : `
1273
+ `) + r.raw, o.text += `
1274
+ ` + r.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = o.text) : t.push(r);
1275
+ continue;
1276
+ }
1277
+ if (e) {
1278
+ this.infiniteLoopError(e.charCodeAt(0));
1279
+ break;
1280
+ }
1281
+ }
1282
+ return this.state.top = true, t;
1283
+ }
1284
+ inline(e, t = []) {
1285
+ return this.inlineQueue.push({ src: e, tokens: t }), t;
1286
+ }
1287
+ inlineTokens(e, t = []) {
1288
+ this.tokenizer.lexer = this;
1289
+ let n = e, s = null;
1290
+ if (this.tokens.links) {
1291
+ let a = Object.keys(this.tokens.links);
1292
+ if (a.length > 0) for (; (s = this.tokenizer.rules.inline.reflinkSearch.exec(n)) !== null; ) a.includes(s[0].slice(s[0].lastIndexOf("[") + 1, -1)) && (n = n.slice(0, s.index) + "[" + "a".repeat(s[0].length - 2) + "]" + n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex));
1293
+ }
1294
+ for (; (s = this.tokenizer.rules.inline.anyPunctuation.exec(n)) !== null; ) n = n.slice(0, s.index) + "++" + n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
1295
+ let r;
1296
+ for (; (s = this.tokenizer.rules.inline.blockSkip.exec(n)) !== null; ) r = s[2] ? s[2].length : 0, n = n.slice(0, s.index + r) + "[" + "a".repeat(s[0].length - r - 2) + "]" + n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
1297
+ n = this.options.hooks?.emStrongMask?.call({ lexer: this }, n) ?? n;
1298
+ let i = false, o = "", u = 1 / 0;
1299
+ for (; e; ) {
1300
+ if (e.length < u) u = e.length;
1301
+ else {
1302
+ this.infiniteLoopError(e.charCodeAt(0));
1303
+ break;
1304
+ }
1305
+ i || (o = ""), i = false;
1306
+ let a;
1307
+ if (this.options.extensions?.inline?.some((p) => (a = p.call({ lexer: this }, e, t)) ? (e = e.substring(a.raw.length), t.push(a), true) : false)) continue;
1308
+ if (a = this.tokenizer.escape(e)) {
1309
+ e = e.substring(a.raw.length), t.push(a);
1310
+ continue;
1311
+ }
1312
+ if (a = this.tokenizer.tag(e)) {
1313
+ e = e.substring(a.raw.length), t.push(a);
1314
+ continue;
1315
+ }
1316
+ if (a = this.tokenizer.link(e)) {
1317
+ e = e.substring(a.raw.length), t.push(a);
1318
+ continue;
1319
+ }
1320
+ if (a = this.tokenizer.reflink(e, this.tokens.links)) {
1321
+ e = e.substring(a.raw.length);
1322
+ let p = t.at(-1);
1323
+ a.type === "text" && p?.type === "text" ? (p.raw += a.raw, p.text += a.text) : t.push(a);
1324
+ continue;
1325
+ }
1326
+ if (a = this.tokenizer.emStrong(e, n, o)) {
1327
+ e = e.substring(a.raw.length), t.push(a);
1328
+ continue;
1329
+ }
1330
+ if (a = this.tokenizer.codespan(e)) {
1331
+ e = e.substring(a.raw.length), t.push(a);
1332
+ continue;
1333
+ }
1334
+ if (a = this.tokenizer.br(e)) {
1335
+ e = e.substring(a.raw.length), t.push(a);
1336
+ continue;
1337
+ }
1338
+ if (a = this.tokenizer.del(e, n, o)) {
1339
+ e = e.substring(a.raw.length), t.push(a);
1340
+ continue;
1341
+ }
1342
+ if (a = this.tokenizer.autolink(e)) {
1343
+ e = e.substring(a.raw.length), t.push(a);
1344
+ continue;
1345
+ }
1346
+ if (!this.state.inLink && (a = this.tokenizer.url(e))) {
1347
+ e = e.substring(a.raw.length), t.push(a);
1348
+ continue;
1349
+ }
1350
+ let c = e;
1351
+ if (this.options.extensions?.startInline) {
1352
+ let p = 1 / 0, k = e.slice(1), h;
1353
+ this.options.extensions.startInline.forEach((R) => {
1354
+ h = R.call({ lexer: this }, k), typeof h == "number" && h >= 0 && (p = Math.min(p, h));
1355
+ }), p < 1 / 0 && p >= 0 && (c = e.substring(0, p + 1));
1356
+ }
1357
+ if (a = this.tokenizer.inlineText(c)) {
1358
+ e = e.substring(a.raw.length), a.raw.slice(-1) !== "_" && (o = a.raw.slice(-1)), i = true;
1359
+ let p = t.at(-1);
1360
+ p?.type === "text" ? (p.raw += a.raw, p.text += a.text) : t.push(a);
1361
+ continue;
1362
+ }
1363
+ if (e) {
1364
+ this.infiniteLoopError(e.charCodeAt(0));
1365
+ break;
1366
+ }
1367
+ }
1368
+ return t;
1369
+ }
1370
+ infiniteLoopError(e) {
1371
+ let t = "Infinite loop on byte: " + e;
1372
+ if (this.options.silent) console.error(t);
1373
+ else throw new Error(t);
1374
+ }
1375
+ };
1376
+ var y = class {
1377
+ options;
1378
+ parser;
1379
+ constructor(e) {
1380
+ this.options = e || T;
1381
+ }
1382
+ space(e) {
1383
+ return "";
1384
+ }
1385
+ code({ text: e, lang: t, escaped: n }) {
1386
+ let s = (t || "").match(m.notSpaceStart)?.[0], r = e.replace(m.endingNewline, "") + `
1387
+ `;
1388
+ return s ? '<pre><code class="language-' + O(s) + '">' + (n ? r : O(r, true)) + `</code></pre>
1389
+ ` : "<pre><code>" + (n ? r : O(r, true)) + `</code></pre>
1390
+ `;
1391
+ }
1392
+ blockquote({ tokens: e }) {
1393
+ return `<blockquote>
1394
+ ${this.parser.parse(e)}</blockquote>
1395
+ `;
1396
+ }
1397
+ html({ text: e }) {
1398
+ return e;
1399
+ }
1400
+ def(e) {
1401
+ return "";
1402
+ }
1403
+ heading({ tokens: e, depth: t }) {
1404
+ return `<h${t}>${this.parser.parseInline(e)}</h${t}>
1405
+ `;
1406
+ }
1407
+ hr(e) {
1408
+ return `<hr>
1409
+ `;
1410
+ }
1411
+ list(e) {
1412
+ let t = e.ordered, n = e.start, s = "";
1413
+ for (let o = 0; o < e.items.length; o++) {
1414
+ let u = e.items[o];
1415
+ s += this.listitem(u);
1416
+ }
1417
+ let r = t ? "ol" : "ul", i = t && n !== 1 ? ' start="' + n + '"' : "";
1418
+ return "<" + r + i + `>
1419
+ ` + s + "</" + r + `>
1420
+ `;
1421
+ }
1422
+ listitem(e) {
1423
+ return `<li>${this.parser.parse(e.tokens)}</li>
1424
+ `;
1425
+ }
1426
+ checkbox({ checked: e }) {
1427
+ return "<input " + (e ? 'checked="" ' : "") + 'disabled="" type="checkbox"> ';
1428
+ }
1429
+ paragraph({ tokens: e }) {
1430
+ return `<p>${this.parser.parseInline(e)}</p>
1431
+ `;
1432
+ }
1433
+ table(e) {
1434
+ let t = "", n = "";
1435
+ for (let r = 0; r < e.header.length; r++) n += this.tablecell(e.header[r]);
1436
+ t += this.tablerow({ text: n });
1437
+ let s = "";
1438
+ for (let r = 0; r < e.rows.length; r++) {
1439
+ let i = e.rows[r];
1440
+ n = "";
1441
+ for (let o = 0; o < i.length; o++) n += this.tablecell(i[o]);
1442
+ s += this.tablerow({ text: n });
1443
+ }
1444
+ return s && (s = `<tbody>${s}</tbody>`), `<table>
1445
+ <thead>
1446
+ ` + t + `</thead>
1447
+ ` + s + `</table>
1448
+ `;
1449
+ }
1450
+ tablerow({ text: e }) {
1451
+ return `<tr>
1452
+ ${e}</tr>
1453
+ `;
1454
+ }
1455
+ tablecell(e) {
1456
+ let t = this.parser.parseInline(e.tokens), n = e.header ? "th" : "td";
1457
+ return (e.align ? `<${n} align="${e.align}">` : `<${n}>`) + t + `</${n}>
1458
+ `;
1459
+ }
1460
+ strong({ tokens: e }) {
1461
+ return `<strong>${this.parser.parseInline(e)}</strong>`;
1462
+ }
1463
+ em({ tokens: e }) {
1464
+ return `<em>${this.parser.parseInline(e)}</em>`;
1465
+ }
1466
+ codespan({ text: e }) {
1467
+ return `<code>${O(e, true)}</code>`;
1468
+ }
1469
+ br(e) {
1470
+ return "<br>";
1471
+ }
1472
+ del({ tokens: e }) {
1473
+ return `<del>${this.parser.parseInline(e)}</del>`;
1474
+ }
1475
+ link({ href: e, title: t, tokens: n }) {
1476
+ let s = this.parser.parseInline(n), r = V(e);
1477
+ if (r === null) return s;
1478
+ e = r;
1479
+ let i = '<a href="' + e + '"';
1480
+ return t && (i += ' title="' + O(t) + '"'), i += ">" + s + "</a>", i;
1481
+ }
1482
+ image({ href: e, title: t, text: n, tokens: s }) {
1483
+ s && (n = this.parser.parseInline(s, this.parser.textRenderer));
1484
+ let r = V(e);
1485
+ if (r === null) return O(n);
1486
+ e = r;
1487
+ let i = `<img src="${e}" alt="${O(n)}"`;
1488
+ return t && (i += ` title="${O(t)}"`), i += ">", i;
1489
+ }
1490
+ text(e) {
1491
+ return "tokens" in e && e.tokens ? this.parser.parseInline(e.tokens) : "escaped" in e && e.escaped ? e.text : O(e.text);
1492
+ }
1493
+ };
1494
+ var L = class {
1495
+ strong({ text: e }) {
1496
+ return e;
1497
+ }
1498
+ em({ text: e }) {
1499
+ return e;
1500
+ }
1501
+ codespan({ text: e }) {
1502
+ return e;
1503
+ }
1504
+ del({ text: e }) {
1505
+ return e;
1506
+ }
1507
+ html({ text: e }) {
1508
+ return e;
1509
+ }
1510
+ text({ text: e }) {
1511
+ return e;
1512
+ }
1513
+ link({ text: e }) {
1514
+ return "" + e;
1515
+ }
1516
+ image({ text: e }) {
1517
+ return "" + e;
1518
+ }
1519
+ br() {
1520
+ return "";
1521
+ }
1522
+ checkbox({ raw: e }) {
1523
+ return e;
1524
+ }
1525
+ };
1526
+ var b = class l2 {
1527
+ options;
1528
+ renderer;
1529
+ textRenderer;
1530
+ constructor(e) {
1531
+ this.options = e || T, this.options.renderer = this.options.renderer || new y(), this.renderer = this.options.renderer, this.renderer.options = this.options, this.renderer.parser = this, this.textRenderer = new L();
1532
+ }
1533
+ static parse(e, t) {
1534
+ return new l2(t).parse(e);
1535
+ }
1536
+ static parseInline(e, t) {
1537
+ return new l2(t).parseInline(e);
1538
+ }
1539
+ parse(e) {
1540
+ this.renderer.parser = this;
1541
+ let t = "";
1542
+ for (let n = 0; n < e.length; n++) {
1543
+ let s = e[n];
1544
+ if (this.options.extensions?.renderers?.[s.type]) {
1545
+ let i = s, o = this.options.extensions.renderers[i.type].call({ parser: this }, i);
1546
+ if (o !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "def", "paragraph", "text"].includes(i.type)) {
1547
+ t += o || "";
1548
+ continue;
1549
+ }
1550
+ }
1551
+ let r = s;
1552
+ switch (r.type) {
1553
+ case "space": {
1554
+ t += this.renderer.space(r);
1555
+ break;
1556
+ }
1557
+ case "hr": {
1558
+ t += this.renderer.hr(r);
1559
+ break;
1560
+ }
1561
+ case "heading": {
1562
+ t += this.renderer.heading(r);
1563
+ break;
1564
+ }
1565
+ case "code": {
1566
+ t += this.renderer.code(r);
1567
+ break;
1568
+ }
1569
+ case "table": {
1570
+ t += this.renderer.table(r);
1571
+ break;
1572
+ }
1573
+ case "blockquote": {
1574
+ t += this.renderer.blockquote(r);
1575
+ break;
1576
+ }
1577
+ case "list": {
1578
+ t += this.renderer.list(r);
1579
+ break;
1580
+ }
1581
+ case "checkbox": {
1582
+ t += this.renderer.checkbox(r);
1583
+ break;
1584
+ }
1585
+ case "html": {
1586
+ t += this.renderer.html(r);
1587
+ break;
1588
+ }
1589
+ case "def": {
1590
+ t += this.renderer.def(r);
1591
+ break;
1592
+ }
1593
+ case "paragraph": {
1594
+ t += this.renderer.paragraph(r);
1595
+ break;
1596
+ }
1597
+ case "text": {
1598
+ t += this.renderer.text(r);
1599
+ break;
1600
+ }
1601
+ default: {
1602
+ let i = 'Token with "' + r.type + '" type was not found.';
1603
+ if (this.options.silent) return console.error(i), "";
1604
+ throw new Error(i);
1605
+ }
1606
+ }
1607
+ }
1608
+ return t;
1609
+ }
1610
+ parseInline(e, t = this.renderer) {
1611
+ this.renderer.parser = this;
1612
+ let n = "";
1613
+ for (let s = 0; s < e.length; s++) {
1614
+ let r = e[s];
1615
+ if (this.options.extensions?.renderers?.[r.type]) {
1616
+ let o = this.options.extensions.renderers[r.type].call({ parser: this }, r);
1617
+ if (o !== false || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(r.type)) {
1618
+ n += o || "";
1619
+ continue;
1620
+ }
1621
+ }
1622
+ let i = r;
1623
+ switch (i.type) {
1624
+ case "escape": {
1625
+ n += t.text(i);
1626
+ break;
1627
+ }
1628
+ case "html": {
1629
+ n += t.html(i);
1630
+ break;
1631
+ }
1632
+ case "link": {
1633
+ n += t.link(i);
1634
+ break;
1635
+ }
1636
+ case "image": {
1637
+ n += t.image(i);
1638
+ break;
1639
+ }
1640
+ case "checkbox": {
1641
+ n += t.checkbox(i);
1642
+ break;
1643
+ }
1644
+ case "strong": {
1645
+ n += t.strong(i);
1646
+ break;
1647
+ }
1648
+ case "em": {
1649
+ n += t.em(i);
1650
+ break;
1651
+ }
1652
+ case "codespan": {
1653
+ n += t.codespan(i);
1654
+ break;
1655
+ }
1656
+ case "br": {
1657
+ n += t.br(i);
1658
+ break;
1659
+ }
1660
+ case "del": {
1661
+ n += t.del(i);
1662
+ break;
1663
+ }
1664
+ case "text": {
1665
+ n += t.text(i);
1666
+ break;
1667
+ }
1668
+ default: {
1669
+ let o = 'Token with "' + i.type + '" type was not found.';
1670
+ if (this.options.silent) return console.error(o), "";
1671
+ throw new Error(o);
1672
+ }
1673
+ }
1674
+ }
1675
+ return n;
1676
+ }
1677
+ };
1678
+ var P = class {
1679
+ options;
1680
+ block;
1681
+ constructor(e) {
1682
+ this.options = e || T;
1683
+ }
1684
+ static passThroughHooks = /* @__PURE__ */ new Set(["preprocess", "postprocess", "processAllTokens", "emStrongMask"]);
1685
+ static passThroughHooksRespectAsync = /* @__PURE__ */ new Set(["preprocess", "postprocess", "processAllTokens"]);
1686
+ preprocess(e) {
1687
+ return e;
1688
+ }
1689
+ postprocess(e) {
1690
+ return e;
1691
+ }
1692
+ processAllTokens(e) {
1693
+ return e;
1694
+ }
1695
+ emStrongMask(e) {
1696
+ return e;
1697
+ }
1698
+ provideLexer(e = this.block) {
1699
+ return e ? x.lex : x.lexInline;
1700
+ }
1701
+ provideParser(e = this.block) {
1702
+ return e ? b.parse : b.parseInline;
1703
+ }
1704
+ };
1705
+ var q = class {
1706
+ defaults = M();
1707
+ options = this.setOptions;
1708
+ parse = this.parseMarkdown(true);
1709
+ parseInline = this.parseMarkdown(false);
1710
+ Parser = b;
1711
+ Renderer = y;
1712
+ TextRenderer = L;
1713
+ Lexer = x;
1714
+ Tokenizer = w;
1715
+ Hooks = P;
1716
+ constructor(...e) {
1717
+ this.use(...e);
1718
+ }
1719
+ walkTokens(e, t) {
1720
+ let n = [];
1721
+ for (let s of e) switch (n = n.concat(t.call(this, s)), s.type) {
1722
+ case "table": {
1723
+ let r = s;
1724
+ for (let i of r.header) n = n.concat(this.walkTokens(i.tokens, t));
1725
+ for (let i of r.rows) for (let o of i) n = n.concat(this.walkTokens(o.tokens, t));
1726
+ break;
1727
+ }
1728
+ case "list": {
1729
+ let r = s;
1730
+ n = n.concat(this.walkTokens(r.items, t));
1731
+ break;
1732
+ }
1733
+ default: {
1734
+ let r = s;
1735
+ this.defaults.extensions?.childTokens?.[r.type] ? this.defaults.extensions.childTokens[r.type].forEach((i) => {
1736
+ let o = r[i].flat(1 / 0);
1737
+ n = n.concat(this.walkTokens(o, t));
1738
+ }) : r.tokens && (n = n.concat(this.walkTokens(r.tokens, t)));
1739
+ }
1740
+ }
1741
+ return n;
1742
+ }
1743
+ use(...e) {
1744
+ let t = this.defaults.extensions || { renderers: {}, childTokens: {} };
1745
+ return e.forEach((n) => {
1746
+ let s = { ...n };
1747
+ if (s.async = this.defaults.async || s.async || false, n.extensions && (n.extensions.forEach((r) => {
1748
+ if (!r.name) throw new Error("extension name required");
1749
+ if ("renderer" in r) {
1750
+ let i = t.renderers[r.name];
1751
+ i ? t.renderers[r.name] = function(...o) {
1752
+ let u = r.renderer.apply(this, o);
1753
+ return u === false && (u = i.apply(this, o)), u;
1754
+ } : t.renderers[r.name] = r.renderer;
1755
+ }
1756
+ if ("tokenizer" in r) {
1757
+ if (!r.level || r.level !== "block" && r.level !== "inline") throw new Error("extension level must be 'block' or 'inline'");
1758
+ let i = t[r.level];
1759
+ i ? i.unshift(r.tokenizer) : t[r.level] = [r.tokenizer], r.start && (r.level === "block" ? t.startBlock ? t.startBlock.push(r.start) : t.startBlock = [r.start] : r.level === "inline" && (t.startInline ? t.startInline.push(r.start) : t.startInline = [r.start]));
1760
+ }
1761
+ "childTokens" in r && r.childTokens && (t.childTokens[r.name] = r.childTokens);
1762
+ }), s.extensions = t), n.renderer) {
1763
+ let r = this.defaults.renderer || new y(this.defaults);
1764
+ for (let i in n.renderer) {
1765
+ if (!(i in r)) throw new Error(`renderer '${i}' does not exist`);
1766
+ if (["options", "parser"].includes(i)) continue;
1767
+ let o = i, u = n.renderer[o], a = r[o];
1768
+ r[o] = (...c) => {
1769
+ let p = u.apply(r, c);
1770
+ return p === false && (p = a.apply(r, c)), p || "";
1771
+ };
1772
+ }
1773
+ s.renderer = r;
1774
+ }
1775
+ if (n.tokenizer) {
1776
+ let r = this.defaults.tokenizer || new w(this.defaults);
1777
+ for (let i in n.tokenizer) {
1778
+ if (!(i in r)) throw new Error(`tokenizer '${i}' does not exist`);
1779
+ if (["options", "rules", "lexer"].includes(i)) continue;
1780
+ let o = i, u = n.tokenizer[o], a = r[o];
1781
+ r[o] = (...c) => {
1782
+ let p = u.apply(r, c);
1783
+ return p === false && (p = a.apply(r, c)), p;
1784
+ };
1785
+ }
1786
+ s.tokenizer = r;
1787
+ }
1788
+ if (n.hooks) {
1789
+ let r = this.defaults.hooks || new P();
1790
+ for (let i in n.hooks) {
1791
+ if (!(i in r)) throw new Error(`hook '${i}' does not exist`);
1792
+ if (["options", "block"].includes(i)) continue;
1793
+ let o = i, u = n.hooks[o], a = r[o];
1794
+ P.passThroughHooks.has(i) ? r[o] = (c) => {
1795
+ if (this.defaults.async && P.passThroughHooksRespectAsync.has(i)) return (async () => {
1796
+ let k = await u.call(r, c);
1797
+ return a.call(r, k);
1798
+ })();
1799
+ let p = u.call(r, c);
1800
+ return a.call(r, p);
1801
+ } : r[o] = (...c) => {
1802
+ if (this.defaults.async) return (async () => {
1803
+ let k = await u.apply(r, c);
1804
+ return k === false && (k = await a.apply(r, c)), k;
1805
+ })();
1806
+ let p = u.apply(r, c);
1807
+ return p === false && (p = a.apply(r, c)), p;
1808
+ };
1809
+ }
1810
+ s.hooks = r;
1811
+ }
1812
+ if (n.walkTokens) {
1813
+ let r = this.defaults.walkTokens, i = n.walkTokens;
1814
+ s.walkTokens = function(o) {
1815
+ let u = [];
1816
+ return u.push(i.call(this, o)), r && (u = u.concat(r.call(this, o))), u;
1817
+ };
1818
+ }
1819
+ this.defaults = { ...this.defaults, ...s };
1820
+ }), this;
1821
+ }
1822
+ setOptions(e) {
1823
+ return this.defaults = { ...this.defaults, ...e }, this;
1824
+ }
1825
+ lexer(e, t) {
1826
+ return x.lex(e, t ?? this.defaults);
1827
+ }
1828
+ parser(e, t) {
1829
+ return b.parse(e, t ?? this.defaults);
1830
+ }
1831
+ parseMarkdown(e) {
1832
+ return (n, s) => {
1833
+ let r = { ...s }, i = { ...this.defaults, ...r }, o = this.onError(!!i.silent, !!i.async);
1834
+ if (this.defaults.async === true && r.async === false) return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));
1835
+ if (typeof n > "u" || n === null) return o(new Error("marked(): input parameter is undefined or null"));
1836
+ if (typeof n != "string") return o(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(n) + ", string expected"));
1837
+ if (i.hooks && (i.hooks.options = i, i.hooks.block = e), i.async) return (async () => {
1838
+ let u = i.hooks ? await i.hooks.preprocess(n) : n, c = await (i.hooks ? await i.hooks.provideLexer(e) : e ? x.lex : x.lexInline)(u, i), p = i.hooks ? await i.hooks.processAllTokens(c) : c;
1839
+ i.walkTokens && await Promise.all(this.walkTokens(p, i.walkTokens));
1840
+ let h = await (i.hooks ? await i.hooks.provideParser(e) : e ? b.parse : b.parseInline)(p, i);
1841
+ return i.hooks ? await i.hooks.postprocess(h) : h;
1842
+ })().catch(o);
1843
+ try {
1844
+ i.hooks && (n = i.hooks.preprocess(n));
1845
+ let a = (i.hooks ? i.hooks.provideLexer(e) : e ? x.lex : x.lexInline)(n, i);
1846
+ i.hooks && (a = i.hooks.processAllTokens(a)), i.walkTokens && this.walkTokens(a, i.walkTokens);
1847
+ let p = (i.hooks ? i.hooks.provideParser(e) : e ? b.parse : b.parseInline)(a, i);
1848
+ return i.hooks && (p = i.hooks.postprocess(p)), p;
1849
+ } catch (u) {
1850
+ return o(u);
1851
+ }
1852
+ };
1853
+ }
1854
+ onError(e, t) {
1855
+ return (n) => {
1856
+ if (n.message += `
1857
+ Please report this to https://github.com/markedjs/marked.`, e) {
1858
+ let s = "<p>An error occurred:</p><pre>" + O(n.message + "", true) + "</pre>";
1859
+ return t ? Promise.resolve(s) : s;
1860
+ }
1861
+ if (t) return Promise.reject(n);
1862
+ throw n;
1863
+ };
1864
+ }
1865
+ };
1866
+ var z = new q();
1867
+ function g(l3, e) {
1868
+ return z.parse(l3, e);
1869
+ }
1870
+ g.options = g.setOptions = function(l3) {
1871
+ return z.setOptions(l3), g.defaults = z.defaults, N(g.defaults), g;
1872
+ };
1873
+ g.getDefaults = M;
1874
+ g.defaults = T;
1875
+ g.use = function(...l3) {
1876
+ return z.use(...l3), g.defaults = z.defaults, N(g.defaults), g;
1877
+ };
1878
+ g.walkTokens = function(l3, e) {
1879
+ return z.walkTokens(l3, e);
1880
+ };
1881
+ g.parseInline = z.parseInline;
1882
+ g.Parser = b;
1883
+ g.parser = b.parse;
1884
+ g.Renderer = y;
1885
+ g.TextRenderer = L;
1886
+ g.Lexer = x;
1887
+ g.lexer = x.lex;
1888
+ g.Tokenizer = w;
1889
+ g.Hooks = P;
1890
+ g.parse = g;
1891
+ var Ft = g.options;
1892
+ var Ut = g.setOptions;
1893
+ var Kt = g.use;
1894
+ var Wt = g.walkTokens;
1895
+ var Xt = g.parseInline;
1896
+ var Vt = b.parse;
1897
+ var Yt = x.lex;
1898
+
1899
+ // packages/extensions/pages/src/markdown.ts
1900
+ var marked = new q({ gfm: true });
1901
+ var BASE_STYLES = `
1902
+ *, *::before, *::after { box-sizing: border-box; }
1903
+ body {
1904
+ max-width: 48rem;
1905
+ margin: 2rem auto;
1906
+ padding: 0 1rem;
1907
+ font-family: system-ui, -apple-system, sans-serif;
1908
+ line-height: 1.6;
1909
+ color: #1a1a1a;
1910
+ }
1911
+ h1, h2, h3, h4, h5, h6 { margin-top: 1.5em; margin-bottom: 0.5em; line-height: 1.3; }
1912
+ h1 { font-size: 2em; }
1913
+ a { color: #2563eb; }
1914
+ code {
1915
+ font-family: ui-monospace, "SFMono-Regular", monospace;
1916
+ font-size: 0.9em;
1917
+ background: #f3f4f6;
1918
+ padding: 0.15em 0.3em;
1919
+ border-radius: 3px;
1920
+ }
1921
+ pre {
1922
+ background: #f3f4f6;
1923
+ padding: 1em;
1924
+ border-radius: 6px;
1925
+ overflow-x: auto;
1926
+ }
1927
+ pre code { background: none; padding: 0; }
1928
+ blockquote {
1929
+ border-left: 3px solid #d1d5db;
1930
+ margin-left: 0;
1931
+ padding-left: 1em;
1932
+ color: #4b5563;
1933
+ }
1934
+ table { border-collapse: collapse; width: 100%; }
1935
+ th, td { border: 1px solid #d1d5db; padding: 0.5em 0.75em; text-align: left; }
1936
+ th { background: #f9fafb; }
1937
+ img { max-width: 100%; height: auto; }
1938
+ hr { border: none; border-top: 1px solid #d1d5db; margin: 2em 0; }
1939
+ `;
1940
+ function escapeHtml(s) {
1941
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1942
+ }
1943
+ function parseFrontmatter(raw) {
1944
+ const match = raw.match(/^---\n([\s\S]*?)\n---\n?/);
1945
+ if (!match) return { body: raw };
1946
+ const block = match[1];
1947
+ const body = raw.slice(match[0].length);
1948
+ const titleMatch = block.match(/^title:\s*(.+)$/m);
1949
+ const styleMatch = block.match(/^style:\s*(.+)$/m);
1950
+ return {
1951
+ title: titleMatch?.[1].trim(),
1952
+ style: styleMatch?.[1].trim(),
1953
+ body
1954
+ };
1955
+ }
1956
+ function resolveStylesheet(mdFilePath, pagesRoot, frontmatterStyle) {
1957
+ if (frontmatterStyle) {
1958
+ const abs = resolve3(pagesRoot, frontmatterStyle);
1959
+ if (abs.startsWith(pagesRoot + "/") && existsSync3(abs)) return frontmatterStyle;
1960
+ }
1961
+ const dir = dirname(mdFilePath);
1962
+ const localCss = resolve3(dir, "style.css");
1963
+ if (existsSync3(localCss)) return relative3(pagesRoot, localCss);
1964
+ if (dir !== pagesRoot) {
1965
+ const rootCss = resolve3(pagesRoot, "style.css");
1966
+ if (existsSync3(rootCss)) return "style.css";
1967
+ }
1968
+ return null;
1969
+ }
1970
+ async function renderMarkdownPage(body, opts) {
1971
+ const html = DOMPurify.sanitize(await marked.parse(body));
1972
+ const title = escapeHtml(opts.title || "Untitled");
1973
+ const linkTag = opts.stylesheetUrl ? `
1974
+ <link rel="stylesheet" href="${escapeHtml(opts.stylesheetUrl)}">` : "";
1975
+ return `<!DOCTYPE html>
1976
+ <html lang="en">
1977
+ <head>
1978
+ <meta charset="utf-8">
1979
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1980
+ <title>${title}</title>
1981
+ <style>${BASE_STYLES}</style>${linkTag}
1982
+ </head>
1983
+ <body>
1984
+ <article>${html}</article>
1985
+ </body>
1986
+ </html>`;
1987
+ }
1988
+
1989
+ // packages/extensions/pages/src/routes.ts
1990
+ var MIME_TYPES = {
1991
+ ".html": "text/html",
1992
+ ".js": "application/javascript",
1993
+ ".css": "text/css",
1994
+ ".json": "application/json",
1995
+ ".svg": "image/svg+xml",
1996
+ ".png": "image/png",
1997
+ ".jpg": "image/jpeg",
1998
+ ".jpeg": "image/jpeg",
1999
+ ".gif": "image/gif",
2000
+ ".ico": "image/x-icon",
2001
+ ".woff": "font/woff",
2002
+ ".woff2": "font/woff2",
2003
+ ".txt": "text/plain",
2004
+ ".xml": "application/xml"
2005
+ };
2006
+ function createRoutes(ctx) {
2007
+ return new Hono().get("/", async (c) => {
2008
+ if (!ctx.db) return c.json({ error: "Pages database not available" }, 503);
2009
+ const { sites, systemSite } = getSites(ctx.db);
2010
+ const recentPages = getRecentPagesList(ctx.db);
2011
+ return c.json({ sites, systemSite, recentPages });
2012
+ }).get("/feed", async (c) => {
2013
+ if (!ctx.db) return c.json({ error: "Pages database not available" }, 503);
2014
+ const mind = c.req.query("mind");
2015
+ const rawLimit = c.req.query("limit");
2016
+ const limit = rawLimit ? parseInt(rawLimit, 10) || 8 : 8;
2017
+ const recentPages = getRecentPagesList(ctx.db, { mind: mind || void 0, limit });
2018
+ return c.json(
2019
+ recentPages.map((p) => ({
2020
+ id: `page-${p.mind}-${p.file}`,
2021
+ title: `${p.mind}/${p.file}`,
2022
+ url: p.url ?? `/minds/${p.mind}/pages/${p.file}`,
2023
+ date: p.modified,
2024
+ author: p.mind,
2025
+ bodyHtml: `<p>Page updated</p>`,
2026
+ iframeUrl: `/ext/pages/public/${p.mind}/${p.file}`,
2027
+ icon: '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="8" r="6"/><path d="M2 8h12M8 2c-2 2-2 10 0 12M8 2c2 2 2 10 0 12"/></svg>',
2028
+ color: "purple"
2029
+ }))
2030
+ );
2031
+ }).put("/publish/:name", async (c) => {
2032
+ const user = ctx.resolveUser(c);
2033
+ if (!user) return c.json({ error: "Unauthorized" }, 401);
2034
+ const name = c.req.param("name");
2035
+ if (user.role !== "admin" && user.username !== name) {
2036
+ return c.json({ error: "Forbidden" }, 403);
2037
+ }
2038
+ const config = ctx.getSystemsConfig();
2039
+ if (!config) return c.json({ error: "Not connected to volute.systems" }, 400);
2040
+ const body = await c.req.text();
2041
+ try {
2042
+ const res = await fetch(`${config.apiUrl}/api/pages/publish/${name}`, {
2043
+ method: "PUT",
2044
+ headers: {
2045
+ "Content-Type": "application/json",
2046
+ Authorization: `Bearer ${config.apiKey}`
2047
+ },
2048
+ body
2049
+ });
2050
+ const data = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));
2051
+ return c.json(data, res.status);
2052
+ } catch (err) {
2053
+ return c.json({ error: `Connection failed: ${err.message}` }, 502);
2054
+ }
2055
+ }).get("/status/:name", async (c) => {
2056
+ const user = ctx.resolveUser(c);
2057
+ if (!user) return c.json({ error: "Unauthorized" }, 401);
2058
+ const name = c.req.param("name");
2059
+ if (user.role !== "admin" && user.username !== name) {
2060
+ return c.json({ error: "Forbidden" }, 403);
2061
+ }
2062
+ const config = ctx.getSystemsConfig();
2063
+ if (!config) return c.json({ error: "Not connected to volute.systems" }, 400);
2064
+ try {
2065
+ const res = await fetch(`${config.apiUrl}/api/pages/status/${name}`, {
2066
+ headers: { Authorization: `Bearer ${config.apiKey}` }
2067
+ });
2068
+ const data = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));
2069
+ return c.json(data, res.status);
2070
+ } catch (err) {
2071
+ return c.json({ error: `Connection failed: ${err.message}` }, 502);
2072
+ }
2073
+ });
2074
+ }
2075
+ var PAGES_CSP = "default-src 'none'; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; font-src 'self'; base-uri 'none'; form-action 'none'";
2076
+ function createPublicRoutes(ctx) {
2077
+ return new Hono().use("*", async (c, next) => {
2078
+ await next();
2079
+ c.res.headers.set("Content-Security-Policy", PAGES_CSP);
2080
+ c.res.headers.set("X-Content-Type-Options", "nosniff");
2081
+ }).get("/:name/*", async (c) => {
2082
+ const name = c.req.param("name");
2083
+ if (name.includes("/") || name.includes("\\") || name === "." || name === "..")
2084
+ return c.text("Not found", 404);
2085
+ let pagesRoot;
2086
+ let blockDotfiles = false;
2087
+ if (name === "_system") {
2088
+ pagesRoot = resolve4(ctx.dataDir, "repo");
2089
+ blockDotfiles = true;
2090
+ } else {
2091
+ pagesRoot = resolve4(ctx.dataDir, "sites", name);
2092
+ }
2093
+ const prefix = `/public/${name}`;
2094
+ const idx = c.req.path.indexOf(prefix);
2095
+ const wildcard = idx >= 0 ? c.req.path.slice(idx + prefix.length) : "/";
2096
+ const requestedPath = resolve4(pagesRoot, wildcard.slice(1));
2097
+ if (requestedPath !== pagesRoot && !requestedPath.startsWith(`${pagesRoot}/`))
2098
+ return c.text("Forbidden", 403);
2099
+ if (blockDotfiles) {
2100
+ const relativePath = requestedPath.slice(pagesRoot.length + 1);
2101
+ if (relativePath.split("/").some((seg) => seg.startsWith(".")))
2102
+ return c.text("Not found", 404);
2103
+ }
2104
+ let fileToServe = requestedPath;
2105
+ let fileStat = await stat(requestedPath).catch(() => null);
2106
+ if (fileStat?.isDirectory()) {
2107
+ const indexPath = resolve4(requestedPath, "index.html");
2108
+ fileStat = await stat(indexPath).catch(() => null);
2109
+ if (fileStat?.isFile()) {
2110
+ fileToServe = indexPath;
2111
+ } else {
2112
+ const mdIndexPath = resolve4(requestedPath, "index.md");
2113
+ fileStat = await stat(mdIndexPath).catch(() => null);
2114
+ if (fileStat?.isFile()) {
2115
+ fileToServe = mdIndexPath;
2116
+ } else {
2117
+ return c.text("Not found", 404);
2118
+ }
2119
+ }
2120
+ } else if (!fileStat?.isFile()) {
2121
+ return c.text("Not found", 404);
2122
+ }
2123
+ const ext = extname(fileToServe);
2124
+ try {
2125
+ if (ext === ".md") {
2126
+ const content = await readFile(fileToServe, "utf-8");
2127
+ const { title, style, body: body2 } = parseFrontmatter(content);
2128
+ const cssRelPath = resolveStylesheet(fileToServe, pagesRoot, style);
2129
+ const cssUrl = cssRelPath ? `/ext/pages/public/${name}/${cssRelPath}` : void 0;
2130
+ const html = await renderMarkdownPage(body2, { title, stylesheetUrl: cssUrl });
2131
+ return c.body(html, 200, { "Content-Type": "text/html; charset=utf-8" });
2132
+ }
2133
+ const mime = MIME_TYPES[ext] || "application/octet-stream";
2134
+ const body = await readFile(fileToServe);
2135
+ return c.body(body, 200, { "Content-Type": mime });
2136
+ } catch (err) {
2137
+ const code = err.code;
2138
+ if (code === "EACCES") return c.text("Forbidden", 403);
2139
+ if (code === "ENOENT") return c.text("Not found", 404);
2140
+ console.error(`[pages] error serving ${fileToServe}:`, err.message);
2141
+ return c.text("Internal server error", 500);
2142
+ }
2143
+ });
2144
+ }
2145
+
2146
+ // packages/extensions/pages/src/index.ts
2147
+ var assetsDir = resolve5(import.meta.dirname, "../dist/ui");
2148
+ var skillsDir = resolve5(import.meta.dirname, "../skills");
2149
+ var src_default = createExtension({
2150
+ id: "pages",
2151
+ name: "Pages",
2152
+ version: "0.1.0",
2153
+ description: "Publish and serve web pages from mind directories",
2154
+ initDb,
2155
+ routes: (ctx) => createRoutes(ctx),
2156
+ publicRoutes: (ctx) => createPublicRoutes(ctx),
2157
+ commands: createCommands(),
2158
+ skillsDir,
2159
+ standardSkill: true,
2160
+ icon: '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="1" y="2" width="14" height="12" rx="1.5"/><path d="M1 5h14"/><circle cx="3" cy="3.5" r="0.5" fill="currentColor" stroke="none"/><circle cx="5" cy="3.5" r="0.5" fill="currentColor" stroke="none"/></svg>',
2161
+ color: "purple",
2162
+ ui: {
2163
+ assetsDir,
2164
+ systemSection: {
2165
+ id: "pages",
2166
+ label: "Pages",
2167
+ urlPatterns: ["/pages", "/pages/:site", "/pages/:site/:path"]
2168
+ },
2169
+ mindSections: [{ id: "pages", label: "Pages" }],
2170
+ feedSource: {
2171
+ endpoint: "/api/ext/pages/feed"
2172
+ }
2173
+ },
2174
+ onDaemonStart(ctx) {
2175
+ ensurePagesRepo(ctx.dataDir, isolationFrom(ctx)).then(() => {
2176
+ if (ctx.db) {
2177
+ const repoDir = resolve5(ctx.dataDir, "repo");
2178
+ const htmlFiles = collectHtmlFiles(repoDir);
2179
+ if (htmlFiles.length > 0) {
2180
+ try {
2181
+ syncSystemPages(ctx.db, htmlFiles);
2182
+ } catch (err) {
2183
+ console.error("[pages] failed to sync system pages to DB:", err);
2184
+ }
2185
+ }
2186
+ }
2187
+ }).catch((err) => {
2188
+ console.error("[pages] failed to initialize pages repo:", err);
2189
+ });
2190
+ },
2191
+ onMindStart(mindName, ctx) {
2192
+ const mindDir = ctx.getMindDir(mindName);
2193
+ if (!mindDir) return;
2194
+ addPagesWorktree(mindName, mindDir, ctx.dataDir, isolationFrom(ctx)).catch((err) => {
2195
+ console.error(`[pages] failed to add pages worktree for ${mindName}:`, err);
2196
+ });
2197
+ }
2198
+ });
2199
+ export {
2200
+ src_default as default
2201
+ };