inlaycms 0.0.0-stage → 0.2.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 (364) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +469 -2
  3. package/assets/admin/admin.css +2 -0
  4. package/assets/admin/admin.js +1 -0
  5. package/assets/admin/editor.js +125 -0
  6. package/dist/adapters/admin/activity.d.ts +17 -0
  7. package/dist/adapters/admin/activity.js +59 -0
  8. package/dist/adapters/admin/assets.d.ts +14 -0
  9. package/dist/adapters/admin/assets.js +64 -0
  10. package/dist/adapters/admin/attention.d.ts +15 -0
  11. package/dist/adapters/admin/attention.js +34 -0
  12. package/dist/adapters/admin/context.d.ts +40 -0
  13. package/dist/adapters/admin/context.js +142 -0
  14. package/dist/adapters/admin/form/walk.d.ts +61 -0
  15. package/dist/adapters/admin/form/walk.js +565 -0
  16. package/dist/adapters/admin/pages.d.ts +38 -0
  17. package/dist/adapters/admin/pages.js +66 -0
  18. package/dist/adapters/admin/publish.d.ts +12 -0
  19. package/dist/adapters/admin/publish.js +195 -0
  20. package/dist/adapters/admin/routes.d.ts +47 -0
  21. package/dist/adapters/admin/routes.js +255 -0
  22. package/dist/adapters/admin/screens/backups.d.ts +11 -0
  23. package/dist/adapters/admin/screens/backups.js +223 -0
  24. package/dist/adapters/admin/screens/dashboard.d.ts +4 -0
  25. package/dist/adapters/admin/screens/dashboard.js +160 -0
  26. package/dist/adapters/admin/screens/editor.d.ts +67 -0
  27. package/dist/adapters/admin/screens/editor.js +416 -0
  28. package/dist/adapters/admin/screens/history.d.ts +4 -0
  29. package/dist/adapters/admin/screens/history.js +105 -0
  30. package/dist/adapters/admin/screens/lists.d.ts +4 -0
  31. package/dist/adapters/admin/screens/lists.js +297 -0
  32. package/dist/adapters/admin/screens/media.d.ts +20 -0
  33. package/dist/adapters/admin/screens/media.js +186 -0
  34. package/dist/adapters/admin/screens/pickers.d.ts +29 -0
  35. package/dist/adapters/admin/screens/pickers.js +134 -0
  36. package/dist/adapters/admin/screens/preview-pane.d.ts +10 -0
  37. package/dist/adapters/admin/screens/preview-pane.js +74 -0
  38. package/dist/adapters/admin/screens/redirects.d.ts +4 -0
  39. package/dist/adapters/admin/screens/redirects.js +137 -0
  40. package/dist/adapters/admin/screens/releases.d.ts +7 -0
  41. package/dist/adapters/admin/screens/releases.js +287 -0
  42. package/dist/adapters/admin/screens/search.d.ts +22 -0
  43. package/dist/adapters/admin/screens/search.js +113 -0
  44. package/dist/adapters/admin/screens/security.d.ts +4 -0
  45. package/dist/adapters/admin/screens/security.js +85 -0
  46. package/dist/adapters/admin/screens/users.d.ts +4 -0
  47. package/dist/adapters/admin/screens/users.js +330 -0
  48. package/dist/adapters/admin/theme.d.ts +1 -0
  49. package/dist/adapters/admin/theme.js +1 -0
  50. package/dist/adapters/admin/translations.d.ts +16 -0
  51. package/dist/adapters/admin/translations.js +23 -0
  52. package/dist/adapters/admin/upload.d.ts +8 -0
  53. package/dist/adapters/admin/upload.js +116 -0
  54. package/dist/adapters/admin/views/data-table.d.ts +82 -0
  55. package/dist/adapters/admin/views/data-table.js +117 -0
  56. package/dist/adapters/admin/views/icons.d.ts +48 -0
  57. package/dist/adapters/admin/views/icons.js +47 -0
  58. package/dist/adapters/admin/views/layout.d.ts +51 -0
  59. package/dist/adapters/admin/views/layout.js +145 -0
  60. package/dist/adapters/admin/views/sheet.d.ts +15 -0
  61. package/dist/adapters/admin/views/sheet.js +6 -0
  62. package/dist/adapters/admin/views/status.d.ts +32 -0
  63. package/dist/adapters/admin/views/status.js +74 -0
  64. package/dist/adapters/auth/handler.d.ts +10 -0
  65. package/dist/adapters/auth/handler.js +63 -0
  66. package/dist/adapters/auth/request.d.ts +8 -0
  67. package/dist/adapters/auth/request.js +14 -0
  68. package/dist/adapters/cli/bin.d.ts +2 -0
  69. package/dist/adapters/cli/bin.js +42 -0
  70. package/dist/adapters/cli/main.d.ts +7 -0
  71. package/dist/adapters/cli/main.js +982 -0
  72. package/dist/adapters/cli/remote.d.ts +52 -0
  73. package/dist/adapters/cli/remote.js +161 -0
  74. package/dist/adapters/mcp/agent-refs.d.ts +9 -0
  75. package/dist/adapters/mcp/agent-refs.js +25 -0
  76. package/dist/adapters/mcp/documents.d.ts +15 -0
  77. package/dist/adapters/mcp/documents.js +26 -0
  78. package/dist/adapters/mcp/fetch-url.d.ts +19 -0
  79. package/dist/adapters/mcp/fetch-url.js +244 -0
  80. package/dist/adapters/mcp/request-state.d.ts +15 -0
  81. package/dist/adapters/mcp/request-state.js +38 -0
  82. package/dist/adapters/mcp/results.d.ts +20 -0
  83. package/dist/adapters/mcp/results.js +61 -0
  84. package/dist/adapters/mcp/route.d.ts +34 -0
  85. package/dist/adapters/mcp/route.js +52 -0
  86. package/dist/adapters/mcp/server.d.ts +44 -0
  87. package/dist/adapters/mcp/server.js +49 -0
  88. package/dist/adapters/mcp/tools/history.d.ts +5 -0
  89. package/dist/adapters/mcp/tools/history.js +84 -0
  90. package/dist/adapters/mcp/tools/media.d.ts +5 -0
  91. package/dist/adapters/mcp/tools/media.js +102 -0
  92. package/dist/adapters/mcp/tools/publish.d.ts +5 -0
  93. package/dist/adapters/mcp/tools/publish.js +157 -0
  94. package/dist/adapters/mcp/tools/read.d.ts +5 -0
  95. package/dist/adapters/mcp/tools/read.js +279 -0
  96. package/dist/adapters/mcp/tools/redirects.d.ts +5 -0
  97. package/dist/adapters/mcp/tools/redirects.js +74 -0
  98. package/dist/adapters/mcp/tools/write.d.ts +5 -0
  99. package/dist/adapters/mcp/tools/write.js +304 -0
  100. package/dist/adapters/site/backup-schedule.d.ts +8 -0
  101. package/dist/adapters/site/backup-schedule.js +31 -0
  102. package/dist/adapters/site/cache.d.ts +29 -0
  103. package/dist/adapters/site/cache.js +63 -0
  104. package/dist/adapters/site/context.d.ts +29 -0
  105. package/dist/adapters/site/context.js +278 -0
  106. package/dist/adapters/site/head.d.ts +23 -0
  107. package/dist/adapters/site/head.js +44 -0
  108. package/dist/adapters/site/limiter.d.ts +17 -0
  109. package/dist/adapters/site/limiter.js +39 -0
  110. package/dist/adapters/site/lock.d.ts +30 -0
  111. package/dist/adapters/site/lock.js +143 -0
  112. package/dist/adapters/site/media-routes.d.ts +4 -0
  113. package/dist/adapters/site/media-routes.js +55 -0
  114. package/dist/adapters/site/plugin.d.ts +122 -0
  115. package/dist/adapters/site/plugin.js +436 -0
  116. package/dist/adapters/site/preview.d.ts +36 -0
  117. package/dist/adapters/site/preview.js +82 -0
  118. package/dist/adapters/site/public.d.ts +6 -0
  119. package/dist/adapters/site/public.js +87 -0
  120. package/dist/adapters/site/render.d.ts +45 -0
  121. package/dist/adapters/site/render.js +191 -0
  122. package/dist/adapters/site/routes.d.ts +17 -0
  123. package/dist/adapters/site/routes.js +125 -0
  124. package/dist/adapters/site/sitemap.d.ts +10 -0
  125. package/dist/adapters/site/sitemap.js +10 -0
  126. package/dist/adapters/web.d.ts +22 -0
  127. package/dist/adapters/web.js +75 -0
  128. package/dist/config.d.ts +21 -0
  129. package/dist/config.js +58 -0
  130. package/dist/core/agent/format.d.ts +62 -0
  131. package/dist/core/agent/format.js +211 -0
  132. package/dist/core/agent/schema.d.ts +6 -0
  133. package/dist/core/agent/schema.js +86 -0
  134. package/dist/core/archive.d.ts +12 -0
  135. package/dist/core/archive.js +72 -0
  136. package/dist/core/auth/auth.d.ts +4911 -0
  137. package/dist/core/auth/auth.js +61 -0
  138. package/dist/core/auth/roles.d.ts +10 -0
  139. package/dist/core/auth/roles.js +38 -0
  140. package/dist/core/auth/service.d.ts +118 -0
  141. package/dist/core/auth/service.js +424 -0
  142. package/dist/core/auth/upload-token.d.ts +8 -0
  143. package/dist/core/auth/upload-token.js +27 -0
  144. package/dist/core/backup/backup.d.ts +28 -0
  145. package/dist/core/backup/backup.js +126 -0
  146. package/dist/core/backup/restore.d.ts +41 -0
  147. package/dist/core/backup/restore.js +264 -0
  148. package/dist/core/backup/schedule.d.ts +12 -0
  149. package/dist/core/backup/schedule.js +29 -0
  150. package/dist/core/boot.d.ts +63 -0
  151. package/dist/core/boot.js +141 -0
  152. package/dist/core/check.d.ts +32 -0
  153. package/dist/core/check.js +111 -0
  154. package/dist/core/content/activity.d.ts +8 -0
  155. package/dist/core/content/activity.js +101 -0
  156. package/dist/core/content/delete.d.ts +5 -0
  157. package/dist/core/content/delete.js +100 -0
  158. package/dist/core/content/diff.d.ts +6 -0
  159. package/dist/core/content/diff.js +129 -0
  160. package/dist/core/content/dry-run.d.ts +24 -0
  161. package/dist/core/content/dry-run.js +69 -0
  162. package/dist/core/content/gaps.d.ts +25 -0
  163. package/dist/core/content/gaps.js +50 -0
  164. package/dist/core/content/hidden.d.ts +33 -0
  165. package/dist/core/content/hidden.js +103 -0
  166. package/dist/core/content/history.d.ts +15 -0
  167. package/dist/core/content/history.js +62 -0
  168. package/dist/core/content/patch.d.ts +40 -0
  169. package/dist/core/content/patch.js +287 -0
  170. package/dist/core/content/path.d.ts +6 -0
  171. package/dist/core/content/path.js +38 -0
  172. package/dist/core/content/publish.d.ts +26 -0
  173. package/dist/core/content/publish.js +211 -0
  174. package/dist/core/content/read.d.ts +99 -0
  175. package/dist/core/content/read.js +141 -0
  176. package/dist/core/content/reader.d.ts +37 -0
  177. package/dist/core/content/reader.js +195 -0
  178. package/dist/core/content/refs.d.ts +44 -0
  179. package/dist/core/content/refs.js +161 -0
  180. package/dist/core/content/release-migrations.d.ts +12 -0
  181. package/dist/core/content/release-migrations.js +154 -0
  182. package/dist/core/content/save.d.ts +25 -0
  183. package/dist/core/content/save.js +87 -0
  184. package/dist/core/content/schema.d.ts +22 -0
  185. package/dist/core/content/schema.js +127 -0
  186. package/dist/core/content/search.d.ts +8 -0
  187. package/dist/core/content/search.js +89 -0
  188. package/dist/core/content/shipped-input.d.ts +39 -0
  189. package/dist/core/content/shipped-input.js +221 -0
  190. package/dist/core/content/shipped.d.ts +112 -0
  191. package/dist/core/content/shipped.js +437 -0
  192. package/dist/core/content/slug.d.ts +23 -0
  193. package/dist/core/content/slug.js +182 -0
  194. package/dist/core/content/stats.d.ts +11 -0
  195. package/dist/core/content/stats.js +30 -0
  196. package/dist/core/content/translate.d.ts +3 -0
  197. package/dist/core/content/translate.js +68 -0
  198. package/dist/core/content/usages.d.ts +13 -0
  199. package/dist/core/content/usages.js +70 -0
  200. package/dist/core/content/validate.d.ts +21 -0
  201. package/dist/core/content/validate.js +124 -0
  202. package/dist/core/content/write.d.ts +10 -0
  203. package/dist/core/content/write.js +93 -0
  204. package/dist/core/core.d.ts +227 -0
  205. package/dist/core/core.js +251 -0
  206. package/dist/core/db/connection.d.ts +6 -0
  207. package/dist/core/db/connection.js +12 -0
  208. package/dist/core/db/migrate.d.ts +9 -0
  209. package/dist/core/db/migrate.js +42 -0
  210. package/dist/core/db/migrations/0001_content.d.ts +2 -0
  211. package/dist/core/db/migrations/0001_content.js +69 -0
  212. package/dist/core/db/migrations/0002_media.d.ts +2 -0
  213. package/dist/core/db/migrations/0002_media.js +26 -0
  214. package/dist/core/db/migrations/0003_redirects.d.ts +2 -0
  215. package/dist/core/db/migrations/0003_redirects.js +19 -0
  216. package/dist/core/db/migrations/0004_token_cutoffs.d.ts +3 -0
  217. package/dist/core/db/migrations/0004_token_cutoffs.js +8 -0
  218. package/dist/core/db/migrations/0005_site_lock.d.ts +3 -0
  219. package/dist/core/db/migrations/0005_site_lock.js +10 -0
  220. package/dist/core/db/migrations/0006_releases.d.ts +3 -0
  221. package/dist/core/db/migrations/0006_releases.js +34 -0
  222. package/dist/core/db/schema.d.ts +155 -0
  223. package/dist/core/db/schema.js +1 -0
  224. package/dist/core/errors.d.ts +27 -0
  225. package/dist/core/errors.js +15 -0
  226. package/dist/core/export/export.d.ts +17 -0
  227. package/dist/core/export/export.js +185 -0
  228. package/dist/core/export/format.d.ts +241 -0
  229. package/dist/core/export/format.js +106 -0
  230. package/dist/core/export/import.d.ts +54 -0
  231. package/dist/core/export/import.js +180 -0
  232. package/dist/core/export/read.d.ts +16 -0
  233. package/dist/core/export/read.js +234 -0
  234. package/dist/core/export/replace.d.ts +17 -0
  235. package/dist/core/export/replace.js +36 -0
  236. package/dist/core/export/report.d.ts +55 -0
  237. package/dist/core/export/report.js +50 -0
  238. package/dist/core/export/schema.d.ts +8 -0
  239. package/dist/core/export/schema.js +47 -0
  240. package/dist/core/export/stage.d.ts +25 -0
  241. package/dist/core/export/stage.js +192 -0
  242. package/dist/core/fields/builtins.d.ts +70 -0
  243. package/dist/core/fields/builtins.js +335 -0
  244. package/dist/core/fields/define.d.ts +86 -0
  245. package/dist/core/fields/define.js +34 -0
  246. package/dist/core/fields/walk.d.ts +49 -0
  247. package/dist/core/fields/walk.js +270 -0
  248. package/dist/core/fields/widgets.d.ts +27 -0
  249. package/dist/core/fields/widgets.js +330 -0
  250. package/dist/core/fields/zod-internals.d.ts +29 -0
  251. package/dist/core/fields/zod-internals.js +28 -0
  252. package/dist/core/media/detect.d.ts +5 -0
  253. package/dist/core/media/detect.js +66 -0
  254. package/dist/core/media/labels.d.ts +6 -0
  255. package/dist/core/media/labels.js +17 -0
  256. package/dist/core/media/library.d.ts +45 -0
  257. package/dist/core/media/library.js +239 -0
  258. package/dist/core/media/store.d.ts +11 -0
  259. package/dist/core/media/store.js +49 -0
  260. package/dist/core/media/variants.d.ts +10 -0
  261. package/dist/core/media/variants.js +59 -0
  262. package/dist/core/messages/en.d.ts +1278 -0
  263. package/dist/core/messages/en.js +1287 -0
  264. package/dist/core/messages/index.d.ts +7 -0
  265. package/dist/core/messages/index.js +14 -0
  266. package/dist/core/preview.d.ts +16 -0
  267. package/dist/core/preview.js +42 -0
  268. package/dist/core/redirects/collapse.d.ts +68 -0
  269. package/dist/core/redirects/collapse.js +153 -0
  270. package/dist/core/redirects/csv.d.ts +15 -0
  271. package/dist/core/redirects/csv.js +68 -0
  272. package/dist/core/redirects/redirects.d.ts +58 -0
  273. package/dist/core/redirects/redirects.js +545 -0
  274. package/dist/core/registry/content.d.ts +26 -0
  275. package/dist/core/registry/content.js +9 -0
  276. package/dist/core/registry/define.d.ts +145 -0
  277. package/dist/core/registry/define.js +41 -0
  278. package/dist/core/registry/migration.d.ts +44 -0
  279. package/dist/core/registry/migration.js +4 -0
  280. package/dist/core/registry/registry.d.ts +18 -0
  281. package/dist/core/registry/registry.js +255 -0
  282. package/dist/core/registry/render.d.ts +98 -0
  283. package/dist/core/registry/render.js +1 -0
  284. package/dist/core/registry/route.d.ts +42 -0
  285. package/dist/core/registry/route.js +3 -0
  286. package/dist/core/release/bundle.d.ts +21 -0
  287. package/dist/core/release/bundle.js +252 -0
  288. package/dist/core/release/keys.d.ts +11 -0
  289. package/dist/core/release/keys.js +60 -0
  290. package/dist/core/release/manifest.d.ts +103 -0
  291. package/dist/core/release/manifest.js +138 -0
  292. package/dist/core/release/pack.d.ts +20 -0
  293. package/dist/core/release/pack.js +97 -0
  294. package/dist/core/release/pointer.d.ts +19 -0
  295. package/dist/core/release/pointer.js +53 -0
  296. package/dist/core/release/read.d.ts +59 -0
  297. package/dist/core/release/read.js +256 -0
  298. package/dist/core/report.d.ts +31 -0
  299. package/dist/core/report.js +37 -0
  300. package/dist/core/richtext/html.d.ts +15 -0
  301. package/dist/core/richtext/html.js +81 -0
  302. package/dist/core/richtext/markdown.d.ts +19 -0
  303. package/dist/core/richtext/markdown.js +951 -0
  304. package/dist/core/richtext/schema.d.ts +98 -0
  305. package/dist/core/richtext/schema.js +275 -0
  306. package/dist/core/site/live.d.ts +56 -0
  307. package/dist/core/site/live.js +145 -0
  308. package/dist/core/site/paths.d.ts +15 -0
  309. package/dist/core/site/paths.js +64 -0
  310. package/dist/core/site/resolve.d.ts +9 -0
  311. package/dist/core/site/resolve.js +202 -0
  312. package/dist/core/site/sitemap.d.ts +11 -0
  313. package/dist/core/site/sitemap.js +24 -0
  314. package/dist/core/site-lock/site-lock.d.ts +21 -0
  315. package/dist/core/site-lock/site-lock.js +65 -0
  316. package/dist/core/site-lock/token.d.ts +7 -0
  317. package/dist/core/site-lock/token.js +24 -0
  318. package/dist/core/theme.d.ts +22 -0
  319. package/dist/core/theme.js +133 -0
  320. package/dist/core/types.d.ts +253 -0
  321. package/dist/core/types.js +1 -0
  322. package/dist/core/version.d.ts +1 -0
  323. package/dist/core/version.js +5 -0
  324. package/dist/host/activate.d.ts +53 -0
  325. package/dist/host/activate.js +162 -0
  326. package/dist/host/app.d.ts +46 -0
  327. package/dist/host/app.js +129 -0
  328. package/dist/host/bin.d.ts +5 -0
  329. package/dist/host/bin.js +8 -0
  330. package/dist/host/config.d.ts +36 -0
  331. package/dist/host/config.js +152 -0
  332. package/dist/host/dev.d.ts +10 -0
  333. package/dist/host/dev.js +293 -0
  334. package/dist/host/diff.d.ts +78 -0
  335. package/dist/host/diff.js +346 -0
  336. package/dist/host/hooks.d.ts +41 -0
  337. package/dist/host/hooks.js +49 -0
  338. package/dist/host/ipc.d.ts +123 -0
  339. package/dist/host/ipc.js +61 -0
  340. package/dist/host/preview-proxy.d.ts +24 -0
  341. package/dist/host/preview-proxy.js +154 -0
  342. package/dist/host/preview-worker.d.ts +42 -0
  343. package/dist/host/preview-worker.js +242 -0
  344. package/dist/host/primary.d.ts +38 -0
  345. package/dist/host/primary.js +357 -0
  346. package/dist/host/push.d.ts +125 -0
  347. package/dist/host/push.js +420 -0
  348. package/dist/host/serve.d.ts +16 -0
  349. package/dist/host/serve.js +150 -0
  350. package/dist/host/store.d.ts +48 -0
  351. package/dist/host/store.js +109 -0
  352. package/dist/host/worker.d.ts +67 -0
  353. package/dist/host/worker.js +310 -0
  354. package/dist/index.d.ts +47 -0
  355. package/dist/index.js +32 -0
  356. package/dist/jsx/html.d.ts +16 -0
  357. package/dist/jsx/html.js +65 -0
  358. package/dist/jsx/jsx-dev-runtime.d.ts +4 -0
  359. package/dist/jsx/jsx-dev-runtime.js +5 -0
  360. package/dist/jsx/jsx-runtime.d.ts +17 -0
  361. package/dist/jsx/jsx-runtime.js +41 -0
  362. package/dist/site.d.ts +17 -0
  363. package/dist/site.js +14 -0
  364. package/package.json +111 -3
