@aiquants/markdown-explorer 0.19.0 → 0.21.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 (32) hide show
  1. package/CHANGELOG.md +65 -1
  2. package/README.md +18 -9
  3. package/dist/EditSurface-Bwl4S1vQ.cjs +7 -0
  4. package/dist/EditSurface-rKoy_ndP.js +880 -0
  5. package/dist/{ExplorerSplit-LiI3IUZn.js → ExplorerSplit-3WMRDA7G.js} +1 -1
  6. package/dist/{ExplorerSplit-BDkBN8A0.cjs → ExplorerSplit-CdqEKz-I.cjs} +1 -1
  7. package/dist/{MultiLayout-BOaQK8fp.cjs → MultiLayout-BEg1X8Jx.cjs} +1 -1
  8. package/dist/{MultiLayout-KWacTPP8.js → MultiLayout-Gf1xT-Le.js} +2 -2
  9. package/dist/{NativeScrollBar-zzpty31a.js → NativeScrollBar-0cpp2OIu.js} +1 -1
  10. package/dist/{NativeScrollBar-BPgV3kp-.cjs → NativeScrollBar-idIQsvCv.cjs} +1 -1
  11. package/dist/{TreeLayout-S5TMf8_A.cjs → TreeLayout-DJY_WqzP.cjs} +1 -1
  12. package/dist/{TreeLayout-C8IP4cjY.js → TreeLayout-DzZCgMTt.js} +2 -2
  13. package/dist/core/labels.d.cts +26 -0
  14. package/dist/core/labels.d.ts +26 -0
  15. package/dist/{index-Dz01kBab.js → index-CJgHGeZs.js} +1323 -1238
  16. package/dist/index-bMaSoQTe.cjs +13 -0
  17. package/dist/index.cjs +1 -1
  18. package/dist/index.js +1 -1
  19. package/dist/{merge-ClVgYrkS.js → merge-BOcofJN5.js} +1 -1
  20. package/dist/{merge-B7Lkcdz0.cjs → merge-BVk6pvO_.cjs} +1 -1
  21. package/dist/sanitizePolicy-BWQtWhsL.js +98 -0
  22. package/dist/sanitizePolicy-gEXeavb-.cjs +1 -0
  23. package/dist/sanitizeWorker.cjs +1 -1
  24. package/dist/sanitizeWorker.js +1 -1
  25. package/docs/behavior/localization.md +5 -1
  26. package/docs/behavior/security.md +18 -8
  27. package/package.json +9 -7
  28. package/dist/EditSurface-4VX20isB.cjs +0 -2
  29. package/dist/EditSurface-Ckg-3iTA.js +0 -786
  30. package/dist/index-DrKHJNY4.cjs +0 -13
  31. package/dist/sanitizePolicy-DlrakwA4.js +0 -96
  32. package/dist/sanitizePolicy-DrIMuYCb.cjs +0 -1
@@ -9,7 +9,10 @@ This page is part of the host-facing contract of `@aiquants/markdown-explorer`;
9
9
  - The explorer passes its document-viewer strings to `@aiquants/markdown`, which names every control and status text of the viewer with them, so the viewer follows the same language:
10
10
  its status texts (`viewerLoading`, `viewerErrorPrefix`, `viewerErrorTitle`, `viewerMissingImage`), its toolbar's buttons (`viewerSelectAlign`, `viewerSelectStyle`, `viewerOpenToc`), the alignment and style menus (`viewerAlignTitle`, `viewerAlignLeft`, `viewerAlignCenter`, `viewerAlignRight`, `viewerPinAlign`, `viewerUnpinAlign`, `viewerStyleTitle`, `viewerPinStyle`, `viewerUnpinStyle`), the table of contents (`viewerTocTitle`, which also names its navigation, `viewerPinToc`, `viewerUnpinToc`)
11
11
  and every Mermaid diagram's controls (`viewerMermaidInteractionMode` for the mouse-interaction menu and its button, `viewerMermaidModeNone`, `viewerMermaidModeZoom`, `viewerMermaidModePan`, `viewerMermaidModePanShift`, `viewerMermaidModeBoth`, `viewerMermaidModeBothShift` for its modes, `viewerMermaidInteractionModeTouch` for the same menu and button under a coarse pointer, `viewerMermaidModeNoneTouch`, `viewerMermaidModeZoomTouch`, `viewerMermaidModePanTouch`, `viewerMermaidModeBothTouch` for its touch items, `viewerMermaidZoomIn`, `viewerMermaidZoomOut`, `viewerMermaidResetView`,