@@ -0,0 +1,951 @@
1
+ import MarkdownIt from 'markdown-it';
2
+ import { Fragment, Mark } from 'prosemirror-model';
3
+ import { MarkdownParser, MarkdownSerializerState } from 'prosemirror-markdown';
4
+ import { z } from 'zod';
5
+ import { t } from '../messages/index.js';
6
+ import { DEFAULT_RICH_TEXT, isRichTextHref, parseRichText, richTextSchema, } from './schema.js';
7
+ const DOCUMENT_PREFIX = 'inlay:document/';
8
+ const MEDIA_PREFIX = 'inlay:media/';
9
+ const HEX64 = /^[0-9a-f]{64}$/;
10
+ const UUID = z.uuid();
11
+ /**
12
+ * Private-use stand-ins for bold and italic delimiters. Once a block is written,
13
+ * `placeDelimiters` swaps them for `*` or `_` runs that read back as the same marks.
14
+ */
15
+ const OPEN_BOLD = '\uE000';
16
+ const CLOSE_BOLD = '\uE001';
17
+ const OPEN_ITALIC = '\uE002';
18
+ const CLOSE_ITALIC = '\uE003';
19
+ const STAND_INS = /[\uE000-\uE003]/g;
20
+ const STAND_IN = {
21
+ [OPEN_BOLD]: { count: 2, open: true },
22
+ [CLOSE_BOLD]: { count: 2, open: false },
23
+ [OPEN_ITALIC]: { count: 1, open: true },
24
+ [CLOSE_ITALIC]: { count: 1, open: false },
25
+ };
26
+ const MAX_MARKERS = 512;
27
+ const MARKER_CHAR = /[ \t>\-*+#0-9.)\uE000-\uE003]/;
28
+ /**
29
+ * True if the last line of `out` is only block markers (quote, bullet, number of up to
30
+ * nine digits, heading of up to six `#`, emphasis) and spaces: nothing the editor typed.
31
+ * A plain scanner, so long runs of `#` or digits can't make it slow.
32
+ */
33
+ function atLineStart(out) {
34
+ let start = out.length;
35
+ while (start > 0 && out[start - 1] !== '\n') {
36
+ // Markers nested as deep as Markdown is read are far shorter; a longer run includes text.
37
+ if (!MARKER_CHAR.test(out[start - 1]) || out.length - start > MAX_MARKERS)
38
+ return false;
39
+ start--;
40
+ }
41
+ let i = start;
42
+ const end = out.length;
43
+ const digit = (c) => c !== undefined && c >= '0' && c <= '9';
44
+ while (i < end) {
45
+ const c = out[i];
46
+ if (c === ' ' || c === '\t' || c === '>' || c === '-' || c === '*' || c === '+' || (c >= '\uE000' && c <= '\uE003')) {
47
+ i++;
48
+ }
49
+ else if (c === '#') {
50
+ let j = i;
51
+ while (out[j] === '#')
52
+ j++;
53
+ if (j - i > 6)
54
+ return false;
55
+ i = j;
56
+ }
57
+ else if (digit(c)) {
58
+ let j = i;
59
+ while (digit(out[j]))
60
+ j++;
61
+ if (j - i > 9 || (out[j] !== '.' && out[j] !== ')'))
62
+ return false;
63
+ i = j + 1;
64
+ }
65
+ else {
66
+ return false;
67
+ }
68
+ }
69
+ return true;
70
+ }
71
+ /** Characters as numeric character references, which read back as themselves. */
72
+ const encodeChars = (s) => Array.from(s, (c) => `&#${c.codePointAt(0)};`).join('');
73
+ /** URL as a link destination: `<…>` when it has spaces or brackets, escaped so markdown-it gives it back unchanged. */
74
+ function destination(url) {
75
+ const entity = /&(?=#?[0-9A-Za-z]+;)/g;
76
+ if (/[\s()<>]/.test(url))
77
+ return '<' + url.replace(/[\\<>]/g, '\\$&').replace(entity, '\\&') + '>';
78
+ return url.replace(/\\/g, '\\\\').replace(entity, '\\&');
79
+ }
80
+ /** Text with each line break, and the whitespace around it, turned into one space. */
81
+ function oneLine(s) {
82
+ if (!/[\r\n]/.test(s))
83
+ return s;
84
+ const lines = s.split(/[\r\n]+/);
85
+ const last = lines.length - 1;
86
+ return lines
87
+ .map((line, i) => (i === 0 ? line.trimEnd() : i === last ? line.trimStart() : line.trim()))
88
+ .filter((line, i) => line !== '' || i === 0 || i === last)
89
+ .join(' ');
90
+ }
91
+ /** Count of directly preceding siblings of the same type, so adjacent lists get alternating markers. */
92
+ function sameTypeRun(node, parent, index) {
93
+ let n = 0;
94
+ for (let i = index - 1; i >= 0 && parent.child(i).type === node.type; i--)
95
+ n++;
96
+ return n;
97
+ }
98
+ const StateBase = MarkdownSerializerState;
99
+ /** How much of the end of the output `State` keeps at hand; more than `MAX_MARKERS`. */
100
+ const TAIL = 1024;
101
+ /**
102
+ * Adds the escaping prosemirror-markdown's `esc` misses: entity-like `&…;`, `<`,
103
+ * line-start markers after a hard break or a list marker, and leading whitespace.
104
+ *
105
+ * Also keeps the end of the output at hand: reading even one character of a string
106
+ * built up by appending makes V8 copy all of it, which on a long line made writing
107
+ * each piece cost as much as everything before it. So the methods that append
108
+ * (`write`, `text`, `flushClose`, `ensureNewLine`) are redone here to read only `tail`.
109
+ */
110
+ class State extends StateBase {
111
+ /** Everything written since `commitLines` last ran. */
112
+ written = '';
113
+ /** The last `TAIL` to `2 * TAIL` characters of `written`, or `null` until next needed. */
114
+ tail = '';
115
+ // @ts-expect-error -- an accessor in place of the base class's `out` field.
116
+ get out() {
117
+ return this.written;
118
+ }
119
+ set out(value) {
120
+ this.written = value;
121
+ this.tail = null;
122
+ }
123
+ /** Appends to the output. */
124
+ append(text) {
125
+ this.written += text;
126
+ if (this.tail !== null) {
127
+ this.tail += text;
128
+ if (this.tail.length > 2 * TAIL)
129
+ this.tail = this.tail.slice(-TAIL);
130
+ }
131
+ }
132
+ /** The end of the output: all of it when shorter than `TAIL`. */
133
+ end() {
134
+ if (this.tail === null)
135
+ this.tail = this.written.slice(-TAIL);
136
+ return this.tail;
137
+ }
138
+ flushClose(size = 2) {
139
+ if (!this.closed)
140
+ return;
141
+ if (!this.atBlank())
142
+ this.append('\n');
143
+ if (size > 1) {
144
+ const delimMin = this.delim.trimEnd();
145
+ for (let i = 1; i < size; i++)
146
+ this.append(delimMin + '\n');
147
+ }
148
+ this.closed = null;
149
+ }
150
+ atBlank() {
151
+ const end = this.end();
152
+ return end === '' || end.endsWith('\n');
153
+ }
154
+ ensureNewLine() {
155
+ if (!this.atBlank())
156
+ this.append('\n');
157
+ }
158
+ write(content) {
159
+ this.flushClose();
160
+ if (this.delim && this.atBlank())
161
+ this.append(this.delim);
162
+ if (content)
163
+ this.append(content);
164
+ }
165
+ text(text, escape = true) {
166
+ const lines = text.split('\n');
167
+ lines.forEach((line, i) => {
168
+ this.write();
169
+ // Escape a `!` that would turn a link into an image.
170
+ if (!escape && line.startsWith('[') && /(^|[^\\])!$/.test(this.end().slice(-2))) {
171
+ this.out = this.out.slice(0, -1) + '\\!';
172
+ }
173
+ this.append(escape ? this.esc(line, this.atBlockStart) : line);
174
+ if (i !== lines.length - 1)
175
+ this.append('\n');
176
+ });
177
+ }
178
+ /** Set to write every block one way; `null` picks the first way that reads back. */
179
+ emphasis = null;
180
+ /** The marker each bullet list was written with. */
181
+ bullets = new WeakMap();
182
+ /** The index of each block's last child that isn't a line break. */
183
+ lastContent = new WeakMap();
184
+ /** Finished lines, moved out of `out` so that rewriting a block's text stays cheap. */
185
+ done = [];
186
+ /** Moves every finished line out of `out`; what is still being written stays. */
187
+ commitLines() {
188
+ const end = this.out.lastIndexOf('\n') + 1;
189
+ if (end === 0)
190
+ return;
191
+ this.done.push(this.out.slice(0, end));
192
+ this.out = this.out.slice(end);
193
+ }
194
+ /** Everything written. */
195
+ result() {
196
+ return this.done.join('') + this.out;
197
+ }
198
+ esc(str, startOfLine = false) {
199
+ const lineStart = atLineStart(this.end());
200
+ let lead = '';
201
+ let rest = str;
202
+ if (lineStart) {
203
+ lead = /^\s*/.exec(str)?.[0] ?? '';
204
+ rest = str.slice(lead.length);
205
+ }
206
+ let out = super.esc(rest, startOfLine || (lineStart && lead === ''));
207
+ if (lineStart && lead === '') {
208
+ out = out
209
+ .replace(/^(\d{1,9})([.)])(?=[ \t]|$)/, '$1\\$2')
210
+ .replace(/^\+(?=[ \t]|$)/, '\\+')
211
+ .replace(/^=/, '\\=');
212
+ }
213
+ // A bare `_` is safe only between two letters or digits; next to anything else it could open or close.
214
+ out = out.replace(/\\[\s\S]|_/g, (m, at, all) => m === '_' && !(/[A-Za-z0-9]/.test(all[at - 1] ?? '') && /[A-Za-z0-9]/.test(all[at + 1] ?? '')) ? '\\_' : m);
215
+ out = out.replace(/<|&(?=#?[0-9A-Za-z]+;)/g, '\\$&').replace(STAND_INS, encodeChars);
216
+ return encodeChars(lead) + out;
217
+ }
218
+ }
219
+ const isEmphasis = (mark) => mark.type.name === 'bold' || mark.type.name === 'italic';
220
+ /** The block with bold and italic taken off, so text that ends up side by side is escaped as one. */
221
+ function withoutEmphasis(node) {
222
+ const children = [];
223
+ node.forEach((child) => children.push(child.mark(child.marks.filter((m) => !isEmphasis(m)))));
224
+ return node.type.create(node.attrs, Fragment.fromArray(children));
225
+ }
226
+ /**
227
+ * The block with bold and italic kept on a line break only when the nearest visible
228
+ * content after it has them too, and the same link; and on spaces only as the same marks as the content
229
+ * before, all of which go on. Elsewhere they can't be seen, and prosemirror-markdown
230
+ * would write a delimiter where it can't open or close.
231
+ */
232
+ function tidyInvisible(node) {
233
+ // Spaces at the end of bold or italic text are looked at on their own.
234
+ const children = [];
235
+ node.forEach((child) => {
236
+ const text = child.text ?? '';
237
+ if (!child.isText || !child.marks.some(isEmphasis))
238
+ return void children.push(child);
239
+ // prosemirror-markdown looks for trailing spaces in the text where bold or italic ends
240
+ // with a regex that is slow on long runs of spaces, so after one the last word is split off.
241
+ const core = text.trimEnd();
242
+ let word = core.length;
243
+ if (/\s{64,}/.test(core))
244
+ while (word > 0 && !/\s/.test(core[word - 1]))
245
+ word--;
246
+ else
247
+ word = 0;
248
+ for (const part of [core.slice(0, word), core.slice(word), text.slice(core.length)]) {
249
+ if (part)
250
+ children.push(richTextSchema.text(part, child.marks));
251
+ }
252
+ });
253
+ const blank = (child) => child?.isText === true && !/\S/.test(child.text ?? '');
254
+ const invisible = children.map((child) => child.type.name === 'hardBreak' || blank(child));
255
+ // For bold and italic: whether the mark runs unbroken from each child to the next visible one.
256
+ const unbroken = new Map();
257
+ for (const name of ['bold', 'italic']) {
258
+ const runs = new Array(children.length).fill(false);
259
+ for (let i = children.length - 1; i >= 0; i--) {
260
+ const has = children[i].marks.some((m) => m.type.name === name);
261
+ runs[i] = invisible[i] ? has && (runs[i + 1] ?? false) : has;
262
+ }
263
+ unbroken.set(name, runs);
264
+ }
265
+ const others = (marks) => marks.filter((m) => !isEmphasis(m));
266
+ // Whether the link stays the same from each child to the next visible one.
267
+ const sameLink = new Array(children.length).fill(true);
268
+ for (let i = children.length - 2; i >= 0; i--) {
269
+ if (invisible[i]) {
270
+ sameLink[i] = Mark.sameSet(others(children[i].marks), others(children[i + 1].marks)) && sameLink[i + 1];
271
+ }
272
+ }
273
+ const tidied = [];
274
+ children.forEach((child, i) => {
275
+ const prev = tidied[i - 1];
276
+ let marks = child.marks;
277
+ if (invisible[i] && marks.some(isEmphasis)) {
278
+ const continues = (m) => sameLink[i] === true && unbroken.get(m.type.name)?.[i] === true;
279
+ if (!blank(child)) {
280
+ marks = marks.filter((m) => !isEmphasis(m) || continues(m));
281
+ }
282
+ else {
283
+ // Spaces take exactly the marks before them, so nothing opens or closes at them,
284
+ // or else no bold or italic at all.
285
+ const same = prev !== undefined &&
286
+ Mark.sameSet(others(prev.marks), others(marks)) &&
287
+ prev.marks.every((m) => !isEmphasis(m) || continues(m));
288
+ marks = same ? prev.marks : others(marks);
289
+ }
290
+ }
291
+ tidied.push(marks === child.marks ? child : child.mark(marks));
292
+ });
293
+ // Built without joining neighbors with the same marks, to keep the split above.
294
+ const size = tidied.reduce((sum, child) => sum + child.nodeSize, 0);
295
+ return node.type.create(node.attrs, new Fragment(tidied, size));
296
+ }
297
+ /** How the emphasis rules see the character a piece starts or ends with next to a delimiter run. */
298
+ function charKind(piece) {
299
+ if (piece === undefined)
300
+ return 'space';
301
+ if ('delim' in piece)
302
+ return 'punct';
303
+ const { isWhiteSpace, isMdAsciiPunct, isPunctCharCode } = tokenizer.utils;
304
+ const code = piece.text.codePointAt(0) ?? 0x20;
305
+ if (isWhiteSpace(code))
306
+ return 'space';
307
+ return isMdAsciiPunct(code) || isPunctCharCode(code) ? 'punct' : 'word';
308
+ }
309
+ /**
310
+ * Swaps the stand-ins in one written block for delimiter runs that CommonMark reads
311
+ * back as the same marks. A run that opens right where another closes uses the other
312
+ * character (`**a*b***_c_`), so the two don't merge into one run; so does one opening
313
+ * inside another (`**a _b_ c**`), so it can't be taken for that one's end. A letter next to a
314
+ * run that couldn't open or close beside it (`said*"hi"*`, or any `_` inside a word)
315
+ * is written as a character reference (`sai&#100;*"hi"*`): it reads back as the same
316
+ * letter but counts as punctuation. `strict` does that next to every run.
317
+ */
318
+ function placeDelimiters(written, strict) {
319
+ const pieces = [];
320
+ const open = [];
321
+ for (const ch of written) {
322
+ const standIn = STAND_IN[ch];
323
+ if (standIn === undefined) {
324
+ pieces.push({ text: ch });
325
+ continue;
326
+ }
327
+ let delim;
328
+ if (standIn.open) {
329
+ const prev = pieces[pieces.length - 1];
330
+ const run = prev !== undefined && 'delim' in prev ? prev : undefined;
331
+ if (run?.open)
332
+ delim = run.delim;
333
+ else
334
+ delim = (run?.delim ?? open[open.length - 1]) === '*' ? '_' : '*';
335
+ open.push(delim);
336
+ }
337
+ else {
338
+ delim = open.pop() ?? '*';
339
+ }
340
+ pieces.push({ delim, ...standIn });
341
+ }
342
+ const encode = new Set();
343
+ for (let i = 0; i < pieces.length;) {
344
+ const piece = pieces[i];
345
+ if (piece === undefined || !('delim' in piece)) {
346
+ i++;
347
+ continue;
348
+ }
349
+ let j = i + 1;
350
+ for (let next = pieces[j]; next !== undefined && 'delim' in next && next.delim === piece.delim; next = pieces[++j])
351
+ ;
352
+ const before = charKind(pieces[i - 1]);
353
+ const after = charKind(pieces[j]);
354
+ const underscore = piece.delim === '_';
355
+ if (piece.open) {
356
+ if (before === 'word' && (strict || underscore || after === 'punct'))
357
+ encode.add(i - 1);
358
+ }
359
+ else if (after === 'word' && (strict || underscore || before === 'punct')) {
360
+ encode.add(j);
361
+ }
362
+ i = j;
363
+ }
364
+ // An `_` left unescaped inside a word could open or close once its neighbor is a reference.
365
+ const textAt = (i) => {
366
+ const piece = pieces[i];
367
+ return piece !== undefined && 'text' in piece ? piece.text : undefined;
368
+ };
369
+ const escape = new Set();
370
+ for (const i of encode) {
371
+ if (textAt(i - 1) === '_' && textAt(i - 2) !== '\\')
372
+ escape.add(i - 1);
373
+ if (textAt(i + 1) === '_')
374
+ escape.add(i + 1);
375
+ }
376
+ return pieces
377
+ .map((piece, i) => {
378
+ if ('delim' in piece)
379
+ return piece.delim.repeat(piece.count);
380
+ if (encode.has(i))
381
+ return encodeChars(piece.text);
382
+ return escape.has(i) ? '\\_' : piece.text;
383
+ })
384
+ .join('');
385
+ }
386
+ const SERIALIZER_OPTIONS = { tightLists: true, hardBreakNodeName: 'hardBreak' };
387
+ /**
388
+ * The block's content as one entry per character or inline node. `all` keeps every
389
+ * mark, `text` all but bold and italic, `emphasis` only bold and italic and only on
390
+ * what can be seen. Marks on whitespace and line breaks, which the writer moves out of
391
+ * links and emphasis, and trailing line breaks, which it drops, are left out.
392
+ */
393
+ function signature(node, kind) {
394
+ const out = [];
395
+ let end = node.childCount;
396
+ while (end > 0 && node.child(end - 1).type.name === 'hardBreak')
397
+ end--;
398
+ const marksOf = (marks) => JSON.stringify(marks.filter((m) => (kind === 'all' ? true : kind === 'text' ? !isEmphasis(m) : isEmphasis(m))).map((m) => m.toJSON()));
399
+ node.forEach((child, _, i) => {
400
+ if (i >= end)
401
+ return;
402
+ if (child.isText) {
403
+ for (const c of child.text ?? '') {
404
+ const visible = /\S/.test(c);
405
+ if (visible || kind !== 'emphasis')
406
+ out.push(c + (visible ? marksOf(child.marks) : ''));
407
+ }
408
+ }
409
+ else if (child.type.name === 'hardBreak') {
410
+ if (kind !== 'emphasis')
411
+ out.push('hardBreak');
412
+ }
413
+ else {
414
+ out.push(child.type.name + JSON.stringify(child.attrs) + marksOf(child.marks));
415
+ }
416
+ });
417
+ return JSON.stringify(out);
418
+ }
419
+ /** The block's content written with `emphasis` and read back, or `null` if it isn't one paragraph. */
420
+ function readBack(node, emphasis) {
421
+ const para = richTextSchema.nodes.paragraph.create(null, node.content);
422
+ const state = new State(nodes, marks, SERIALIZER_OPTIONS);
423
+ state.emphasis = emphasis;
424
+ state.renderContent(richTextSchema.nodes.doc.create(null, para));
425
+ try {
426
+ const back = parser.parse(state.result());
427
+ return back.childCount === 1 && back.firstChild?.type === para.type ? back.firstChild : null;
428
+ }
429
+ catch {
430
+ return null;
431
+ }
432
+ }
433
+ /** Above this many bold and italic runs, a block that doesn't read back loses all of them. */
434
+ const MAX_RUNS_TO_TRY = 32;
435
+ /**
436
+ * The block with only the bold and italic runs that read back the same, added one by
437
+ * one in order, or `null` if it has too many runs to try.
438
+ */
439
+ function keepWhatReadsBack(node, fits) {
440
+ const children = [];
441
+ node.forEach((child) => children.push(child));
442
+ const runs = [];
443
+ for (const name of ['bold', 'italic']) {
444
+ let from = -1;
445
+ children.forEach((child, i) => {
446
+ const mark = child.marks.find((m) => m.type.name === name);
447
+ if (mark && from < 0)
448
+ from = i;
449
+ const next = children[i + 1];
450
+ if (mark && from >= 0 && !next?.marks.some((m) => m.type.name === name)) {
451
+ runs.push({ mark, from, to: i });
452
+ from = -1;
453
+ }
454
+ });
455
+ }
456
+ if (runs.length > MAX_RUNS_TO_TRY)
457
+ return null;
458
+ runs.sort((a, b) => a.from - b.from);
459
+ let marksAt = children.map((child) => child.marks.filter((m) => !isEmphasis(m)));
460
+ const build = () => node.type.create(node.attrs, Fragment.fromArray(children.map((child, i) => child.mark(marksAt[i]))));
461
+ for (const run of runs) {
462
+ const before = marksAt;
463
+ marksAt = marksAt.map((set, i) => (i >= run.from && i <= run.to ? run.mark.addToSet(set) : set));
464
+ const candidate = build();
465
+ if (!fits(readBack(candidate, 'strict'), candidate))
466
+ marksAt = before;
467
+ }
468
+ return build();
469
+ }
470
+ /**
471
+ * How to write the block's bold and italic, and the block to write. The first way that
472
+ * reads back the same; failing that (because something else in the block doesn't), the
473
+ * first way that adds no text and keeps the bold and italic on what can be seen. Failing
474
+ * both, only the runs that read back are kept, and the rest are left out rather than
475
+ * written as stray `*` or `_` text.
476
+ */
477
+ function chooseWriting(node) {
478
+ let marked = false;
479
+ node.forEach((child) => {
480
+ if (child.marks.some(isEmphasis))
481
+ marked = true;
482
+ });
483
+ if (!marked)
484
+ return { emphasis: 'minimal', node };
485
+ const tries = ['minimal', 'strict'].map((emphasis) => ({ emphasis, back: readBack(node, emphasis) }));
486
+ const want = signature(node, 'all');
487
+ for (const { emphasis, back } of tries)
488
+ if (back && signature(back, 'all') === want)
489
+ return { emphasis, node };
490
+ const plain = readBack(node, 'none');
491
+ const text = plain && signature(plain, 'text');
492
+ const fits = (back, target) => back !== null && signature(back, 'text') === text && signature(back, 'emphasis') === signature(target, 'emphasis');
493
+ for (const { emphasis, back } of tries)
494
+ if (fits(back, node))
495
+ return { emphasis, node };
496
+ const kept = text === null ? null : keepWhatReadsBack(node, fits);
497
+ return kept ? { emphasis: 'strict', node: kept } : { emphasis: 'none', node };
498
+ }
499
+ /** Writes a paragraph's or heading's content. Trailing whitespace is encoded, or it would be trimmed. */
500
+ function renderTextblock(state, node, fromBlockStart) {
501
+ const writing = state.emphasis ? { emphasis: state.emphasis, node } : chooseWriting(node);
502
+ state.commitLines();
503
+ const start = state.out.length;
504
+ state.renderInline(writing.emphasis === 'none' ? withoutEmphasis(writing.node) : tidyInvisible(writing.node), fromBlockStart);
505
+ const written = placeDelimiters(state.out.slice(start), writing.emphasis === 'strict');
506
+ const kept = written.trimEnd();
507
+ state.out = state.out.slice(0, start) + kept + encodeChars(written.slice(kept.length));
508
+ }
509
+ /** True for a block with nothing but line breaks, which are dropped at the end of a block. */
510
+ function writesNothing(node) {
511
+ let nothing = node !== null;
512
+ node?.forEach((child) => {
513
+ if (child.type.name !== 'hardBreak')
514
+ nothing = false;
515
+ });
516
+ return nothing;
517
+ }
518
+ /**
519
+ * A list that can't interrupt a paragraph (a numbered list not starting at 1, or one
520
+ * whose first item is empty) would read back as part of the text above it in a tight
521
+ * list, so it gets a blank line first.
522
+ */
523
+ function separateList(state, node) {
524
+ const first = node.firstChild;
525
+ let empty = first !== null;
526
+ first?.forEach((child) => {
527
+ if (!writesNothing(child))
528
+ empty = false;
529
+ });
530
+ const start = node.type.name === 'orderedList' ? Number(node.attrs.start ?? 1) : 1;
531
+ if ((empty || start !== 1) && state.closed && state.closed.type !== node.type)
532
+ state.flushClose(2);
533
+ }
534
+ const nodes = {
535
+ blockquote(state, node) {
536
+ state.wrapBlock('> ', null, node, () => state.renderContent(node));
537
+ },
538
+ heading(state, node) {
539
+ state.write('#'.repeat(Number(node.attrs.level)) + ' ');
540
+ renderTextblock(state, node, false);
541
+ // A trailing run of `#` would be read as the heading's closing sequence.
542
+ const end = state.end();
543
+ let run = end.length;
544
+ while (run > 0 && end[run - 1] === '#')
545
+ run--;
546
+ if (run === 0 && end.length < state.out.length) {
547
+ // A run of `#` longer than the tail: look at the whole output.
548
+ const out = state.out;
549
+ run = out.length;
550
+ while (run > 0 && out[run - 1] === '#')
551
+ run--;
552
+ if (run > 0 && out[run - 1] !== '\\')
553
+ state.out = out.slice(0, run) + '\\' + out.slice(run);
554
+ }
555
+ else if (run > 0 && run < end.length && end[run - 1] !== '\\') {
556
+ const at = state.out.length - (end.length - run);
557
+ state.out = state.out.slice(0, at) + '\\' + state.out.slice(at);
558
+ }
559
+ state.closeBlock(node);
560
+ },
561
+ bulletList(state, node, parent, index) {
562
+ // A list takes the other marker from a list right before it, which it would otherwise
563
+ // join, and from one it starts on the same line as, since `- - -` is a rule.
564
+ const out = state.end();
565
+ const marker = out[out.length - 2];
566
+ const lead = out[out.length - 3];
567
+ const onMarker = !state.closed && out.endsWith(' ') && (marker === '-' || marker === '*') && (lead === undefined || lead === '\n' || lead === ' ' || lead === '\t');
568
+ const before = index > 0 ? state.bullets.get(parent.child(index - 1)) : undefined;
569
+ const outer = before ?? (onMarker ? marker : undefined);
570
+ const bullet = outer === '-' ? '* ' : '- ';
571
+ state.bullets.set(node, bullet.charAt(0));
572
+ separateList(state, node);
573
+ state.renderList(node, ' ', () => bullet);
574
+ },
575
+ orderedList(state, node, parent, index) {
576
+ const start = Number(node.attrs.start ?? 1);
577
+ const sep = sameTypeRun(node, parent, index) % 2 ? ') ' : '. ';
578
+ // Numbers are padded after, not before, so every item's text starts in the same column
579
+ // even when the list starts on its parent item's first line.
580
+ const width = String(start + node.childCount - 1).length;
581
+ separateList(state, node);
582
+ state.renderList(node, ' '.repeat(width + 2), (i) => (String(start + i) + sep).padEnd(width + 2, ' '));
583
+ },
584
+ listItem(state, node) {
585
+ // `- > x` reads back as an empty first paragraph followed by the quote; writing the
586
+ // empty paragraph would leave a blank line that ends the item.
587
+ const skipFirst = node.childCount > 1 && writesNothing(node.firstChild);
588
+ node.forEach((child, _, i) => {
589
+ if (!(skipFirst && i === 0))
590
+ state.render(child, node, i);
591
+ });
592
+ },
593
+ paragraph(state, node) {
594
+ renderTextblock(state, node, true);
595
+ state.closeBlock(node);
596
+ },
597
+ image(state, node) {
598
+ const alt = typeof node.attrs.alt === 'string' ? oneLine(node.attrs.alt) : '';
599
+ state.write('![');
600
+ state.append(state.esc(alt));
601
+ state.append(`](${MEDIA_PREFIX}${String(node.attrs.media)})`);
602
+ },
603
+ hardBreak(state, node, parent, index) {
604
+ // Only breaks with something after them are written; a trailing one would be text.
605
+ let last = state.lastContent.get(parent);
606
+ if (last === undefined) {
607
+ last = -1;
608
+ parent.forEach((child, _, i) => {
609
+ if (child.type !== node.type)
610
+ last = i;
611
+ });
612
+ state.lastContent.set(parent, last);
613
+ }
614
+ if (index < last)
615
+ state.write('\\\n');
616
+ },
617
+ text(state, node, parent, index) {
618
+ // A `!` right before a link would make it an image. prosemirror-markdown checks for
619
+ // this, but rewrites the whole output each time and misreads `\\!`, so it is escaped here.
620
+ const text = node.text ?? '';
621
+ const linkOf = (n) => n.marks.find((m) => m.type.name === 'link');
622
+ const next = index + 1 < parent.childCount ? parent.child(index + 1) : null;
623
+ const link = next && linkOf(next);
624
+ if (text.endsWith('!') && link && !link.eq(linkOf(node) ?? link.type.create())) {
625
+ state.text(text.slice(0, -1));
626
+ state.append('\\!');
627
+ }
628
+ else {
629
+ state.text(text);
630
+ }
631
+ },
632
+ };
633
+ const marks = {
634
+ link: {
635
+ open: '[',
636
+ close: (_state, mark) => {
637
+ const href = typeof mark.attrs.document === 'string' ? DOCUMENT_PREFIX + mark.attrs.document : String(mark.attrs.href);
638
+ return `](${destination(href)})`;
639
+ },
640
+ mixable: true,
641
+ },
642
+ bold: { open: OPEN_BOLD, close: CLOSE_BOLD, mixable: true, expelEnclosingWhitespace: true },
643
+ italic: { open: OPEN_ITALIC, close: CLOSE_ITALIC, mixable: true, expelEnclosingWhitespace: true },
644
+ };
645
+ /** The doc as CommonMark: tight lists, `- ` bullets, `inlay:` URIs for internal links and images. */
646
+ export function richTextToMarkdown(doc) {
647
+ const node = richTextSchema.nodeFromJSON(doc);
648
+ const state = new State(nodes, marks, SERIALIZER_OPTIONS);
649
+ state.renderContent(node);
650
+ return state.result();
651
+ }
652
+ // ---------------------------------------------------------------------------
653
+ // Markdown → rich text
654
+ const tokenizer = new MarkdownIt('commonmark', { html: false, linkify: false, typographer: false });
655
+ tokenizer.validateLink = () => true;
656
+ tokenizer.normalizeLink = (url) => url;
657
+ tokenizer.normalizeLinkText = (url) => url;
658
+ /**
659
+ * Reads the syntax that CommonMark keeps as plain text but writers mean as formatting rich text can't hold:
660
+ * HTML, tables and strikethrough. Used only to refuse it, so it isn't silently stored as literal characters.
661
+ */
662
+ const detector = new MarkdownIt('commonmark', { html: true, linkify: false, typographer: false }).enable([
663
+ 'table',
664
+ 'strikethrough',
665
+ ]);
666
+ detector.validateLink = () => true;
667
+ /** markdown-it stops reading blocks nested this deep and drops the rest of the input. */
668
+ const MAX_NESTING = tokenizer.options.maxNesting ?? 20;
669
+ /** An env whose `references` note each label added and, later, each one looked up. */
670
+ function trackingEnv() {
671
+ const env = { definitions: [], used: new Set(), added: null, inline: false };
672
+ env.references = new Proxy({}, {
673
+ set(target, key, value) {
674
+ if (typeof key === 'string')
675
+ env.added = key;
676
+ return Reflect.set(target, key, value);
677
+ },
678
+ get(target, key, receiver) {
679
+ if (env.inline && typeof key === 'string' && Object.hasOwn(target, key))
680
+ env.used?.add(key);
681
+ return Reflect.get(target, key, receiver);
682
+ },
683
+ });
684
+ return env;
685
+ }
686
+ const referenceRule = tokenizer.block.ruler.getRules('').find((rule) => rule.name === 'reference');
687
+ if (referenceRule) {
688
+ tokenizer.block.ruler.at('reference', (state, startLine, endLine, silent) => {
689
+ const env = state.env;
690
+ if (!env.definitions)
691
+ return referenceRule(state, startLine, endLine, silent);
692
+ env.added = null;
693
+ if (!referenceRule(state, startLine, endLine, silent))
694
+ return false;
695
+ if (!silent) {
696
+ const from = (state.bMarks[startLine] ?? 0) + (state.tShift[startLine] ?? 0);
697
+ const text = state.src.slice(from, state.eMarks[startLine]).trim();
698
+ env.definitions.push({ line: startLine + 1, text, label: env.added });
699
+ }
700
+ return true;
701
+ });
702
+ }
703
+ else {
704
+ // Without a way to see definitions, read them as text rather than lose them.
705
+ tokenizer.block.ruler.disable('reference');
706
+ }
707
+ // Once the blocks are read, lookups in `references` come from links and images.
708
+ tokenizer.core.ruler.after('block', 'inlay_used_references', (state) => {
709
+ const env = state.env;
710
+ if (env.definitions)
711
+ env.inline = true;
712
+ });
713
+ /** An image's alt as plain text, the way a browser shows it. */
714
+ function altText(children) {
715
+ return (children ?? [])
716
+ .map((c) => {
717
+ if (c.type === 'text' || c.type === 'text_special' || c.type === 'code_inline')
718
+ return c.content;
719
+ if (c.type === 'softbreak' || c.type === 'hardbreak')
720
+ return ' ';
721
+ if (c.type === 'image')
722
+ return altText(c.children);
723
+ return '';
724
+ })
725
+ .join('');
726
+ }
727
+ const parser = new MarkdownParser(richTextSchema, tokenizer, {
728
+ blockquote: { block: 'blockquote' },
729
+ paragraph: { block: 'paragraph' },
730
+ list_item: { block: 'listItem' },
731
+ bullet_list: { block: 'bulletList' },
732
+ ordered_list: { block: 'orderedList', getAttrs: (tok) => ({ start: Number(tok.attrGet('start') ?? 1) }) },
733
+ heading: { block: 'heading', getAttrs: (tok) => ({ level: Number(tok.tag.slice(1)) }) },
734
+ image: {
735
+ node: 'image',
736
+ getAttrs: (tok) => ({
737
+ media: (tok.attrGet('src') ?? '').slice(MEDIA_PREFIX.length),
738
+ alt: altText(tok.children) || null,
739
+ }),
740
+ },
741
+ hardbreak: { node: 'hardBreak' },
742
+ em: { mark: 'italic' },
743
+ strong: { mark: 'bold' },
744
+ link: {
745
+ mark: 'link',
746
+ getAttrs: (tok) => {
747
+ const href = tok.attrGet('href') ?? '';
748
+ return href.startsWith(DOCUMENT_PREFIX) ? { document: href.slice(DOCUMENT_PREFIX.length) } : { href };
749
+ },
750
+ },
751
+ });
752
+ const FEATURE_MESSAGE = {
753
+ heading: 'richtext.feature.heading',
754
+ bold: 'richtext.feature.bold',
755
+ italic: 'richtext.feature.italic',
756
+ link: 'richtext.feature.link',
757
+ bulletList: 'richtext.feature.bulletList',
758
+ orderedList: 'richtext.feature.orderedList',
759
+ blockquote: 'richtext.feature.blockquote',
760
+ image: 'richtext.feature.image',
761
+ hardBreak: 'richtext.feature.hardBreak',
762
+ code: 'richtext.feature.code',
763
+ codeBlock: 'richtext.feature.codeBlock',
764
+ rule: 'richtext.feature.rule',
765
+ html: 'richtext.feature.html',
766
+ table: 'richtext.feature.table',
767
+ strike: 'richtext.feature.strike',
768
+ other: 'richtext.feature.other',
769
+ };
770
+ /** Token types that map to a feature a field may switch off. */
771
+ const TOKEN_FEATURE = {
772
+ bullet_list_open: 'bulletList',
773
+ ordered_list_open: 'orderedList',
774
+ blockquote_open: 'blockquote',
775
+ strong_open: 'bold',
776
+ em_open: 'italic',
777
+ link_open: 'link',
778
+ image: 'image',
779
+ hardbreak: 'hardBreak',
780
+ };
781
+ const TOKEN_UNSUPPORTED = {
782
+ code_inline: 'code',
783
+ code_block: 'codeBlock',
784
+ fence: 'codeBlock',
785
+ hr: 'rule',
786
+ };
787
+ /** Token types the parser turns into rich text without any check. */
788
+ const PLAIN_TOKENS = new Set([
789
+ 'paragraph_open',
790
+ 'paragraph_close',
791
+ 'list_item_open',
792
+ 'list_item_close',
793
+ 'bullet_list_close',
794
+ 'ordered_list_close',
795
+ 'blockquote_close',
796
+ 'heading_close',
797
+ 'strong_close',
798
+ 'em_close',
799
+ 'link_close',
800
+ 'inline',
801
+ 'text',
802
+ 'text_special',
803
+ 'softbreak',
804
+ ]);
805
+ /** Token types of `detector` for syntax that would otherwise be kept as literal text. */
806
+ const TOKEN_LITERAL = {
807
+ html_block: 'html',
808
+ html_inline: 'html',
809
+ table_open: 'table',
810
+ s_open: 'strike',
811
+ };
812
+ /** One problem per line and kind for HTML, tables and strikethrough in `markdown`. */
813
+ function literalSyntaxProblems(markdown) {
814
+ const problems = [];
815
+ const seen = new Set();
816
+ const add = (name, line) => {
817
+ if (name === undefined || seen.has(`${line}:${name}`))
818
+ return;
819
+ seen.add(`${line}:${name}`);
820
+ problems.push({
821
+ code: 'unsupported',
822
+ line,
823
+ message: t('richtext.unsupported', { line, feature: t(FEATURE_MESSAGE[name]) }),
824
+ });
825
+ };
826
+ let line = 1;
827
+ for (const tok of detector.parse(markdown, {})) {
828
+ if (tok.map)
829
+ line = tok.map[0] + 1;
830
+ add(TOKEN_LITERAL[tok.type], line);
831
+ let inline = line;
832
+ for (const child of tok.children ?? []) {
833
+ add(TOKEN_LITERAL[child.type], inline);
834
+ if (child.type === 'softbreak' || child.type === 'hardbreak')
835
+ inline++;
836
+ }
837
+ }
838
+ return problems;
839
+ }
840
+ const isSafeHref = (href) => href.startsWith(DOCUMENT_PREFIX) ? UUID.safeParse(href.slice(DOCUMENT_PREFIX.length)).success : isRichTextHref(href);
841
+ const isLibraryImage = (src) => src.startsWith(MEDIA_PREFIX) && HEX64.test(src.slice(MEDIA_PREFIX.length));
842
+ /** Every problem in the token stream and `env`, in line order, before anything is built. */
843
+ function findProblems(tokens, opts, env) {
844
+ const problems = [];
845
+ const feature = (name) => t(FEATURE_MESSAGE[name]);
846
+ const add = (code, line, id, params) => {
847
+ problems.push({ code, line, message: t(id, { line, ...params }) });
848
+ };
849
+ const allowed = (f) => opts.features.includes(f);
850
+ const check = (tok, line, inHeading) => {
851
+ const unsupported = TOKEN_UNSUPPORTED[tok.type];
852
+ if (unsupported)
853
+ return add('unsupported', line, 'richtext.unsupported', { feature: feature(unsupported) });
854
+ if (tok.type === 'heading_open') {
855
+ const level = Number(tok.tag.slice(1));
856
+ if (!allowed('heading') || opts.headings.length === 0) {
857
+ return add('not_allowed', line, 'richtext.notAllowed', { feature: feature('heading') });
858
+ }
859
+ if (!opts.headings.includes(level)) {
860
+ return add('heading_level', line, 'richtext.headingLevel', { level, levels: opts.headings.join(', ') });
861
+ }
862
+ return;
863
+ }
864
+ const name = TOKEN_FEATURE[tok.type];
865
+ if (name === undefined) {
866
+ if (!PLAIN_TOKENS.has(tok.type))
867
+ add('unsupported', line, 'richtext.unsupported', { feature: feature('other') });
868
+ return;
869
+ }
870
+ if (inHeading && (name === 'image' || name === 'hardBreak')) {
871
+ return add('unsupported', line, 'richtext.headingContent', { feature: feature(name) });
872
+ }
873
+ if (!allowed(name))
874
+ return add('not_allowed', line, 'richtext.notAllowed', { feature: feature(name) });
875
+ if (name === 'link' || name === 'image') {
876
+ if (tok.attrGet('title'))
877
+ add('unsupported', line, 'richtext.title', { feature: feature(name) });
878
+ }
879
+ if (name === 'link') {
880
+ const href = tok.attrGet('href') ?? '';
881
+ if (!isSafeHref(href))
882
+ add('link_url', line, 'richtext.linkUrl', { href });
883
+ }
884
+ if (name === 'image') {
885
+ const src = tok.attrGet('src') ?? '';
886
+ if (!isLibraryImage(src))
887
+ add('image_source', line, 'richtext.imageSource', { src });
888
+ }
889
+ };
890
+ /** Walks inline tokens; line breaks move the line on, including those inside an image's alt. */
891
+ const walkInline = (children, line, inHeading, inAlt) => {
892
+ for (const child of children) {
893
+ if (!inAlt)
894
+ check(child, line, inHeading);
895
+ if (child.type === 'softbreak' || child.type === 'hardbreak')
896
+ line++;
897
+ if (child.type === 'image' && child.children)
898
+ line = walkInline(child.children, line, inHeading, true);
899
+ }
900
+ return line;
901
+ };
902
+ let line = 1;
903
+ let inHeading = false;
904
+ for (const tok of tokens) {
905
+ if (tok.map)
906
+ line = tok.map[0] + 1;
907
+ if (tok.type === 'inline') {
908
+ walkInline(tok.children ?? [], line, inHeading, false);
909
+ continue;
910
+ }
911
+ if (tok.type === 'heading_open')
912
+ inHeading = true;
913
+ if (tok.type === 'heading_close')
914
+ inHeading = false;
915
+ if ((tok.type === 'blockquote_open' || tok.type === 'list_item_open') && tok.level + 1 >= MAX_NESTING) {
916
+ add('unsupported', line, 'richtext.tooDeep', {});
917
+ }
918
+ check(tok, line, false);
919
+ }
920
+ // A definition no link uses would vanish; one that is used ends up in its links.
921
+ for (const def of env.definitions ?? []) {
922
+ if (def.label === null || !env.used?.has(def.label)) {
923
+ add('unsupported', def.line, 'richtext.unusedDefinition', { text: def.text });
924
+ }
925
+ }
926
+ return problems.sort((a, b) => a.line - b.line);
927
+ }
928
+ /**
929
+ * Reads CommonMark into a normalized rich text doc allowed by `opts`. Anything the
930
+ * format or the field can't hold is reported as a line-numbered problem. Never throws.
931
+ */
932
+ export function markdownToRichText(markdown, opts) {
933
+ const options = { ...DEFAULT_RICH_TEXT, ...opts };
934
+ const unreadable = () => ({
935
+ ok: false,
936
+ problems: [{ code: 'unsupported', line: 1, message: t('richtext.unreadable', { line: 1 }) }],
937
+ });
938
+ try {
939
+ const env = trackingEnv();
940
+ const tokens = tokenizer.parse(markdown, env);
941
+ const problems = [...findProblems(tokens, options, env), ...literalSyntaxProblems(markdown)];
942
+ if (problems.length > 0)
943
+ return { ok: false, problems: problems.sort((a, b) => a.line - b.line) };
944
+ const node = parser.parse(markdown);
945
+ const parsed = parseRichText(node.toJSON(), options);
946
+ return parsed.ok ? parsed : unreadable();
947
+ }
948
+ catch {
949
+ return unreadable();
950
+ }
951
+ }