12
- `viewerMermaidPanUp`, `viewerMermaidPanDown`, `viewerMermaidPanLeft`, `viewerMermaidPanRight` for the buttons that move the view while the drawing overflows its frame, `viewerMermaidRetry`, and `viewerMermaidDiagram`, the name of the diagram's focusable frame), and the titles of embedded frames (`viewerEmbeddedVideo` and `viewerEmbeddedPost` after a provider's name, as in "YouTube: embedded video", and `viewerEmbeddedFrame` before the host of an iframe written in a document without a title).
12
+ `viewerMermaidPanUp`, `viewerMermaidPanDown`, `viewerMermaidPanLeft`, `viewerMermaidPanRight` for the buttons that move the view while the drawing overflows its frame, `viewerMermaidRetry`, and `viewerMermaidDiagram`, the name of the diagram's focusable frame),
13
+ every ```spreadsheets table (`viewerSpreadsheetTable` and `viewerSpreadsheetFullscreenDialog` for the table's name in the document and full screen, `viewerSpreadsheetZoomIn`, `viewerSpreadsheetZoomOut`, `viewerSpreadsheetResetZoom`, `viewerSpreadsheetHighlight`, `viewerSpreadsheetCopyAll`, `viewerSpreadsheetSaveTsv`, `viewerSpreadsheetSaveMenu`, `viewerSpreadsheetSaveTsvWithBom`, `viewerSpreadsheetFullscreen` and `viewerSpreadsheetExitFullscreen` for its toolbar and save menu, `viewerSpreadsheetSize` for its size, `viewerSpreadsheetFileName` for the saved file,
14
+ `viewerSpreadsheetCopied`, `viewerSpreadsheetCopyFailed`, `viewerSpreadsheetReadOnly`, `viewerSpreadsheetFormatRefused`, `viewerSpreadsheetFenceRefused`, `viewerSpreadsheetEditConflict`, `viewerSpreadsheetOptionsError` and `viewerSpreadsheetLoadFailed` for its notices,
15
+ `viewerSpreadsheetCellAnnouncement`, `viewerSpreadsheetEmptyCell` and `viewerSpreadsheetSelectionAnnouncement` for what it announces, and `viewerSpreadsheetRetry`; the grid takes `locale` as its own locale, which picks the language of its own catalog, its data-validation messages and its scroll bar), and the titles of embedded frames (`viewerEmbeddedVideo` and `viewerEmbeddedPost` after a provider's name, as in "YouTube: embedded video", and `viewerEmbeddedFrame` before the host of an iframe written in a document without a title).
13
16
  A label the viewer receives carries no `lang` of its own, so it is read in the page's language. Where the viewer's own built-in label is in a catalog's language, the catalog repeats it word for word (the English catalog the viewer's English labels, such as `Display Style` and `Zoom In`; the Japanese catalog its Japanese ones, such as `目次を開く`), writing a full-width form in half-width (`拡大縮小+移動 (左ドラッグ)` for the viewer's `拡大縮小+移動 (左ドラッグ)`).
14
17
  - The explorer passes `treeEntryKindDirectory` and `treeEntryKindFile` (the kind words in the rows' accessible names) and `treeScrollUp`, `treeScrollDown`, `treeScrollToTop` and `treeScrollToBottom` (the tree's scroll bar) to `@aiquants/directory-tree`.
15
18
  - The explorer passes every string the multi view's drag-and-drop layout shows to `@aiquants/drag-drop-panels`: the panel headers' buttons (`panelMove`, `panelSwitchToCustomDrag`, `panelSwitchToNormalDrag`, `panelHide`, `panelMaximize`, `panelRestore`, `panelClose`), the items of their move menus (`panelMovePreviousColumn`, `panelMoveNextColumn`, `panelMoveUp`, `panelMoveDown`) and the custom drag mode's badge (`panelCustomDragBadge`),
@@ -44,6 +47,7 @@ const HANDBOOK_LABELS = {
44
47
  the path's last segment and the failure's title — the text of the matching `failure…Title` label, not the reason's code), `imageZoomLevel(percent)`, `treeRefreshFailed(reason)`, `documentRefreshed(name)`, `documentRefreshFailed(reason)`, `refreshDocumentNamed(name)` (a multi-view panel's icon-only Refresh document: its accessible name and tooltip, `name` being the panel title),
45
48
  `showMarkupNamed(name)` (a multi-view panel's icon-only Source toggle: its accessible name and tooltip, `name` being the panel title), `panelLimit(max)`, `panelOpened(name)`, `panelClosed(name)`, `panelAlreadyOpen(name)`, `panelHidden(name)`, `panelShown(name)`, `panelMaximized(name)`, `panelRestored(name)` — so each language can place the value where its grammar needs it.
46
49
  - The labels `@aiquants/drag-drop-panels` fills itself are templates instead, strings whose `{name}` placeholders mark where each value goes: `panelMoved` (`{title}` the panel's name, `{column}` its visible column, `{position}` its place among that column's shown panels), `panelMoveUnavailable` (`{title}`, and `{move}` the name of the move, one of the `panelMove…` labels), `panelDragStarted` and `panelDragCancelled` (`{title}`) and `multiColumnRegion` (`{column}`); columns and positions count from 1.
50
+ So are the table labels `@aiquants/markdown` fills: `viewerSpreadsheetSize` (`{rows}` and `{cols}`, the table's rows and columns), `viewerSpreadsheetCopyFailed` (`{reason}`, why the copy failed), `viewerSpreadsheetCellAnnouncement` (`{cell}` the cell's A1 name, `{value}` its value or `viewerSpreadsheetEmptyCell`), `viewerSpreadsheetSelectionAnnouncement` (`{range}`, the selection's A1 range), and `viewerSpreadsheetOptionsError` and `viewerSpreadsheetLoadFailed` (`{message}`, what is wrong).
47
51
  `MARKDOWN_EXPLORER_LABEL_TEMPLATES` lists each template's placeholders, and braces in every other label are literal text.
48
52
  - `labels` must be a plain object. An unknown key throws a `RangeError` that lists the valid keys, a value of the wrong type (a string where a function is expected, or the reverse) throws a `TypeError`, and a blank string throws a `RangeError`, because a blank name is neither shown nor announced. A template that uses a placeholder its key does not offer (`{name}` for `{title}`, say) throws a `RangeError` naming the placeholders it accepts, because a placeholder that is never filled would be read out as it is. A key set to `undefined` keeps the catalog's string.
49
53
  - The overrides are compared by value, key by key: writing `labels={{ … }}` inline does not re-render the explorer on every render of the host, but a function created inline is a new value each time — hoist it, or memoize the object.
@@ -8,9 +8,11 @@ The explorer renders documents that the reader did not write, from storage the r
8
8
 
9
9
  - A document path from a URL must be acceptable before any source sees it: non-empty, at most 4096 UTF-16 code units, well-formed (no lone surrogate, which no URL can carry), without control characters (U+0000–U+001F, U+007F) and without backslashes (some filesystems read them as separators). Anything else is answered as `invalid`.
10
10
  - Deny rules (`deny`, default `DEFAULT_DENIED_PATH_SEGMENTS`) hide matching entries from every listing — by entry name and by path, so a denied folder is pruned with everything under it — and refuse every document or children request for a matching path with a `forbidden` failure before any source is called.
11
- - A rule is matched against each path segment (or entry name) at every percent-decoding level up to three decodes, against each level whole and against its parts split again on `/` or `\` (a storage may read either character as part of one name, as a Linux file name, a Drive name or a GCS object name does, or as a separator), and after NFKC normalization and full case folding (upper-casing then lower-casing, which folds `ſ` to `s` and `ı` to `i`). Decoding is lenient: a malformed escape stays as written while the valid ones around it are decoded. `%2Eenv`, `%252Eenv`, `.%65nv`, `docs%5C.env`, `SECRETS` and `ſecrets` are all denied like `.env` and `secrets`, whatever the storage backend decodes or folds before opening the path.
11
+ - A rule is matched against each path segment (or entry name) at every percent-decoding level up to three decodes, against each level whole and against its parts split again on `/` or `\` (a storage may read either character as part of one name, as a Linux file name, a Drive name or a GCS object name does, or as a separator), and after NFKC normalization and full case folding (upper-casing then lower-casing, which folds `ſ` to `s` and `ı` to `i`). Decoding is lenient: a malformed escape stays as written while the valid ones around it are decoded.
12
+ `%2Eenv`, `%252Eenv`, `.%65nv`, `docs%5C.env`, `SECRETS` and `ſecrets` are all denied like `.env` and `secrets`, whatever the storage backend decodes or folds before opening the path.
12
13
  - Pattern syntax: a pattern matches one whole segment; `*` matches any run of characters inside it. `deny: false` turns the rules off; a custom array replaces the defaults (spread `DEFAULT_DENIED_PATH_SEGMENTS` to extend them).
13
- - The defaults cover environment files (`.env*` — every name starting with `.env`, for example `.env~`, `.env-old`, `.envs/`, and also `.envelope.md` — and `*.env` with the names its backups and copies take: `*.env.*`, `*.env~*`, `*.env-*`, `*.env_*` and `*.env#*`, for example `prod.env.bak`, `prod.env.production`, `prod.env.1`, `prod.env~`, `prod.env-old`, `prod.env_backup` and `#prod.env#`; rules have no exceptions, so a document named like `deploy.env.md` is denied too, while names in which `.env` is followed by a letter or digit, such as `prod.environment.md`, or has no dot before it, such as `environment.md` and `my-env.md`, are not),
14
+ - The defaults cover environment files (`.env*` — every name starting with `.env`, for example `.env~`, `.env-old`, `.envs/`, and also `.envelope.md` — and `*.env` with the names its backups and copies take:
15
+ `*.env.*`, `*.env~*`, `*.env-*`, `*.env_*` and `*.env#*`, for example `prod.env.bak`, `prod.env.production`, `prod.env.1`, `prod.env~`, `prod.env-old`, `prod.env_backup` and `#prod.env#`; rules have no exceptions, so a document named like `deploy.env.md` is denied too, while names in which `.env` is followed by a letter or digit, such as `prod.environment.md`, or has no dot before it, such as `environment.md` and `my-env.md`, are not),
14
16
  version-control metadata (`.git`, `.git-credentials`, `.svn`, `.hg`), `node_modules`, secrets files (`secrets`, `.secrets`, and `secrets.` with `json`, `yml`, `yaml`, `toml`, `ini` or `txt`), the credential folders and files of command-line tools (`.ssh`, `.aws`, `.gnupg`, `.docker`, `.kube`, `.terraform`, `.npmrc`, `.yarnrc`, `.yarnrc.yml`, `.netrc`, `_netrc`, `.pypirc`, `.pgpass`, `.my.cnf`, `.htpasswd`, `.vault-token`),
15
17
  keys and keystores (`id_rsa*`, `id_dsa*`, `id_ecdsa*`, `id_ed25519*`, `*.pem`, `*.key`, `*.p8`, `*.p12`, `*.pfx`, `*.ppk`, `*.jks`, `*.keystore`, `*.kdbx`), credential files (`*credentials*.json`, `service-account*.json`), Terraform state and variables (`*.tfstate`, `*.tfstate.*`, `*.tfvars`, `*.tfvars.json`) and shell histories (`.*_history`, `fish_history`).
16
18
  - `createFileSystemSource` additionally checks lexical containment before any filesystem call and again after resolving the real path, refuses symbolic links, and never follows a path outside its root. It opens a file without following a link (where the platform has `O_NOFOLLOW`) and reads it only when the opened file is the one the checks saw (the same device and inode; a document read refuses another file as `forbidden`).
@@ -41,8 +43,9 @@ Markdown HTML returned by a source is sanitized on the server with DOMPurify, in
41
43
  - `allow`, `allowfullscreen`, `frameborder` and `referrerpolicy` survive only on iframes: `referrerpolicy` only as `no-referrer`, `origin`, `same-origin`, `strict-origin` or `strict-origin-when-cross-origin` (`EMBED_FRAME_REFERRER_POLICIES`), and `allow` reduced to `autoplay`, `clipboard-write`, `encrypted-media`, `fullscreen`, `picture-in-picture` and `web-share`, each without its allowlist (`reduceFrameFeatures`);
42
44
  - `target` survives only on `a` and `area`, and a link with any `target` other than `_self` gets `rel="noopener noreferrer"`;
43
45
  - `id` attributes that would clobber `document` or form properties (`cookie`, `forms`, `location`, …) are removed — except on headings, which the table of contents needs and which cannot clobber `document`;
44
- - the markup converters write for GitHub alerts and Zenn's message and details containers survives as written, through DOMPurify's own allow-lists: `div`, `p`, `aside`, `span`, `details` and `summary` with their `class` (and `aria-hidden` on a message's symbol), and an alert's inline SVG icon, `svg` with its `class`, `viewBox`, `version`, `width`, `height` and `aria-hidden` and `path` with its `d` (the README's Documents gives the markup, and its Load the styles the `@aiquants/markdown` stylesheets that draw it). Inside it, as anywhere else, event handlers, `script`, `foreignObject`, `use` and `animate` are removed and URLs follow the rules above;
45
- - `data-*` attributes survive only for the Markdown renderer's contract — `data-link-kind`, `data-doc-path`, `data-doc-exists`, `data-footnote-ref` and `data-footnote-backref` on links, `data-asset-src` and `data-asset-exists` on images, `data-footnotes` on sections, and the embed placeholder below — so the renderer's iframe plugin trigger (`data-plugin-type`) and the `<div data-plugin-type>` placeholders of `@aiquants/markdown` 5 never reach the browser; SVG and MathML pass through DOMPurify's own allow-lists;
46
+ - the markup converters write for GitHub alerts and Zenn's message and details containers survives as written, through DOMPurify's own allow-lists: `div`, `p`, `aside`, `span`, `details` and `summary` with their `class` (and `aria-hidden` on a message's symbol), and an alert's inline SVG icon, `svg` with its `class`, `viewBox`, `version`, `width`, `height` and `aria-hidden` and `path` with its `d` (the README's Documents gives the markup, and its Load the styles the `@aiquants/markdown` stylesheets that draw it).
47
+ Inside it, as anywhere else, event handlers, `script`, `foreignObject`, `use` and `animate` are removed and URLs follow the rules above;
48
+ - `data-*` attributes survive only for the Markdown renderer's contract — `data-link-kind`, `data-doc-path`, `data-doc-exists`, `data-footnote-ref` and `data-footnote-backref` on links, `data-asset-src` and `data-asset-exists` on images, `data-footnotes` on sections, `data-code-meta` on code (a ```spreadsheets table's options, an inert value), and the embed placeholder below — so the renderer's iframe plugin trigger (`data-plugin-type`) and the `<div data-plugin-type>` placeholders of `@aiquants/markdown` 5 never reach the browser; SVG and MathML pass through DOMPurify's own allow-lists;
46
49
  - the embed placeholder, `data-embed-url` on a `<p>` (the converter's mark of a paragraph whose only content is one absolute `http(s)` link without credentials, holding the link's `href` byte for byte), survives only where `placeholderLinkOf` of `@aiquants/markdown/embeds` accepts it, whatever the provider.
47
50
  DOMPurify visits a parent before its children, so the sanitizer records the paragraph's attribute as parsed and, once DOMPurify is done with the attributes of a link directly inside that paragraph, restores it only when the paragraph holds exactly that one link (besides comments, white space, U+00A0 and U+3000) and the parsed attribute value equals the link's `href` as DOMPurify trimmed it.
48
51
  A padded attribute value, another `href`, an `href` DOMPurify removed (`javascript:`, `data:`), a relative or credential-bearing URL, a second link, text, any other element (even one after the link that DOMPurify then removes) or the attribute on another element leaves the paragraph and its link without it; a duplicated attribute is read as its first occurrence, as the HTML parser keeps it. A forged placeholder can therefore at most re-create what the converter writes for the bare link, and the viewer validates it again before it embeds or cards anything.
@@ -65,15 +68,22 @@ A markdown document that lists more than 10,000 headings (`EXPLORER_MAX_HEADINGS
65
68
  Sanitizing never runs on the request thread. HTML larger than `sanitizer.maxHtmlBytes` (4 MiB by default) is refused as `too-large` at once; the rest goes to a pool of worker threads (`sanitizer.workers`, 2 by default), shared by every explorer of the process with the same pool settings, with a per-document deadline (`sanitizer.deadlineMs`, 30 s by default): a document that misses it is `too-large`, and its worker is replaced.
66
69
  In the worker the nesting limit is enforced while the HTML is parsed, by the parser and in the mode DOMPurify's jsdom uses (parse5, the input as a whole document, scripting disabled), before DOMPurify runs and within the document's deadline.
67
70
  The parse stops, and the document is `too-large` without being sanitized, as soon as an element is placed deeper than 512 levels (the depth at which Chromium's HTML parser stops nesting elements; the children of `body` are at depth 1 and a `template`'s contents one level below it), or as soon as the parser has created more elements than the HTML has characters plus `html`, `head` and `body` (only formatting elements the parser reopens over and over can do that; an ordinary document stays far below).
68
- Before DOMPurify runs, the guard also counts every element, attribute and comment the parser creates and refuses the document (`too-large`) once the count passes (`sanitizer.workerHeapMb` − 64 MiB − `sanitizer.maxHtmlBytes` × 32 bytes) ÷ 4 KiB, which is 81,920 nodes by default, or once it has seen more than 4,096 comments wherever they sit. jsdom inserts each comment the parser attaches to the document itself (before `<html>` or after `</html>`) in time that grows with those already there (4,000 took 0.37 s and 8,000 took 1.4 s in the worker, while 8,000 comments inside the body took 0.14 s), so the cap keeps that worst case near 0.4 s. The constants are measured: the worker needs about 48 MiB of its own, a parsed node costs at most about 3.4 KB at the sanitizer's peak and a byte of HTML at most about 31 bytes, so a document the guard accepts fits in the worker's heap. The budget does not depend on the worker's heap limit and holds even where a process-wide `--max-old-space-size` overrides it.
69
- Before parsing, a linear scan follows every `<` or `</` followed by a letter through the tokenizer's tag states, quotes included, and refuses the document once a tag could hold more than 1,024 attributes, duplicates included; it also reads text the tokenizer would treat as text, so it may refuse more, never less. While parsing, `html` and `body` may receive at most 1,024 attributes through repeated tags. parse5, jsdom and DOMPurify look each attribute up in its element's list, so one element's attributes cost time that grows with the square of their number: without the cap, 40,000 attributes in one tag take 36 s and 79 repeated `body` tags of 1,000 attributes 90 s in the worker, while 78 tags of 1,024 take 1.8 s. The guard also adds up the name and value characters of every attribute the parser creates, including the copies it gives a formatting element it reopens or the adoption agency recreates, and refuses the document once they exceed `sanitizer.maxHtmlBytes` (a document whose elements each appear once never does): Without the budget, 1 MiB of copied `title` makes the worker write 210 million characters; the budget refuses it in about 0.1 s. Sanitized HTML longer than 4 × `sanitizer.maxHtmlBytes` UTF-16 code units (16,777,216 by default; ordinary HTML measured at most 2.05 characters per byte) is a cached `too-large`: the worker never posts it and the service refuses it should it arrive, so neither the cache (where the longest outcome weighs 32 MiB of the default 64 MiB) nor a caller ever holds more.
71
+ Before DOMPurify runs, the guard also counts every element, attribute and comment the parser creates and refuses the document (`too-large`) once the count passes (`sanitizer.workerHeapMb` − 64 MiB − `sanitizer.maxHtmlBytes` × 32 bytes) ÷ 4 KiB, which is 81,920 nodes by default, or once it has seen more than 4,096 comments wherever they sit. jsdom inserts each comment the parser attaches to the document itself (before `<html>` or after `</html>`) in time that grows with those already there (4,000 took 0.37 s and 8,000 took 1.4 s in the worker, while 8,000 comments inside the body took 0.14 s),
72
+ so the cap keeps that worst case near 0.4 s. The constants are measured: the worker needs about 48 MiB of its own, a parsed node costs at most about 3.4 KB at the sanitizer's peak and a byte of HTML at most about 31 bytes, so a document the guard accepts fits in the worker's heap. The budget does not depend on the worker's heap limit and holds even where a process-wide `--max-old-space-size` overrides it.
73
+ Before parsing, a linear scan follows every `<` or `</` followed by a letter through the tokenizer's tag states, quotes included, and refuses the document once a tag could hold more than 1,024 attributes, duplicates included; it also reads text the tokenizer would treat as text, so it may refuse more, never less.
74
+ While parsing, `html` and `body` may receive at most 1,024 attributes through repeated tags. parse5, jsdom and DOMPurify look each attribute up in its element's list, so one element's attributes cost time that grows with the square of their number: without the cap, 40,000 attributes in one tag take 36 s and 79 repeated `body` tags of 1,000 attributes 90 s in the worker, while 78 tags of 1,024 take 1.8 s.
75
+ The guard also adds up the name and value characters of every attribute the parser creates, including the copies it gives a formatting element it reopens or the adoption agency recreates, and refuses the document once they exceed `sanitizer.maxHtmlBytes` (a document whose elements each appear once never does): Without the budget, 1 MiB of copied `title` makes the worker write 210 million characters; the budget refuses it in about 0.1 s.
76
+ Sanitized HTML longer than 4 × `sanitizer.maxHtmlBytes` UTF-16 code units (16,777,216 by default; ordinary HTML measured at most 2.05 characters per byte) is a cached `too-large`: the worker never posts it and the service refuses it should it arrive, so neither the cache (where the longest outcome weighs 32 MiB of the default 64 MiB) nor a caller ever holds more.
70
77
  Every sanitizer worker starts with Node's `resourceLimits`: `workerHeapMb` MiB of old generation (512 by default) and 32 MiB of young generation. A worker whose heap runs out is ended with `ERR_WORKER_OUT_OF_MEMORY`, and its document is answered `too-large` and cached. The young generation is kept small on purpose: with Node's default for a worker (192 MiB), a worker at its limit could abort the whole process instead of ending alone, because one scavenge can promote more than the 16 MiB of leeway Node gives it.
71
78
  An element counts at the depth where the parser first places it, so when the parser later moves misnested markup to a shallower place (the adoption agency for misnested formatting tags, a `frameset` replacing `body`), a document whose finished tree is at most 512 levels deep can still be refused; a deeper one is never accepted. DOMPurify's own walk also stops at the first element deeper than 512 levels.
72
79
  Each request names its reader's scope. The pool admits at most `sanitizer.jobsPerScope` documents per reader running or waiting and `sanitizer.maxQueuedJobs` waiting in all; a document beyond either is `failed`, logged without the principal and not remembered, so a later request tries again.
73
- A page sends the document of every panel to the sanitizer at once for one reader, so the admission defaults follow the multi view: `jobsPerScope` defaults to `multiView.maxPanels` + max(1, `workers` − 1) + 3 — the panels, the previous page's documents still running after a reload (a running job is not stopped when its requests leave, and one reader runs at most max(1, `workers` − 1) at once), the two intent prefetches and one spare; 16 with the default 12 panels and two workers. `maxQueuedJobs` defaults to four times `jobsPerScope`, also when it is set. Neither may be set below `multiView.maxPanels` (a `RangeError` naming both at startup). All anonymous readers share one scope and therefore one admission budget.
80
+ A page sends the document of every panel to the sanitizer at once for one reader, so the admission defaults follow the multi view: `jobsPerScope` defaults to `multiView.maxPanels` + max(1, `workers` − 1) + 3 — the panels, the previous page's documents still running after a reload (a running job is not stopped when its requests leave, and one reader runs at most max(1, `workers` − 1) at once), the two intent prefetches and one spare; 16 with the default 12 panels and two workers. `maxQueuedJobs` defaults to four times `jobsPerScope`, also when it is set.
81
+ Neither may be set below `multiView.maxPanels` (a `RangeError` naming both at startup). All anonymous readers share one scope and therefore one admission budget.
74
82
  A reader runs at most `workers` − 1 documents at once (one when there is a single worker), and a free worker goes to the reader running the fewest, so one reader cannot starve the others; all anonymous readers share one scope.
75
83
  Concurrent requests of one reader for the same input share one job; jobs of different readers are separate, and the first to finish answers the others; a waiting job is dropped when every request waiting on it has left. The first outcome remembered for an input stays: it answers every other job still pending for that input and drops those still waiting, and a duplicate already running finishes on its worker without answering anyone or replacing that outcome, so a document near the deadline or the heap limit cannot flip between `sanitized` and `too-large`.
76
- Every outcome that describes the HTML (a refusal for nesting, the node budget, the heap or the deadline included) is remembered by the SHA-256 of the input in a cache bounded by count (1024 entries) and by bytes (`sanitizer.cacheBytes`, 64 MiB by default), so a document read by many readers is sanitized — or refused — once. A worker is sent a document only after it has reported that it is ready. A worker that fails before then (it cannot be started, is not ready within the deadline, or fails or exits while starting) never received the document: the document is answered `failed`, the cause is logged, and the outcome is not cached. A failure while a worker holds a document it was sent, such as an uncaught error or an unexpected exit, is that document's crash and stays a cached `failed`, whatever order Node delivers the worker's error and its messages in. Running out of heap and missing the deadline stay a cached `too-large`. Creating the explorer fails when the worker file is missing next to the server module; where DOMPurify cannot run, it refuses instead of returning its input unchanged, and the document fails.
84
+ Every outcome that describes the HTML (a refusal for nesting, the node budget, the heap or the deadline included) is remembered by the SHA-256 of the input in a cache bounded by count (1024 entries) and by bytes (`sanitizer.cacheBytes`, 64 MiB by default), so a document read by many readers is sanitized — or refused — once. A worker is sent a document only after it has reported that it is ready.
85
+ A worker that fails before then (it cannot be started, is not ready within the deadline, or fails or exits while starting) never received the document: the document is answered `failed`, the cause is logged, and the outcome is not cached. A failure while a worker holds a document it was sent, such as an uncaught error or an unexpected exit, is that document's crash and stays a cached `failed`, whatever order Node delivers the worker's error and its messages in. Running out of heap and missing the deadline stay a cached `too-large`.
86
+ Creating the explorer fails when the worker file is missing next to the server module; where DOMPurify cannot run, it refuses instead of returning its input unchanged, and the document fails.
77
87
 
78
88
  Fixed or absolutely positioned markup in a document cannot cover the host or the explorer: the document region is its containing block and clips its painting (in a multi-view panel, the panel's frame clips it). Such markup can still cover the rest of its own document.
79
89
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiquants/markdown-explorer",
3
- "version": "0.19.0",
3
+ "version": "0.21.0",
4
4
  "description": "Markdown document explorer for React Router 8 (framework mode): a source tree with a single-document view and a multi-panel reading view, storage-agnostic server ports, golden-ratio layout and an en / ja UI.",
5
5
  "sideEffects": [
6
6
  "**/*.css"
@@ -68,21 +68,23 @@
68
68
  "parse5": "^8.0.0"
69
69
  },
70
70
  "peerDependencies": {
71
- "@aiquants/directory-tree": "^5.0.0",
71
+ "@aiquants/directory-tree": "^5.0.1",
72
72
  "@aiquants/drag-drop-panels": "^0.12.0",
73
- "@aiquants/markdown": "^8.1.1",
73
+ "@aiquants/markdown": "^10.0.0",
74
74
  "@aiquants/resize-panels": "^2.2.0",
75
- "@aiquants/virtualscroll": "^3.22.0",
75
+ "@aiquants/spreadsheet": "^0.15.0",
76
+ "@aiquants/virtualscroll": "^3.22.1",
76
77
  "react": "^19.2.7",
77
78
  "react-dom": "^19.2.7",
78
79
  "react-router": "^8.0.0"
79
80
  },
80
81
  "devDependencies": {
81
- "@aiquants/directory-tree": "5.0.0",
82
+ "@aiquants/directory-tree": "5.0.1",
82
83
  "@aiquants/drag-drop-panels": "0.12.0",
83
- "@aiquants/markdown": "8.1.1",
84
+ "@aiquants/markdown": "10.0.0",
84
85
  "@aiquants/resize-panels": "2.2.0",
85
- "@aiquants/virtualscroll": "3.22.0",
86
+ "@aiquants/spreadsheet": "0.15.0",
87
+ "@aiquants/virtualscroll": "3.22.1",
86
88
  "@heroicons/react": "^2.2.0",
87
89
  "@playwright/test": "^1.59.1",
88
90
  "@tailwindcss/cli": "^4.1.18",
@@ -1,2 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=require("react/jsx-runtime"),p=require("react"),x=require("./index-DrKHJNY4.cjs"),ee=require("@codemirror/commands"),ae=require("@codemirror/lang-markdown"),ye=require("@codemirror/language"),ce=require("@codemirror/search"),K=require("@codemirror/state"),I=require("@codemirror/view"),_=require("@lezer/highlight"),Ce=require("@aiquants/markdown"),ne=require("@aiquants/markdown/source-lines"),W=require("./dataRoute-BONacTPi.cjs"),oe=require("./sanitizePolicy-DrIMuYCb.cjs"),_e=require("isomorphic-dompurify"),Q=require("@aiquants/resize-panels"),G=require("./location-BVEN_Ihk.cjs"),ue=require("./useSplitPersistence-Ba-v64n-.cjs"),Te={history:ee.historyField},Pe=ye.HighlightStyle.define([{tag:[_.tags.heading1,_.tags.heading2,_.tags.heading3,_.tags.heading4,_.tags.heading5,_.tags.heading6,_.tags.heading],color:"var(--aqmx-syntax-heading)",fontWeight:"700"},{tag:_.tags.strong,fontWeight:"700"},{tag:_.tags.emphasis,fontStyle:"italic"},{tag:_.tags.strikethrough,textDecoration:"line-through"},{tag:_.tags.link,color:"var(--aqmx-syntax-link)",textDecoration:"underline"},{tag:_.tags.url,color:"var(--aqmx-syntax-url)"},{tag:_.tags.monospace,color:"var(--aqmx-syntax-code)"},{tag:_.tags.quote,color:"var(--aqmx-syntax-quote)"},{tag:[_.tags.processingInstruction,_.tags.contentSeparator,_.tags.labelName,_.tags.meta],color:"var(--aqmx-syntax-mark)"}]),Ne=I.EditorView.theme({"&":{height:"100%",color:"var(--aqmx-text)",backgroundColor:"var(--aqmx-surface)",fontSize:"var(--aqmx-font-size-title)"},"&.cm-focused":{outline:"none"},".cm-scroller":{fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',lineHeight:"var(--aqmx-line-height-prose)"},".cm-content":{caretColor:"var(--aqmx-text)",paddingBlock:"var(--aqmx-space-6)"},".cm-line":{paddingInline:"var(--aqmx-space-6)"},"&.cm-focused .cm-cursor":{borderLeftColor:"var(--aqmx-text)"},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:"var(--aqmx-editor-selection)"},".cm-activeLine":{backgroundColor:"var(--aqmx-editor-active-line)"},".cm-gutters":{backgroundColor:"var(--aqmx-surface-raised)",color:"var(--aqmx-editor-gutter)",borderInlineEnd:"var(--aqmx-space-1) solid var(--aqmx-border)"},".cm-activeLineGutter":{backgroundColor:"var(--aqmx-editor-active-line)"},".cm-searchMatch":{outline:"var(--aqmx-space-1) solid var(--aqmx-border-strong)"},".cm-panels":{backgroundColor:"var(--aqmx-surface-raised)",color:"var(--aqmx-text)"}}),Le="data-aqmx-conflict-actions",De=I.Decoration.line({attributes:{"data-aqmx-conflict-line":"marker"}}),Ve=I.Decoration.line({attributes:{"data-aqmx-conflict-line":"ours"}}),je=I.Decoration.line({attributes:{"data-aqmx-conflict-line":"theirs"}});class He extends I.WidgetType{constructor(t,r){super(),this.index=t,this.labels=r}index;labels;eq(t){return t.index===this.index&&t.labels===this.labels}toDOM(t){const r=document.createElement("div");r.setAttribute(Le,String(this.index));for(const[o,a]of[["ours",this.labels.useOurs],["theirs",this.labels.useTheirs],["both",this.labels.keepBoth]]){const s=document.createElement("button");s.type="button",s.textContent=a,s.setAttribute("data-aqmx-conflict-choice",o),s.addEventListener("mousedown",l=>l.preventDefault()),s.addEventListener("click",()=>{const l=Y(t.state.doc)[this.index];l!==void 0&&(ke(t,l,o),t.focus())}),r.append(s)}return r}ignoreEvent(){return!0}}const Y=e=>x.findConflictsInLines(e.iterLines()),de=(e,t)=>{const r=new K.RangeSetBuilder;return Y(e).forEach((o,a)=>{const s=e.line(o.start);r.add(s.from,s.from,I.Decoration.widget({widget:new He(a,t),block:!0,side:-1}));for(let l=o.start;l<=o.end;l+=1){const n=e.line(l).from,h=l===o.start||l===o.separator||l===o.end?De:l<o.separator?Ve:je;r.add(n,n,h)}}),r.finish()},Be=e=>K.StateField.define({create:t=>de(t.doc,e),update:(t,r)=>r.docChanged?de(r.state.doc,e):t,provide:t=>I.EditorView.decorations.from(t)}),ke=(e,t,r)=>{const{doc:o}=e.state,a=(u,c)=>{const g=[];for(let m=u;m<=c;m+=1)g.push(o.line(m).text);return g},s=a(t.start+1,t.separator-1),l=a(t.separator+1,t.end-1),n=r==="ours"?s:r==="theirs"?l:[...s,...l];let h=o.line(t.start).from,f=o.line(t.end).to;n.length===0&&(t.end<o.lines?f+=1:t.start>1&&(h-=1));const i=n.join(`
2
- `);e.dispatch({changes:{from:h,to:f,insert:i},selection:K.EditorSelection.cursor(h),scrollIntoView:!0,userEvent:"input.resolve"})},ze=({parent:e,scroll:t,text:r,saved:o,labels:a,onChange:s,onGeometry:l,onSave:n})=>{const h=[I.EditorView.scrollHandler.of((u,c,g)=>(Fe(u,c.head,g,t),!0)),I.lineNumbers(),I.highlightActiveLineGutter(),ee.history(),I.drawSelection(),I.highlightActiveLine(),ce.highlightSelectionMatches(),I.EditorView.lineWrapping,ae.markdown({base:ae.markdownLanguage}),ye.syntaxHighlighting(Pe),Be(a),I.keymap.of([{key:"Mod-s",preventDefault:!0,run:()=>(n(),!0)},...ce.searchKeymap,...ee.historyKeymap,...ee.defaultKeymap]),I.EditorView.contentAttributes.of({"aria-label":a.editor,"aria-multiline":"true"}),I.EditorView.updateListener.of(u=>{u.docChanged&&s(),(u.docChanged||u.heightChanged||u.geometryChanged)&&l(u.docChanged)}),Ne],f=Xe(o,h)??K.EditorState.create({doc:r,extensions:h}),i=new I.EditorView({state:f,parent:e});return{text:()=>i.state.doc.toString(),replaceText:u=>{const c=i.state.doc.toString();if(c===u)return;let g=0;const m=Math.min(c.length,u.length);for(;g<m&&c.charCodeAt(g)===u.charCodeAt(g);)g+=1;let S=0;for(;S<m-g&&c.charCodeAt(c.length-1-S)===u.charCodeAt(u.length-1-S);)S+=1;i.dispatch({changes:{from:g,to:c.length-S,insert:u.slice(g,u.length-S)},userEvent:"input.replace"})},reveal:({line:u,column:c},g)=>{const{doc:m}=i.state,S=m.line(Math.min(Math.max(u,1),m.lines)),v=Math.min(S.from+c,S.to);i.dispatch({selection:K.EditorSelection.cursor(v),effects:fe(i,v,g,t)})},showLine:u=>{const{doc:c}=i.state,g=c.line(Math.min(Math.max(u,1),c.lines)).from;i.dispatch({effects:fe(i,g,null,t)})},topLine:()=>{const u=t.scrollerOf(i.scrollDOM),c=x.visibleTopOf(u,i.contentDOM),g=x.frameTopOf(u)+u.clientHeight,{documentTop:m}=i,{doc:S}=i.state;let v=i.lineBlockAtHeight(Math.max(c-m,0));for(;S.lineAt(v.from).text.trim()===""&&v.to<S.length;){const A=i.lineBlockAt(v.to+1);if(m+A.top>=g)break;v=A}const k=i.coordsAtPos(v.from),O=k===null?m+v.top:k.top;return{line:i.state.doc.lineAt(v.from).number,clientTop:O,offset:O-c}},lineSpans:u=>{const c=i.scrollDOM,g=c.scrollTop+i.documentTop-x.visibleTopOf(c,i.contentDOM),{doc:m}=i.state,S=v=>m.line(Math.min(Math.max(v,1),m.lines)).from;return u.map(({first:v,last:k})=>({top:g+i.lineBlockAt(S(v)).top,bottom:g+i.lineBlockAt(S(k)).bottom}))},scrollElement:i.scrollDOM,focus:()=>i.focus(),conflicts:()=>Y(i.state.doc),resolveAtCursor:u=>{const c=Y(i.state.doc),g=i.state.doc.lineAt(i.state.selection.main.head).number,m=c.find(S=>S.end>=g);return m===void 0?!1:(ke(i,m,u),!0)},nextConflict:()=>{const u=Y(i.state.doc);if(u[0]===void 0)return!1;const g=i.state.doc.lineAt(i.state.selection.main.head).number,m=u.findIndex(O=>O.start>g),S=m<0?0:m,v=i.state.doc.line(u[S].start).from;i.dispatch({selection:K.EditorSelection.cursor(v),effects:I.EditorView.scrollIntoView(v,{y:"center"})});const k=i.contentDOM.querySelector(`[${Le}="${String(S)}"] button`);return k instanceof HTMLElement?k.focus({preventScroll:!0}):i.focus(),!0},save:()=>i.state.toJSON(Te),destroy:()=>i.destroy()}},fe=(e,t,r,o)=>{const a=o.scrollerOf(e.scrollDOM),s=(r===null?x.visibleTopOf(a,e.contentDOM):r)-x.frameTopOf(a);return I.EditorView.scrollIntoView(t,{y:"start",yMargin:s})},Fe=(e,t,r,o)=>{const a=Ue(e,t),s=o.scrollerOf(e.scrollDOM),l=x.frameTopOf(s),n=x.visibleTopOf(s,e.contentDOM),h=l+s.clientHeight;let f=0;switch(r.y){case"start":f=a.top-(l+r.yMargin);break;case"center":f=(a.top+a.bottom)/2-(n+h)/2;break;case"end":f=a.bottom-(h-r.yMargin);break;default:a.top<n+r.yMargin?f=a.top-(n+r.yMargin):a.bottom>h-r.yMargin&&(f=Math.min(a.bottom-(h-r.yMargin),a.top-(n+r.yMargin)))}if(f!==0&&(s.scrollTop+=f),r.y==="start")return;const i=Ge(e,t);i!==null&&o.reveal(i)},Ue=(e,t)=>{const{node:r,offset:o}=e.domAtPos(t);if(r.nodeType===Node.TEXT_NODE){const l=r.ownerDocument?.createRange();if(l!==void 0){l.setStart(r,o),l.setEnd(r,o);const[n]=l.getClientRects();if(n!==void 0&&n.height>0)return{top:n.top,bottom:n.bottom}}}const a=e.lineBlockAt(t),s=e.documentTop+a.top;return{top:s,bottom:s+a.height}},Ge=(e,t)=>{const{node:r}=e.domAtPos(t);for(let o=r instanceof Element?r:r.parentElement;o!==null;o=o.parentElement)if(o.parentElement===e.contentDOM)return o;return null},Xe=(e,t)=>{if(e==null)return null;try{return K.EditorState.fromJSON(e,{extensions:t},Te)}catch{return null}},Ke=610,We=987,pe=Object.freeze({kind:"unavailable"}),$e="true",Ye="false",Je=e=>e===$e?!0:e===Ye?!1:null,Qe=e=>{const t=new DOMParser().parseFromString(e,"text/html"),r=[];for(const o of t.querySelectorAll("img[data-asset-src], a[data-doc-path]")){const a=o.localName==="img",s=o.getAttribute(a?"data-asset-src":"data-doc-path");s!==null&&r.push({target:{kind:a?"asset":"doc",path:s},exists:Je(o.getAttribute(a?"data-asset-exists":"data-doc-exists"))})}return r},Ze=({path:e,instant:t,preview:r,initial:o,onView:a})=>{const s=new AbortController,l={asset:new Map,doc:new Map};let n=o,h=null,f=!1,i=!1,u=null,c=null,g=[],m,S=!1,v,k=null;const O=y=>{y.parsed===n.parsed&&y.failure===n.failure&&y.busy===n.busy&&y.tier===n.tier||(n=y,a(y))},A=(y,d)=>{f||(f=!0,console.error(`[markdown-explorer] ${y}`,...d===void 0?[]:[d]))},j=y=>{if(t!==null)for(const{target:d,exists:E}of t.marksOf(y))l[d.kind].set(d.path,E)},D=()=>{clearTimeout(v),v=void 0,k?.abort(),k=null},V=()=>{c=null,g=[],clearTimeout(m),m=void 0},H=(y,d)=>{O({parsed:n.parsed,failure:y,busy:!1,tier:d})},b=()=>{clearTimeout(m),m=g.length===0?void 0:setTimeout(q,We)},T=()=>{if(t===null||c===null)return;const y=c,d=[],E={asset:new Set,doc:new Set};let R;try{R=t.sanitize(y.html,C=>{const U=l[C.kind].get(C.path);return U===void 0&&!E[C.kind].has(C.path)&&(E[C.kind].add(C.path),d.push(C)),U??void 0})}catch(C){V(),C instanceof oe.HtmlNestingLimitError?H(W.failureOf("too-large"),"instant"):(A("the draft sanitizer failed",C),H(W.failureOf("failed"),"instant"));return}g=d;const M=n.parsed!==null&&n.parsed.htmlContent===R&&n.parsed.headings===y.headings?n.parsed:{htmlContent:R,headings:y.headings};O({parsed:M,failure:null,busy:!1,tier:"instant"}),b()},q=()=>{if(m=void 0,S||c===null||g.length===0)return;S=!0;const y=g;r(e,c.text,s.signal).then(d=>{if(S=!1,!(s.signal.aborted||!("kind"in d))){d.kind==="preview"&&j(d.htmlContent);for(const E of y)l[E.kind].has(E.path)||l[E.kind].set(E.path,null);T()}})},P=y=>{D(),V(),O({...n,busy:!0,tier:"server"});const d=new AbortController;k=d,v=setTimeout(()=>{v=void 0,r(e,y,d.signal).then(E=>{if(!(d.signal.aborted||!("kind"in E))){if(k=null,E.kind==="failure"){H(E.failure,"server");return}j(E.htmlContent),O({parsed:{htmlContent:E.htmlContent,headings:E.headings},failure:null,busy:!1,tier:"server"})}})},Ke)},w=async(y,d)=>{let E;try{E=await y.convert({path:e,text:d},s.signal)}catch(M){return s.signal.aborted||A("the draft converter rejected a conversion, which its contract allows only once the signal aborted",M),pe}const R=W.draftAnswerViolation(E);return R===null?E:(A(`the draft converter answered outside its contract: ${R}`),pe)},B=(y,d)=>{switch(d.kind){case"preview":if(D(),d.headings.length>W.EXPLORER_MAX_HEADINGS){V(),H(W.failureOf("too-large"),"instant");return}c={text:y,html:d.htmlContent,headings:d.headings.map(({text:E,depth:R,id:M})=>({text:E,depth:R,id:M}))},T();return;case"failure":D(),V(),H(W.failureOf(d.failure.reason,d.failure.code),"instant");return;case"unavailable":P(y);return}},z=async y=>{i=!0;try{for(;u!==null&&!s.signal.aborted;){const d=u;u=null;const E=await w(y,d);if(s.signal.aborted)return;B(d,E)}}finally{i=!1}};return t!==null&&t.seed!==null&&j(t.seed),{update:y=>{if(!(s.signal.aborted||y===h)){if(h=y,clearTimeout(m),m=void 0,t===null){P(y);return}u=y,i||z(t.converter)}},dispose:()=>{s.abort(),u=null,clearTimeout(m),m=void 0,D()}}},et=(e,t)=>oe.createHtmlSanitizer(_e(window),e,t,oe.MAX_HTML_NESTING_DEPTH),tt=(e,t)=>e.flatMap((r,o)=>{const a=t[o];return a===void 0?[]:[{editor:a.top,preview:r.top},{editor:a.bottom,preview:r.bottom}]}),X=(e,t)=>{const r=e[t];if(r===void 0)throw new RangeError(`[markdown-explorer] a scroll map index must be in 0..${String(e.length-1)}; got ${String(t)}`);return r},rt=e=>{const t=[];for(const o of e){let a=0,s=t.length;for(;a<s;){const l=a+s>>1;X(t,l).pair.preview<=o.preview?a=l+1:s=l}t[a]={pair:o,before:a===0?void 0:X(t,a-1)}}const r=[];for(let o=t.at(-1);o!==void 0;o=o.before)r.push(o.pair);return r.reverse()},nt=(e,t)=>{const r=Math.max(t.editorMax,0),o=Math.max(t.previewMax,0),a=r-t.editorViewport,s=o-t.previewViewport,l=e.filter(f=>f.editor>0&&f.editor<a&&f.preview>0&&f.preview<s).sort((f,i)=>f.editor-i.editor||f.preview-i.preview);let n={editor:0,preview:0};const h=[n];for(const f of rt(l))f.editor>n.editor&&f.preview>n.preview&&(h.push(f),n=f);return h.push({editor:r,preview:o}),{toPreview:f=>me(h,"editor","preview",f),toEditor:f=>me(h,"preview","editor",f)}},me=(e,t,r,o)=>{const a=X(e,0),s=X(e,e.length-1);if(Number.isNaN(o)||o<=a[t])return a[r];if(o>=s[t])return s[r];let l=0,n=e.length-1;for(;n-l>1;){const i=l+n>>1;X(e,i)[t]<=o?l=i:n=i}const h=X(e,l),f=X(e,n);return h[r]+(f[r]-h[r])*(o-h[t])/(f[t]-h[t])},ot=610,he=89,ge=.5,it=({editor:e,preview:t,previewBlocks:r,editorSpans:o,requestFrame:a,cancelFrame:s,now:l})=>{let n="editor",h=0,f=null,i=null,u=!1,c=null,g=null;const m={editor:0,preview:0},S={editor:null,preview:null};let v=null,k=()=>{};const O=w=>{f!==null&&w!==f||(n=w,h=l()+ot)},A=(w,B)=>{w!==n&&f===null&&l()>=h&&!j(w,B)&&(n=w),T()},j=(w,B)=>{const z=S[w];return l()<m[w]||z!==null&&Math.abs(B.position()-z)<ge},D=e.onScroll(()=>A("editor",e)),V=e.onIntent(()=>O("editor")),H=()=>{const w=t();return w!==v&&(k(),v=w,k=w===null?()=>{}:b(w)),w},b=w=>{const B=w.onScroll(()=>A("preview",w)),z=w.onIntent(()=>O("preview"));return()=>{B(),z()}},T=()=>{!u&&i===null&&(i=a(q))},q=()=>{i=null;const w=H();w!==null&&(c??=r(),g??=nt(tt(c,o(c)),{editorMax:e.max(),previewMax:w.max(),editorViewport:e.viewport(),previewViewport:w.viewport()}),n==="editor"?P(w,"preview",g.toPreview(e.position())):P(e,"editor",g.toEditor(w.position())))},P=(w,B,z)=>{if(Math.abs(w.position()-z)<ge){S[B]=w.position();return}m[B]=l()+he,S[B]=w.scrollTo(z)};return T(),{editorChanged:w=>{g=null,w&&O("editor"),T()},previewChanged:()=>{c=null,g=null,m.preview=l()+he,T()},showAlone:w=>{f=w,!(w===null||w===n)&&(n=w,h=0,T())},dispose:()=>{u=!0,i!==null&&s(i),i=null,D(),V(),k()}}},ve=Object.freeze(["wheel","pointerdown","keydown","focusin"]),qe=e=>({position:()=>e.scrollTop,max:()=>Math.max(e.scrollHeight-e.clientHeight,0),viewport:()=>e.clientHeight,scrollTo:t=>(e.scrollTo({top:t,behavior:"instant"}),e.scrollTop),onScroll:t=>(e.addEventListener("scroll",t,{passive:!0}),()=>e.removeEventListener("scroll",t)),onIntent:t=>{for(const r of ve)e.addEventListener(r,t,{capture:!0,passive:!0});return()=>{for(const r of ve)e.removeEventListener(r,t,{capture:!0})}}}),$="[data-aqmd-scroll-container]",st="[data-aqmd-content]",lt=`[${ne.SOURCE_LINES_ATTRIBUTE}]`,at=Object.freeze(["p1","p2","p3","p4","p5","p6","p7","p8"]),Re=(e,t)=>{const r=x.loadedOf(e.peek(t));return r!==null&&r.document.kind==="markdown"?{htmlContent:r.document.htmlContent,headings:r.document.headings}:null},ct=(e,t,r,o,a)=>{if(r===void 0)return null;let s;try{s=et(e,t)}catch(l){return console.error("[markdown-explorer] the draft sanitizer cannot run in this browser, so the server renders the preview",l),null}return{converter:r,sanitize:s,marksOf:Qe,seed:Re(o,a)?.htmlContent??null}},ut=e=>{const t=[];let r=null;for(const o of e.querySelectorAll(lt)){const a=ne.parseSourceLines(o.getAttribute(ne.SOURCE_LINES_ATTRIBUTE));if(a===null||o.getClientRects().length===0)continue;r??=e.scrollTop-x.visibleTopOf(e,o);const{top:s,bottom:l}=o.getBoundingClientRect();t.push({first:a.first,last:a.last,top:r+s,bottom:r+l})}return t},dt=({path:e,readDraft:t,viewer:r,concealed:o,onEditAt:a,onLayout:s,handleRef:l})=>{const{config:n,data:h,documents:f,draftConverter:i,labels:u}=x.useExplorer(),[c,g]=p.useState(()=>({parsed:Re(f,e),failure:null,busy:!0,tier:i===void 0?"server":"instant"})),m=p.useRef(null),S=p.useRef(null),v=p.useRef(c);p.useLayoutEffect(()=>{v.current=c});const k=p.useEffectEvent(()=>t());p.useEffect(()=>{const b=ct(n.iframeHosts,n.dataPath,i,f,e),T=Ze({path:e,instant:b,preview:h.preview,initial:v.current,onView:q=>p.startTransition(()=>g(q))});return S.current=T,T.update(k()),()=>{T.dispose(),S.current=null}},[n,h,f,i,e]);const O=p.useEffectEvent(()=>s());p.useLayoutEffect(()=>{c.parsed!==null&&O()},[c.parsed]);const A=c.parsed!==null;p.useLayoutEffect(()=>{const b=A?m.current?.querySelector($):null;if(!(b instanceof HTMLElement))return;b.tabIndex=0;const T=new ResizeObserver(()=>O());T.observe(b);const q=b.querySelector(st);return q!==null&&T.observe(q),()=>T.disconnect()},[A]);const j=p.useRef(null);p.useImperativeHandle(l,()=>({draft:b=>{S.current?.update(b)},scrollPort:()=>{const b=m.current?.querySelector($);return b instanceof HTMLElement?(j.current?.scroller!==b&&(j.current={scroller:b,port:qe(b)}),j.current.port):null},blocks:()=>{const b=m.current?.querySelector($);return b instanceof HTMLElement?ut(b):[]},focus:()=>{const b=m.current?.querySelector($);b instanceof HTMLElement&&b.focus({preventScroll:!0})},anchor:b=>{const T=m.current,q=T?.querySelector($);return T===null||!(q instanceof HTMLElement)?null:x.anchorOfView(T,b(q))},place:({line:b,clientTop:T},q)=>{const P=m.current,w=P===null?null:x.blockAtLine(P,b);w!==null&&(q(w).scrollTop+=x.lineTopIn(w,b)-T)}}),[]);const D=b=>{const T=m.current,{target:q}=b;if(a===void 0||T===null||!(q instanceof Element)||!x.isEditingDoubleClick(q))return;const P=x.anchorOfDoubleClick(q,T,T.ownerDocument.getSelection());P!==null&&a(P)},V=p.useMemo(()=>({...r,showToc:!1,showStyle:!1,showAlign:!1,renderScrollBar:void 0}),[r]),H=p.useMemo(()=>c.parsed===null?null:L.jsx("div",{className:"aqmx-document-viewer",children:L.jsx(Ce.MarkdownViewer,{...V,parseResult:c.parsed,content:null})}),[V,c.parsed]);return L.jsxs("section",{ref:m,className:"aqmx-edit-preview","aria-label":u.previewRegion,"aria-busy":c.busy,inert:o!==null,hidden:o==="removed","data-aqmx-preview-tier":c.tier,"data-testid":"markdown-explorer-edit-preview",onDoubleClick:a===void 0?void 0:D,children:[c.failure===null?null:L.jsx("p",{className:"aqmx-callout aqmx-document-notice","data-aqmx-tone":"warning","data-testid":"markdown-explorer-edit-preview-failure",children:u.previewFailed(x.failureTitleOf(u,c.failure.reason))}),H??(c.failure===null?L.jsx("div",{className:"aqmx-skeleton","aria-hidden":"true","data-testid":"markdown-explorer-edit-preview-skeleton",children:at.map(b=>L.jsx("span",{},b))}):null),c.busy?L.jsx("p",{className:"aqmx-sr-only",children:u.previewUpdating}):null]})},we="data-aqmx-edit-split",re="--aqmx-edit-share",Ee="--aqmx-edit-gutter",ft="data-aqmx-edit-split-probe",pt="aqmx-edit-split",mt="aqmx-edit-editor",ht="aqmx-edit-preview",be={value:G.EDIT_SPLIT_MIN_PERCENT,unit:"percentage"},xe={value:G.EDIT_SPLIT_MAX_PERCENT,unit:"percentage"},Se=e=>{if(e.length!==2)return null;const[t=0,r=0]=e,o=t+r;return o>0?t/o*100:null},Z=e=>{const t=e.current?.parentElement;if(t==null)throw new Error("[markdown-explorer] the edit split is not mounted in its surface");return t},gt=(e,t,r)=>{const[o,a]=p.useState(null);return p.useLayoutEffect(()=>{const s=e.current,l=t.current;if(s===null||l===null)throw new Error("[markdown-explorer] the edit split is not mounted");const n={frame:s.getBoundingClientRect().width,measure:l.getBoundingClientRect().width},h=()=>{n.frame>0&&n.measure>0&&a(G.editSplitOrientation(n.frame,n.measure,r))};h();const f=new ResizeObserver(i=>{for(const u of i){const[c]=u.borderBoxSize;c!==void 0&&(u.target===s&&(n.frame=c.inlineSize),u.target===l&&(n.measure=c.inlineSize))}h()});return f.observe(s),f.observe(l),()=>f.disconnect()},[e,t,r]),o},vt=({editorId:e})=>{const{edits:t,labels:r}=x.useExplorer(),o=p.useRef(null),a=p.useRef(null),s=ue.useCoarsePointer()?G.COARSE_TARGET_PIXELS:G.FINE_TARGET_PIXELS,l=gt(o,a,s),[n]=p.useState(()=>t.editorShare());p.useLayoutEffect(()=>{const i=Z(o);return i.style.setProperty(Ee,`${String(s)}px`),()=>{i.style.removeProperty(Ee)}},[s]),p.useLayoutEffect(()=>{const i=Z(o);return i.style.setProperty(re,`${String(n)}%`),()=>{i.style.removeProperty(re)}},[n]),p.useLayoutEffect(()=>{if(l===null)return;const i=Z(o);return i.setAttribute(we,l),()=>i.removeAttribute(we)},[l]);const h=ue.useSplitPersistence(p.useCallback(i=>{const u=Se(i);u!==null&&t.setEditorShare(u)},[t])),f=p.useCallback((i,u)=>{const c=Se(i);c!==null&&Z(o).style.setProperty(re,`${String(c)}%`),h.layoutChanged(i,u)},[h]);return L.jsxs("div",{ref:o,className:"aqmx-edit-split","data-testid":"markdown-explorer-edit-split",children:[L.jsx("span",{ref:a,className:"aqmx-edit-split-probe","aria-hidden":"true",[ft]:""}),l===null?null:L.jsxs(Q.PanelGroup,{id:pt,direction:l==="beside"?"horizontal":"vertical",onLayout:f,className:"aqmx-edit-split-group",children:[L.jsx(Q.Panel,{id:mt,defaultSize:{value:n,unit:"percentage"},minSize:be,maxSize:xe,contentOverflow:"hidden"}),L.jsx(Q.PanelResizeHandle,{thickness:s,indicator:{visible:!0,thickness:G.SPLIT_HANDLE_PIXELS.gripThickness,length:G.SPLIT_HANDLE_PIXELS.gripLength,barThickness:G.SPLIT_HANDLE_PIXELS.barThickness,barLength:G.SPLIT_HANDLE_PIXELS.barLength},title:r.editViewSplitResize,"aria-label":r.editViewSplitResize,"aria-controls":e,onDragging:h.draggingChanged,className:"aqmx-split-handle aqmx-edit-split-handle"}),L.jsx(Q.Panel,{id:ht,defaultSize:{value:100-n,unit:"percentage"},minSize:be,maxSize:xe,contentOverflow:"hidden"})]})]})},Oe=144,wt=Object.freeze(["e1","e2","e3","e4","e5","e6","e7","e8"]),Et=e=>{if(typeof e!="object"||e===null)return!1;const{generation:t,topLine:r}=e;return"state"in e&&typeof t=="number"&&typeof r=="number"},bt=e=>{e.stopPropagation()},xt=e=>{const{path:t,name:r,session:o}=e,{edits:a,labels:s,announcer:l}=x.useExplorer(),{phase:n}=o,h=p.useCallback(()=>a.retry(t),[a,t]);switch(p.useEffect(()=>{n.kind==="failed"&&l.announce(s.documentFailed(r,x.failureTitleOf(s,n.failure.reason)))},[n,l,s,r]),n.kind){case"opening":return L.jsxs(L.Fragment,{children:[L.jsx("div",{className:"aqmx-skeleton","aria-hidden":"true","data-testid":"markdown-explorer-edit-skeleton",children:wt.map(f=>L.jsx("span",{},f))}),L.jsx("p",{className:"aqmx-sr-only",children:s.editLoading})]});case"grant":return L.jsx("div",{className:"aqmx-edit-message",children:L.jsx(x.EditGrantNotice,{href:n.href,onRetry:h,testId:"markdown-explorer-edit-grant"})});case"failed":return L.jsx("div",{className:"aqmx-edit-message",children:L.jsx(x.FailureView,{failure:n.failure,alert:!1,onRetry:h,testId:"markdown-explorer-edit-failure"})});case"editing":return L.jsx(St,{...e})}},St=({path:e,name:t,session:r,layout:o,viewer:a,region:s,paneScroll:l})=>{const{edits:n,labels:h}=x.useExplorer(),f=p.useRef(null),i=p.useId(),u=p.useRef(null),c=p.useRef(null),g=p.useRef(null),m=o==="fill",S=x.useSideBySide(),v=x.editViewOf(r,S,m),k=v!=="editor"||r.previewPrepared,O=k&&m,A=p.useRef({layout:o,region:s,paneScroll:l});p.useLayoutEffect(()=>{A.current={layout:o,region:s,paneScroll:l}});const j=p.useRef(r.generation);p.useLayoutEffect(()=>{j.current=r.generation});const D=p.useRef({view:v,previewMounted:k});p.useLayoutEffect(()=>{D.current={view:v,previewMounted:k}});const V=p.useRef(null),H=p.useRef(null),b=p.useRef(!1),T=p.useMemo(()=>({editor:h.editorLabel(t),useOurs:h.conflictUseOurs,useTheirs:h.conflictUseTheirs,keepBoth:h.conflictKeepBoth}),[h,t]),q=p.useCallback(d=>{const{region:E,paneScroll:R}=A.current,M=E();return M===null?d:R.scrollerOf(M,d)},[]);p.useLayoutEffect(()=>{const d=f.current,E=n.draft(e);if(d===null||E===null)return;const R=n.editorState.get(e),M=Et(R)&&R.generation===j.current?R:null;let C=null,U=null;const te=()=>{C!==null&&clearTimeout(C),C=null,U!==null&&n.setDraft(e,U.text())},F=ze({parent:d,scroll:{scrollerOf:N=>{const{layout:J,region:Ie,paneScroll:Me}=A.current,le=Ie();return J==="fill"||le===null?N:Me.scrollerOf(le,N)},reveal:N=>A.current.paneScroll.reveal(N)},text:E,saved:M===null?void 0:M.state,labels:T,onGeometry:N=>g.current?.editorChanged(N),onChange:()=>{C??=setTimeout(te,Oe),D.current.previewMounted&&U!==null&&c.current?.draft(U.text())},onSave:()=>{n.save(e)}});U=F,u.current=F;const ie=()=>{const N=F.topLine();return{line:N.line,clientTop:N.clientTop}},se=()=>c.current?.anchor(q)??null,Ae=n.bindEditor(e,{flush:te,adopt:N=>F.replaceText(N),returnPoint:()=>{const N=D.current.view==="preview"&&A.current.layout==="content"?se():null;return N===null?ie():{line:N.lines.first,clientTop:N.clientTop}},nextConflict:()=>D.current.view!=="preview"?F.nextConflict():F.conflicts().length===0?!1:(b.current=!0,n.setView(e,"editor"),!0),beforeView:N=>{if(A.current.layout==="fill")return;if(N==="preview"){V.current={to:"preview",point:ie()};return}const J=se();V.current=J===null?null:{to:"editor",anchor:J}}});return M!==null&&F.showLine(M.topLine),()=>{te(),n.editorState.set(e,{state:F.save(),generation:j.current,topLine:F.topLine().line}),Ae(),F.destroy(),U=null,u.current=null}},[n,e,T,q]);const{request:P}=r;p.useLayoutEffect(()=>{const d=u.current,E=n.draft(e);d===null||E===null||P===null||(P.anchor!==null&&d.reveal(x.positionInSource(E,P.anchor),P.anchor.clientTop),d.focus(),n.consumeRequest(e))},[n,e,P,T]),p.useLayoutEffect(()=>{v!=="editor"&&!r.previewPrepared&&n.preparePreview(e)},[n,e,v,r.previewPrepared]),p.useLayoutEffect(()=>{const d=V.current,E=H.current,R=b.current;V.current=null,H.current=null,b.current=!1;const M=u.current;if(d?.to==="preview")c.current?.place(d.point,q);else if(d?.to==="editor"&&M!==null){const C=n.draft(e);C!==null&&M.reveal(x.positionInSource(C,d.anchor),d.anchor.clientTop)}R?M?.nextConflict():E==="editor"?M?.focus():E==="preview"&&c.current?.focus()},[n,e,v,q]);const w=p.useCallback(()=>{const d=u.current;if(d===null)throw new Error("[markdown-explorer] the preview read the draft before the editor was mounted");return d.text()},[]);p.useLayoutEffect(()=>{const d=u.current;if(!O||d===null)return;const E=it({editor:qe(d.scrollElement),preview:()=>c.current?.scrollPort()??null,previewBlocks:()=>c.current?.blocks()??[],editorSpans:R=>d.lineSpans(R),requestFrame:R=>requestAnimationFrame(R),cancelFrame:R=>cancelAnimationFrame(R),now:()=>performance.now()});return E.showAlone(x.paneShownAlone(D.current.view)),g.current=E,()=>{E.dispose(),g.current=null}},[O,n,e,T]),p.useLayoutEffect(()=>{g.current?.showAlone(x.paneShownAlone(v))},[v]);const B=p.useCallback(()=>g.current?.previewChanged(),[]),z=p.useCallback(d=>n.start(e,d),[n,e]),y=d=>{if(d.key==="Escape"){x.consumeKey(d);return}if(!x.isEditViewShortcut(d.nativeEvent,x.isApplePlatform(navigator.platform)))return;x.consumeKey(d);const E=x.toggledEditView(v);H.current=E,x.chooseEditView(n,e,E,m)};return L.jsxs("div",{className:"aqmx-edit","data-aqmx-edit-layout":o,"data-aqmx-edit-view":v,"data-testid":"markdown-explorer-edit",onKeyDown:y,onDoubleClick:bt,children:[L.jsx("div",{ref:f,id:i,className:"aqmx-edit-editor","data-testid":"markdown-explorer-editor",inert:v==="preview",hidden:v==="preview"&&!m,...x.ALLOW_KEY_REPEAT}),v==="split"?L.jsx(vt,{editorId:i}):null,k?L.jsx(dt,{path:e,readDraft:w,viewer:a,concealed:v!=="editor"?null:m?"overlay":"removed",onEditAt:v==="preview"?z:void 0,onLayout:B,handleRef:c}):null]})};exports.DRAFT_WRITE_INTERVAL_MS=Oe;exports.default=xt;