@aiquants/markdown-explorer 0.35.0 → 0.37.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 (93) hide show
  1. package/CHANGELOG.md +165 -0
  2. package/README.md +105 -13
  3. package/dist/{EditSurface-D2j1kCEE.js → EditSurface-BQgwRUrR.js} +250 -245
  4. package/dist/EditSurface-Xvk5wZu7.cjs +6 -0
  5. package/dist/ExplorerSplit-C_3FChSt.cjs +2 -0
  6. package/dist/ExplorerSplit-C_kaEnyM.js +1619 -0
  7. package/dist/{MultiLayout-CxV5SI7f.cjs → MultiLayout-BZNj1GYo.cjs} +1 -1
  8. package/dist/{MultiLayout-BeJ5Lubb.js → MultiLayout-DROxkTdD.js} +24 -24
  9. package/dist/{NativeScrollBar-RWXpVhbI.cjs → NativeScrollBar-BDF9A1sc.cjs} +1 -1
  10. package/dist/{NativeScrollBar-BM5NULzg.js → NativeScrollBar-DvdOpwIW.js} +2 -2
  11. package/dist/TreeLayout-Cc-ykewY.js +103 -0
  12. package/dist/TreeLayout-D_DYV64_.cjs +1 -0
  13. package/dist/client/MarkdownExplorer.d.cts +4 -5
  14. package/dist/client/MarkdownExplorer.d.ts +4 -5
  15. package/dist/client/hostContract.d.cts +1 -8
  16. package/dist/client/hostContract.d.ts +1 -8
  17. package/dist/core/config.d.cts +6 -0
  18. package/dist/core/config.d.ts +6 -0
  19. package/dist/core/contracts.d.cts +21 -0
  20. package/dist/core/contracts.d.ts +21 -0
  21. package/dist/core/dataRoute.d.cts +5 -1
  22. package/dist/core/dataRoute.d.ts +5 -1
  23. package/dist/core/documentId.d.cts +6 -0
  24. package/dist/core/documentId.d.ts +6 -0
  25. package/dist/core/labels.d.cts +10 -9
  26. package/dist/core/labels.d.ts +10 -9
  27. package/dist/core/location.d.cts +21 -0
  28. package/dist/core/location.d.ts +21 -0
  29. package/dist/explorerCore-DivWkFQF.cjs +1 -0
  30. package/dist/explorerCore-EkU0mwdW.js +1085 -0
  31. package/dist/index-BmOU3xcK.cjs +18 -0
  32. package/dist/{index-C1YMH-yI.js → index-dtjghDWY.js} +2647 -2466
  33. package/dist/index.cjs +1 -1
  34. package/dist/index.d.cts +3 -2
  35. package/dist/index.d.ts +3 -2
  36. package/dist/index.js +49 -45
  37. package/dist/location-Dh6K-y7w.js +761 -0
  38. package/dist/location-DrOP6t1F.cjs +1 -0
  39. package/dist/{merge-DQUYEGCx.cjs → merge-BCFCL1cF.cjs} +1 -1
  40. package/dist/{merge-Bb_HpPhe.js → merge-DC_h-t31.js} +1 -1
  41. package/dist/ownUrls-BTPGNhBt.cjs +1 -0
  42. package/dist/ownUrls-DD0cSCsF.js +409 -0
  43. package/dist/{sanitizeJob-BYRk17nr.js → sanitizeJob-BYqzjFJC.js} +1 -1
  44. package/dist/{sanitizeJob-Cs9o3Vpl.cjs → sanitizeJob-CudE1RUP.cjs} +1 -1
  45. package/dist/{sanitizePolicy-CiQfnxyd.cjs → sanitizePolicy-C-ehd0J_.cjs} +1 -1
  46. package/dist/{sanitizePolicy-CEMdaLUB.js → sanitizePolicy-DAPnUUVm.js} +1 -1
  47. package/dist/sanitizeWorker.cjs +1 -1
  48. package/dist/sanitizeWorker.js +3 -3
  49. package/dist/{sanitizerService-KWXv7bPm.js → sanitizerService-B8v4ap9t.js} +1 -1
  50. package/dist/{sanitizerService-BY4CPCoA.cjs → sanitizerService-DomN7lwC.cjs} +1 -1
  51. package/dist/server/anonymous.d.cts +2 -2
  52. package/dist/server/anonymous.d.ts +2 -2
  53. package/dist/server/errors.d.cts +1 -1
  54. package/dist/server/errors.d.ts +1 -1
  55. package/dist/server/ports.d.cts +24 -2
  56. package/dist/server/ports.d.ts +24 -2
  57. package/dist/server.cjs +1 -1
  58. package/dist/server.d.cts +1 -1
  59. package/dist/server.d.ts +1 -1
  60. package/dist/server.js +16 -16
  61. package/dist/serverBrowser.cjs +1 -1
  62. package/dist/serverBrowser.js +3 -3
  63. package/dist/serverCore.cjs +1 -1
  64. package/dist/serverCore.d.cts +1 -1
  65. package/dist/serverCore.d.ts +1 -1
  66. package/dist/serverCore.js +4 -4
  67. package/dist/styles/markdown-explorer.css +1 -1
  68. package/dist/{tapScrollCircle-BEydRn0y.js → tapScrollCircle-CqMZzWjo.js} +1 -1
  69. package/dist/{tapScrollCircle-DdX0Wri0.cjs → tapScrollCircle-DVNlszeF.cjs} +1 -1
  70. package/dist/testing.cjs +1 -1
  71. package/dist/testing.d.cts +5 -0
  72. package/dist/testing.d.ts +5 -0
  73. package/dist/testing.js +80 -2
  74. package/dist/{useSplitPersistence-B2Fj508K.cjs → useSplitPersistence-BUa_KMsV.cjs} +1 -1
  75. package/dist/{useSplitPersistence-Fkqak8G8.js → useSplitPersistence-pnb21dsr.js} +1 -1
  76. package/docs/behavior/dom-hooks.md +11 -2
  77. package/docs/behavior/hosting.md +1 -1
  78. package/docs/behavior/localization.md +2 -2
  79. package/docs/behavior/security.md +24 -3
  80. package/docs/behavior/url-contract.md +26 -0
  81. package/package.json +6 -4
  82. package/dist/EditSurface-CLG70Vnn.cjs +0 -6
  83. package/dist/ExplorerSplit-CfP1smbT.js +0 -1589
  84. package/dist/ExplorerSplit-D_0VohOv.cjs +0 -2
  85. package/dist/TreeLayout-AxLw-36S.js +0 -103
  86. package/dist/TreeLayout-Bg2YH-EY.cjs +0 -1
  87. package/dist/explorerCore-DLpDuSev.js +0 -998
  88. package/dist/explorerCore-DYrxS9ez.cjs +0 -1
  89. package/dist/index-LQWQfpAf.cjs +0 -18
  90. package/dist/location--KvTA0Ri.js +0 -726
  91. package/dist/location-D8DyDkuA.cjs +0 -1
  92. package/dist/ownUrls-B259RGgd.cjs +0 -1
  93. package/dist/ownUrls-Dh5g6ZJi.js +0 -370
package/CHANGELOG.md CHANGED
@@ -1,5 +1,170 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ ### Breaking
6
+
7
+ - **Access failures go to the host's presenter (`accessFailure`, required; hosts, readers).** `<MarkdownExplorer>`
8
+ takes `accessFailure`, an `AccessFailurePresenter<ReactNode>` of `@aiquants/auth-core` (a new peer, `^0.8.0`), and
9
+ words neither `unauthorized` nor `forbidden` itself any more: each place that meets one (a document, the tree and
10
+ its refresh, a folder's children, a document's refresh, its source, the editor's text, a revision, the server's
11
+ preview of a draft, a save, Copy permalink's ID) hands the presenter an occurrence
12
+ `{ kind, place, deniedSentence, retry }` and draws the node it returns inside the place's own hooks. A place hands
13
+ the same frozen occurrence for as long as it shows the same failure; `retry` repeats the place's work once the reader
14
+ is signed in again (`null` for Copy permalink and the preview), and `deniedSentence` is `null` except for the
15
+ `forbidden` answer of an ID URL, which carries `documentIdForbidden`. The explorer's announcer says nothing of an
16
+ access failure, since the presenter's node speaks for itself. Anything but a function throws a `TypeError` at the
17
+ first render. Migration: pass a presenter, for example one that draws auth-core's
18
+ `accessFailureView(occurrence, { keepsWork: true }, resolveAccessFailureLabels(locale))` (the README's quick start
19
+ and [Access failures](README.md#access-failures)).
20
+ - **The props for a session that ended are gone (hosts).** `onReload`, `onSessionEnded` and `accountState` are no longer
21
+ read, and `EXPLORER_ACCOUNT_STATES` and `ExplorerAccountState` are no longer exported. Migration: drop them; signing
22
+ in again is the presenter's action, after which it calls the occurrence's `retry`.
23
+ - **Nine label keys are removed (hosts).** `failureUnauthorizedTitle`, `failureUnauthorizedBody`,
24
+ `failureUnauthorizedSignInBody`, `failureUnauthorizedSignedOutBody`, `failureForbiddenTitle`, `failureForbiddenBody`,
25
+ `reloadPage`, `signInAgain` and `signIn`: the catalogs hold no words for an access failure, and `labels` that names
26
+ one throws, as for any unknown key. Migration: drop them from `labels` and word access failures in the presenter.
27
+ - **`signedOutPage` takes `{ request, url }` (hosts).** Its first argument is the new `ExplorerPageRouteArgs`: the
28
+ request and the URL React Router normalized for the loader (without the single-fetch `.data` suffix and `_routes`),
29
+ so `url.pathname + url.search` is the page to return to after sign-in on a client navigation too, where
30
+ `request.url` names the `.data` request. Migration: `signedOutPage: ({ request, url }, headers) => …`;
31
+ `anonymousAccess` follows.
32
+ - **`forbiddenPage` is removed: a forbidden reader gets auth-core's refusal (hosts).** For a reader `authenticate`
33
+ answers `forbidden` for, the page loader throws `accessFailureResponse("forbidden")` with the authentication's
34
+ headers: a 403 whose body is `{ "accessFailure": "forbidden" }` and whose `Cache-Control` is `no-store` (the
35
+ explorer's own 403 carried `private, no-store`), for the page route's error boundary. The exported `headers` carry
36
+ that `Cache-Control` to the HTML document and the single-fetch data while the page route has its own
37
+ `ErrorBoundary`; the `Content-Type` stays the entry's and React Router's. auth-core throws a `TypeError` when the
38
+ authentication's headers set `Content-Type` or `Cache-Control`. Migration: remove `forbiddenPage`, and draw the
39
+ refusal in the page route's `ErrorBoundary` with the presenter:
40
+ `accessFailureKindOfStatus(error.status)` of an `isRouteErrorResponse` error, as the occurrence
41
+ `{ kind, place: "page", deniedSentence: null, retry: null }`.
42
+
43
+ ### Changed
44
+
45
+ - **Every hook that carries `data-aqmx-failure` keeps it for an access failure (hosts).** The element holds the
46
+ presenter's node instead of the explorer's callout: no callout, tone, role or text of the explorer's, whatever it
47
+ holds for the explorer's own reasons (`markdown-explorer-refresh-failure` and `markdown-explorer-tree-failure` are no
48
+ `role="alert"` then). A host's `renderTreeFailure` still replaces what the tree failure holds, and `undefined` keeps
49
+ the presenter's node. `data-aqmx-tone` stays `danger` for `failed` and `warning` for the other reasons of the
50
+ explorer's own.
51
+ - **The ID URL a reader may not open (readers).** Its failure is the presenter's node, with `documentIdForbidden` as the
52
+ sentence of what was denied, instead of a callout whose body that label was.
53
+ - **A save or a Copy permalink press refused by an access failure (readers).** A save leaves the status of the unsaved
54
+ draft (`draftUnsaved`, with `data-aqmx-save="failed"`) and shows the presenter's node below the bar's row
55
+ (`markdown-explorer-save-access-failure`), whose retry saves again without asking `confirmUnversionedSaves` again.
56
+ A permalink press shows its node in the bar (`markdown-explorer-permalink-access-failure`) and is not announced: the
57
+ button stays `idle`, the node shows the latest press's failure only, and it goes at the next press and when the bar
58
+ moves to another document, while the document is edited it is hidden, and it is drawn again (a new occurrence) once
59
+ the editing ends.
60
+
61
+ ### Added
62
+
63
+ - **One node for the lazy folders an access failure stops (readers).** The folders whose children meet an access
64
+ failure, one after another, share one node of the presenter above the tree
65
+ (`markdown-explorer-folder-access-failure`, the place `read`), one occurrence while any of them stays stopped, whose
66
+ retry loads them all again; the node goes once none is stopped. The rows keep `data-aqmx-children="failed"` and their
67
+ Try again, the announcer names none of the folders, and the end of an Expand all press counts them among the folders
68
+ that could not be loaded, so the folders one press stops at once share one node that speaks once.
69
+ - **Access failures behind the open sheet move into it (readers).** While the explorer's sheet is open (a native modal
70
+ `dialog` on a frame too narrow for the split, so the content behind it is inert and hidden from assistive
71
+ technology), the content's access failures are drawn at the top of the explorer inside the sheet, in the order they
72
+ came (`markdown-explorer-sheet-access-failures`), and nothing behind it; once the sheet closes each node goes back to
73
+ its place with the same occurrence.
74
+
75
+ ## 0.36.0 (2026-11-12) — Document IDs: a permalink that keeps opening its document when the document's path changes
76
+
77
+ ### Breaking
78
+
79
+ - **Two exported types gain what document IDs add (hosts, types only).** `ExplorerLocationResult` (what
80
+ `resolveExplorerLocation` answers) has a third kind, `{ kind: "document-id", id, opens, location }`, which the
81
+ resolver answers only with `documentIds` in the configuration: a host that switches over `kind` exhaustively needs a
82
+ case for it (its `location` is the one to draw meanwhile). `ExplorerPageData` carries a required `documentId`, `null`
83
+ on every page but an ID URL's that does not open (the explorer's loader writes it): a host that builds page data
84
+ itself, for its own tests for example, adds `documentId: null`. Without `documentIds` nothing changes at run time.
85
+
86
+ ### Added
87
+
88
+ - **Document IDs and their URLs (hosts, readers).** With `documentIds: { slug }` in `defineExplorerConfig`,
89
+ `{basePath}/{slug}/{ID}` opens the document an ID names in the tree view and `{basePath}/{slug}/{ID}/{views.single}`
90
+ in the single view, with the URL's `style` and `align` and, in the single view, its embedding parameters. The slug
91
+ follows the view slugs' rule and differs from every view slug and from `dataPath`'s first segment under `basePath`;
92
+ without the option it stays an unknown view slug.
93
+ The page loader answers an ID the reader can open with a `302` to the document's path URL, under the source that
94
+ admits it, with `Cache-Control: private, no-store` (never `301` or `308`, which a browser keeps while the path an ID
95
+ names changes when its document moves), and any other ID with the page of the default source's tree,
96
+ `documentId: { id, failure }` in the page data and the failure's status (`invalid` 400 for an ID written wrong,
97
+ `not-found` 404, `forbidden` 403, `failed` 500), never naming the path. A navigation inside the explorer to an ID URL
98
+ shows the document's skeleton, resolves the ID through the data route's new `resolve-id` operation and replaces the
99
+ URL with the path URL, keeping its fragment; a failure shows in the document's place
100
+ (`markdown-explorer-document-id-failure`, with `data-aqmx-failure`), with Try again for `failed` only.
101
+ - **The ID (hosts).** 12 symbols of Crockford's Base32: 11 random symbols the server draws from Web Crypto and a mod-37
102
+ check symbol, kept inside the alphabet by drawing again a body whose remainder is 32 or more. `DOCUMENT_ID_ALPHABET`,
103
+ `DOCUMENT_ID_LENGTH`, `isCanonicalDocumentId` (the canonical form), `parseDocumentId` (a reader's writing: hyphens,
104
+ lowercase, `I`, `L` and `O`; a character outside ASCII is refused before any case is raised) and `groupDocumentId`
105
+ (`7K3M-9QX2-AB4W`) are exported from `.`; `explorerHref` writes an ID URL from
106
+ `{ view: "document-id", id, opens?, overrides?, embed? }`, and `ExplorerDocumentIdOpening` names how the document
107
+ opens. `documentIdVectors()` and `DocumentIdVector` of `./testing` list the answers `parseDocumentId` owes, for a
108
+ host's registry and for an implementation of the rule in another language.
109
+ - **Copy permalink (readers).** With `documentIds`, the bar of a document that is not edited offers Copy permalink after
110
+ Refresh document, from the server's render on and unavailable (`aria-disabled`) while the document loads or failed,
111
+ so the bar's buttons keep their places: a press asks the new `issue-id` operation for the document's ID
112
+ (issued on the first press, the same ID ever after) and copies its ID URL, absolute and with the router's basename,
113
+ in the form of the current view (the single view's with its overrides and embedding parameters, the tree view's with
114
+ its overrides, a multi-view panel's as the tree view's). The write starts inside the press, as Safari requires, with
115
+ a `ClipboardItem` whose text the ID URL fulfils, and the outcome is announced and shown as the other copies' are,
116
+ with the ID grouped or with why nothing was copied (`markdown-explorer-document-permalink`,
117
+ `data-aqmx-copy-outcome`). New labels, in English and Japanese: `copyPermalink`, `copyPermalinkLabel`,
118
+ `copyPermalinkNamed`, `permalinkCopied`, `permalinkCopyFailed`, `permalinkClipboardRefused`,
119
+ `documentIdFailedTitle`, `documentIdInvalid`, `documentIdNotFound` and `documentIdForbidden`.
120
+ - **The registry of document IDs (hosts).** `createMarkdownExplorer` takes `documentIds`
121
+ (`ExplorerDocumentIdPorts`) exactly when the configuration has `documentIds` (either alone throws a `TypeError`):
122
+ `issue(context, path, candidate)` answers an `ExplorerDocumentIdIssue` (`issued`, `existing` with the path's ID, or
123
+ `taken`) and `resolve(context, id)` an `ExplorerDocumentIdBinding` (`bound` with a path, or `unbound`). The explorer
124
+ draws every candidate (up to 4 per issue), checks the reader before it calls a port — the deny rules, the sources'
125
+ boundaries and the document's existence through `asset`, without opening its bytes —, hands the registry the
126
+ document path (never a source's `readPath`), and checks every answer: a broken one is logged and answered `failed`.
127
+ `issue-id` (`POST`) needs `X-Markdown-Explorer: document-id` and the cross-origin check of a refresh, before the
128
+ reader is authenticated; `resolve-id` (`GET`, `HEAD`) takes the canonical form only. Unlike a document request, both
129
+ answer a failure with its own status, and without the ports both answer as unknown operations (404).
130
+
131
+ ### Tests
132
+
133
+ - `tests/unit/documentId.test.ts`: the ID's alphabet, the drawing (the redraw of a body whose check value is 32 or
134
+ more included), the canonical check, the lenient reading and the grouping, against the table of
135
+ `tests/fixtures/document-id-vectors.json` that `./testing` ships.
136
+ - `tests/server/documentIdOperations.test.ts` (a runtime-independent suite): the ports' assembly, `issue-id` (the
137
+ method, the proof and the cross-origin check before authentication, the path checks before the registry, the
138
+ `readPath` the registry never sees, the redraw of `taken` candidates and its limit, broken answers, `ExplorerError`
139
+ and other exceptions), `resolve-id` (the method, canonical IDs only, the disclosure table, broken bindings) and the
140
+ page loader's redirects and failure pages.
141
+ - `tests/components/documentIdUrl.test.tsx` (an ID URL inside the explorer: the skeleton, the replacing navigation
142
+ that keeps the fragment, the failures and their Try again, the cancellation on a change of URL, the failures the
143
+ loader answered), `tests/components/documentPermalink.test.tsx` (Copy permalink: when the bar holds it and when it
144
+ is unavailable, its names, the write inside the press, the forms of the three views and the basename, the issue's
145
+ failure and the browser's refusal, the latest press deciding) and
146
+ `tests/components/documentPermalinkHydration.test.tsx` (the unavailable button the server draws while the document
147
+ streams, the hydration without a mismatch or a request, and the same button acting once the document opens, with the
148
+ served buttons keeping their order at the row's end).
149
+ - `location`, `settings`, `labels`, `dataClient` and `entryPurity` cover the ID URLs, the `documentIds` option, the new
150
+ labels, the client's `issueId` and `resolveId`, and the `./testing` entry's second table.
151
+ - `tests/e2e/document-ids.spec.ts` (Chromium), on the demo's registry of document IDs (`demo/app/document-ids.server.ts`,
152
+ which the demo's `/docs` explorer now has under `/docs/d/<ID>`): Copy permalink through the real clipboard, the
153
+ loader's `302` with `private, no-store` in the tree and single views with the fragment kept, and the pages of an ID
154
+ written wrong, one no document has and one bound to a path no source admits (the status, the failure in the
155
+ document's place, no second request, no Copy permalink, no path).
156
+
157
+ ### Documentation
158
+
159
+ - README: `documentIds` in the configuration, the ID URLs in Views and URLs, the `documentIds` ports in the Server API
160
+ table, a Document IDs section (issue, resolve, the answers' checks, erasing and moving), the security model and the
161
+ demo's registry.
162
+ - `docs/behavior/url-contract.md`: the ID URLs in the shape and canonical-form tables and a Document IDs section (the
163
+ ID, writing and reading, the page loader, the browser, Copy permalink). `docs/behavior/security.md`: a Document IDs
164
+ section (an ID is not a permission, the disclosure table, `resolve-id`, `issue-id`, the answers' checks), the ID
165
+ operations' statuses, and what the host's registry must keep. `docs/behavior/dom-hooks.md`:
166
+ `markdown-explorer-document-permalink` and `markdown-explorer-document-id-failure`.
167
+
3
168
  ## 0.35.0 (2026-11-10) — The server half runs in the page on a browser runtime, a host drives the explorer through props and a handle, and each document carries its language
4
169
 
5
170
  ### Breaking
package/README.md CHANGED
@@ -50,7 +50,7 @@ A single-view (embedding) page never downloads the tree and multi-panel views, w
50
50
 
51
51
  - React 19.2.7 or later and React Router 8 in framework mode (route modules with `loader` / `headers`).
52
52
  - Node.js 22.22 or later (the floor React Router 8 declares). The package ships ES modules and CommonJS; the CommonJS entries load the ESM-only `react-router` through `require(esm)`.
53
- - The peer packages, at these versions or later within the caret ranges the package declares: `@aiquants/markdown` ^13.0.0 (document rendering;
53
+ - The peer packages, at these versions or later within the caret ranges the package declares: `@aiquants/auth-core` ^0.8.0 (the access failure contract: the occurrence the host's presenter draws, and the 403 refusal of the page loader, `accessFailureResponse`), `@aiquants/markdown` ^13.0.0 (document rendering;
54
54
  the column width and colour pair a reader picks in its display popover (`CONTENT_MEASURES` and `CONTENT_COLORS` of `@aiquants/markdown/viewer-settings`) and the labels of the popover's sections and of a diagram's notices, a document's language for its content (`contentLang`) apart from the UI language of the labels the explorer passes (`labelsLang`), and the size of a document table's tap-scroll circle (`spreadsheetTapScrollCircle`'s `size`);
55
55
  the gutter its scroll container keeps beside the explorer's bar for the tap-scroll circle (`scrollBarGutter`, given as a custom property that a media query sets), code blocks whose Copy button sits in a header row above the code, and documents whose front matter does not render; the Source toggle of a storage SVG image that stands alone in a paragraph, read through `imageSource`, and a Copy that copies the image as a PNG image or its source, the source readable in every display style, a notice in place of a block that cannot render and plain text for a fence in a language it does not know;
56
56
  the full screen of its tables, Mermaid diagrams and SVG images, which every block marks with the same DOM hook (`data-aqmd-fullscreen`), and `DEFAULT_MARKDOWN_STYLE`, the style a document starts in by default; its components' stylesheet without utilities,
@@ -75,7 +75,7 @@ A single-view (embedding) page never downloads the tree and multi-panel views, w
75
75
  ## Installation
76
76
 
77
77
  ```bash
78
- pnpm add @aiquants/markdown-explorer @aiquants/markdown @aiquants/directory-tree @aiquants/drag-drop-panels @aiquants/resize-panels @aiquants/virtualscroll
78
+ pnpm add @aiquants/markdown-explorer @aiquants/auth-core @aiquants/markdown @aiquants/directory-tree @aiquants/drag-drop-panels @aiquants/resize-panels @aiquants/virtualscroll
79
79
  ```
80
80
 
81
81
  The package's entries are `@aiquants/markdown-explorer` (the browser half: `<MarkdownExplorer>`, the shared configuration and links), `@aiquants/markdown-explorer/server` (the server half on Node), `@aiquants/markdown-explorer/storage` (`clearExplorerStorage` only, with no dependencies), `@aiquants/markdown-explorer/testing` (the answers the deny rules owe, for tests) and the stylesheet `@aiquants/markdown-explorer/styles/markdown-explorer.css`.
@@ -106,9 +106,10 @@ The source ids are not part of it: they are the ids of the server's `sources` (a
106
106
  | Option | Type | Purpose |
107
107
  | --- | --- | --- |
108
108
  | `basePath` | `string` | Page mount, with a leading slash and no trailing slash (for example `/docs`). |
109
- | `dataPath` | `string` | Data route mount in the same form; it differs from `basePath` and does not start with a view slug under it. |
109
+ | `dataPath` | `string` | Data route mount in the same form; it differs from `basePath` and does not start with a view slug or `documentIds.slug` under it. |
110
110
  | `settingsCookie` | `string` | Name of the display-preference cookie (an RFC 6265 token). |
111
111
  | `views?` | `{ tree?, multi?, single? }` | URL slugs of the views; each defaults to its view's name. |
112
+ | `documentIds?` | `{ slug }` | Document IDs (see [Document IDs](#document-ids)): `slug` is the URL segment under `basePath` that opens a document by its ID (`{basePath}/{slug}/{ID}`), written as a view slug is (letters, digits, `_` and `-`, starting with a letter or digit) and unlike every view slug. The server then needs the `documentIds` ports, and without the option it takes none; none when omitted. |
112
113
  | `multiView?` | `{ maxPanels?, columns? }` | The panel limit (1–64, default 12) and the logical column count (1–6, default 4). |
113
114
  | `expandAll?` | `{ maxFolders?, maxDepth? }` | Expand all's budget per press (see [Expand all and Collapse all](#expand-all-and-collapse-all)): the folder listings a press may start (1–10,000, default 500, `EXPAND_ALL_FOLDER_LIMITS`) and the deepest level (the top being 1) at which it opens a folder of unknown contents (1–64, default 16, `EXPAND_ALL_DEPTH_LIMITS`). Each field defaults on its own, also when given as `undefined`; a value that is not an integer within its bounds or an unknown key throws a `RangeError` naming the field, and anything but a plain object a `TypeError`. |
114
115
  | `revealDocument?` | `{ maxDepth? }` | The deepest document whose folders the reader's "Reveal the open document" setting opens, counted in folders between the source's top level and the document (1–64, default 16, `REVEAL_DOCUMENT_DEPTH_LIMITS`); a deeper document is not revealed. Each folder of the chain takes at most one listing, so this also bounds a reveal's listings. The field defaults on its own, also when given as `undefined`; an unknown key throws a `RangeError`, anything but a plain object a `TypeError` (see [Revealing the open document](#revealing-the-open-document)). |
@@ -182,8 +183,10 @@ The base route (`docs`) must be registered as well as the splat: a client naviga
182
183
 
183
184
  ```tsx
184
185
  // app/routes/docs.tsx
186
+ import { accessFailureKindOfStatus } from "@aiquants/auth-core"
185
187
  import { MarkdownExplorer, shouldRevalidateExplorer } from "@aiquants/markdown-explorer"
186
188
  import { isRouteErrorResponse, useLoaderData, useRouteError } from "react-router"
189
+ import { presentAccessFailure } from "../access-failure"
187
190
  import { explorerConfig } from "../explorer.config"
188
191
  import { explorer } from "../explorer.server"
189
192
 
@@ -196,7 +199,7 @@ export default function Docs() {
196
199
  <div className="docs-page">
197
200
  <header>Handbook</header>
198
201
  <main className="docs-explorer">
199
- <MarkdownExplorer data={useLoaderData<typeof loader>()} config={explorerConfig} storageNamespace="docs" lockDocumentScroll />
202
+ <MarkdownExplorer data={useLoaderData<typeof loader>()} config={explorerConfig} storageNamespace="docs" accessFailure={presentAccessFailure} lockDocumentScroll />
200
203
  </main>
201
204
  </div>
202
205
  )
@@ -204,7 +207,54 @@ export default function Docs() {
204
207
 
205
208
  export function ErrorBoundary() {
206
209
  const error = useRouteError()
207
- return <p>{isRouteErrorResponse(error) && error.status === 403 ? "You cannot open these documents." : "Something went wrong."}</p>
210
+ const kind = isRouteErrorResponse(error) ? accessFailureKindOfStatus(error.status) : null
211
+ return kind === null ? <p>Something went wrong.</p> : presentAccessFailure({ kind, place: "page", deniedSentence: null, retry: null })
212
+ }
213
+ ```
214
+
215
+ ```tsx
216
+ // app/access-failure.tsx
217
+ import { type AccessFailureAction, type AccessFailurePresenter, accessFailureView, resolveAccessFailureLabels } from "@aiquants/auth-core"
218
+ import type { ReactNode } from "react"
219
+
220
+ const labels = resolveAccessFailureLabels("en")
221
+
222
+ const follow = (action: AccessFailureAction, retry: (() => void) | null): void => {
223
+ switch (action) {
224
+ case "retry":
225
+ retry?.()
226
+ return
227
+ case "back":
228
+ window.history.back()
229
+ return
230
+ case "top":
231
+ window.location.assign("/")
232
+ return
233
+ case "sign-in":
234
+ case "sign-in-again":
235
+ window.location.assign("/sign-in")
236
+ return
237
+ case "sign-in-again-in-new-window":
238
+ window.open("/sign-in", "_blank", "noopener")
239
+ }
240
+ }
241
+
242
+ // The explorer keeps the reader's unsaved drafts in the page, so it keeps work.
243
+ export const presentAccessFailure: AccessFailurePresenter<ReactNode> = (occurrence) => {
244
+ const view = accessFailureView(occurrence, { keepsWork: true }, labels)
245
+ return (
246
+ <div role={view.politeness}>
247
+ <p>{view.title}</p>
248
+ {view.sentences.map((sentence) => (
249
+ <p key={sentence}>{sentence}</p>
250
+ ))}
251
+ {view.actions.map(({ action, label }) => (
252
+ <button key={action} type="button" onClick={() => follow(action, occurrence.retry)}>
253
+ {label}
254
+ </button>
255
+ ))}
256
+ </div>
257
+ )
208
258
  }
209
259
  ```
210
260
 
@@ -217,7 +267,8 @@ export const action = explorer.dataAction
217
267
  ```
218
268
 
219
269
  - Take the content folder from configuration (an environment variable here), not from `import.meta.url`: after `react-router build` the server module runs from `build/server/index.js`, so a path relative to the module would point into `build/`.
220
- - The page route needs its own `ErrorBoundary`: React Router stops carrying `headers` at the boundary that renders an error, so without one the default 403 answer loses its `Cache-Control: private, no-store`.
270
+ - The explorer words no access failure itself, neither in the page nor around it: it hands each one to the presenter you pass as `accessFailure` (`@aiquants/auth-core`'s `AccessFailurePresenter`, here drawing auth-core's own view of the failure; see [Access failures](#access-failures)), and the page route's error boundary draws the page's own refusal with the same presenter. With `anonymousAccess` nobody is signed out, but a document outside every source still answers `forbidden`.
271
+ - The page route needs its own `ErrorBoundary`: React Router stops carrying `headers` at the boundary that renders an error, so without one the 403 refusal of a reader without access loses its `Cache-Control: no-store`.
221
272
  - The data route module must not have a default export; with one it becomes a UI route and the JSON answers are rendered as a page.
222
273
  - `shouldRevalidateExplorer` keeps React Router from running the page loader again on a submission, a move to another document, view or source (another path under the splat, another query) and a navigation that drops the hash; the unchanged URL (a `revalidate()` call, a link to the current page) keeps React Router's decision. It is built with `@aiquants/route-revalidation`.
223
274
  - The explorer adds no `main` landmark in any view (its own landmarks — the explorer `nav`, the document region, the multi view's columns — sit inside yours), so the page places it in its own `<main>`.
@@ -309,6 +360,7 @@ to; load it when your documents contain math.
309
360
  | Tree | `{basePath}/{tree}`, `{basePath}/{tree}/{document}` or `{basePath}/{tree}/{folder}/` | The source tree beside the selected document, or the selected folder's README |
310
361
  | Multi-panel | `{basePath}/{multi}?doc=…&doc=…&maximized=…&markup=…` | Several documents as panels in columns |
311
362
  | Single | `{basePath}/{single}/{document}` | One document over the whole frame (for reading and embedding) |
363
+ | Document ID | `{basePath}/{documentIds.slug}/{ID}` or `{basePath}/{documentIds.slug}/{ID}/{single}` | Nothing of its own: with `documentIds` in the configuration, it sends the reader to the path URL of the document its ID names, in the tree or the single view |
312
364
 
313
365
  - `?source=<id>` selects the tree's source among the server's sources; the first source is the default and is written by omission. Switching the source never closes open documents — a document path names one document whichever trees list it.
314
366
  - A document path occupies one URL segment. Build links with `explorerHref(config, target)`, the only function that writes explorer URLs; read them back with `resolveExplorerLocation(config, splat, search)`. Both need the server's source ids for the `source` parameter: pass a configuration joined with them, `withExplorerSources(config, sourceIds)` (`ExplorerLocationConfig`; `isExplorerSourceId` is the id rule, and an empty, invalid or repeated id throws a `RangeError`).
@@ -319,6 +371,8 @@ to; load it when your documents contain math.
319
371
  - `markup` names the Markdown documents, SVG images and table files shown as written (the Source toggle): `markup=true` for the tree or single view's document, and one `markup=<document>` per open document shown that way in the multi view, in the order of `doc`. In `ExplorerLocation` it is a boolean in the tree and single views and a list in the multi view; a target without it shows every document rendered.
320
372
  - `maximized` says what fills the page: `maximized=true` for the tree view's document or folder README (the Maximize button at the end of the document's bar; see [The maximized document](docs/behavior/layout.md#the-maximized-document)), and `maximized=<document>` for the open document whose panel is maximized in the multi view. In `ExplorerLocation` it is a boolean in the tree view and a document or `null` in the multi view; the single view, whose frame is the page already, has none.
321
373
  The tree view's maximize stays through a source switch and the document links and table-of-contents entries it follows (their hrefs never carry it); a pick in the tree and a switch between the views drop it.
374
+ - With `documentIds` in the configuration, a document's bar offers **Copy permalink** (unavailable while the document loads or failed), which copies the document's ID URL in the form of the current view: an ID the server issues on the first press (12 symbols of Crockford's Base32, such as `7K3M9QX2AB4W`) and the host's registry binds to the document's path, so the link keeps opening the document when its path changes,
375
+ for every reader who may open that path. Write such a link with `explorerHref(config, { view: "document-id", id, opens?: "single", overrides?, embed? })`; `resolveExplorerLocation` reads one as `{ kind: "document-id", id, opens, location }` (see [Document IDs](docs/behavior/url-contract.md#document-ids)).
322
376
  - History: a click in the tree replaces the URL's document or folder; links inside a document, entries of its table of contents (in the tree and single views, to the heading's hash), source switches and view switches push; every multi-view action, the Source toggle and the tree view's Maximize replace (hiding and showing a panel leave the URL unchanged).
323
377
  - An entry of a document's table of contents links to its heading's own address: the page's URL with the heading's fragment, or, in a multi-view panel, the panel's document in the tree view with that fragment, so a modified or middle click, a new tab or a copied address opens the heading (see [URL contract](docs/behavior/url-contract.md#table-of-contents)).
324
378
 
@@ -353,8 +407,7 @@ In the tree view a folder can be selected as GitHub's file tree does, and the vi
353
407
  | `sources` | `ExplorerSource<P>[]` | The sources in switcher order (at least one; the first is the default): `id` (lowercase letters, digits and `-`, starting with a letter or digit, unique; the URL's `source` value), `label` (a string, or a function of the principal), `boundary` (where the source's documents may lie, see [Source boundaries](#source-boundaries)), `tree(context)` (lists the source's roots), `children?(context, path, readPath)` for lazy folders (asked only while the tree shows the folder open — the reader opened it, Expand all opened it (a press keeps opening folders as their listings land, within `expandAll`), or a remembered expansion opened it — and only for a path inside the source's boundary; a listing no tree wants any more is aborted through `context.signal`, which the source should honour), `ancestors?(context, path, readPath, options)` (the folders down to a document, for the reader's reveal; see [Revealing the open document](#revealing-the-open-document)), `cacheScope?` (`"principal"`, the default, or `"shared"`). The `context` is described under [Entries and notices](#entries-and-notices). |
354
408
  | `document` | `(context, path, readPath) => Promise<ExplorerHostDocument>` | Resolves a document path. Called only for a path inside at least one source's boundary; `readPath` is what the admitting source's `confirm` answered (`path` when that source has no `confirm`), so read `readPath` and show the document as `path`. An image, media, text or file document reports its file's `version`; the explorer writes its URL (see [Documents](#documents)). |
355
409
  | `asset` | `(context, path, readPath, options) => Promise<ExplorerAssetFile \| ExplorerAssetRedirect>` | Finds the file behind the data route's `asset` operation (and its `text` operation, which reads a Markdown document's source through it): any regular file the document admission admits, whatever its kind. Called only after the path passed the deny rules and the same union admission as a document, with the same `readPath`; see [Serving files](#serving-files). `options.delivery` says what the explorer delivers of the file (`"file"`, `"text"` or `"workbook"`): with `"file"` it may answer a short-lived URL instead, see [Redirecting to the storage](#redirecting-to-the-storage), and with `"workbook"` a storage that converts the file on read delivers a workbook, see [Serving files](#serving-files). |
356
- | `signedOutPage` | `(request, headers) => Response` | The page response for a signed-out reader, usually a redirect to sign-in. Data requests answer 401 instead. |
357
- | `forbiddenPage?` | `(request, headers) => Response` | The page response for a reader without access (default: a 403 for the route's error boundary). |
410
+ | `signedOutPage` | `(args: ExplorerPageRouteArgs, headers) => Response` | The page response for a signed-out reader, usually a redirect to sign-in. `args` is `{ request, url }`: the request, and `url`, the page's URL normalized by React Router (without the `.data` suffix and the `_routes` parameter of a single-fetch request), the address to return to after signing in. `headers` holds the authentication's headers and `Cache-Control: private, no-store`. Data requests answer 401 instead. |
358
411
  | `notices?` | `(context) => Promise<ExplorerNotice[]>` | Callouts above the tree (a missing permission with a link that grants it, for example). |
359
412
  | `deny?` | `string[] \| false` | Segment patterns hidden from every listing and refused on every read (default `DEFAULT_DENIED_PATH_SEGMENTS`). |
360
413
  | `treeCache?` | `{ ttlMs?, maxEntries?, maxBytes? } \| false` | The server's tree cache, each limit defaulting on its own (5 minutes, 64 entries, 64 MiB of the trees' JSON, counted at two bytes per character). The time to live counts from the moment the tree's walk began, and an expired tree is never answered: a page load or tree request after it waits for one new walk, which every concurrent request shares. Each cached tree is also kept parsed beside its JSON, which `maxBytes` does not count; its share falls as names get longer and is higher for non-ASCII names (measured on trees of 20,000 entries: about 1.0 to 1.9 times the counted bytes for ASCII names of 40 down to 4 characters, 1.4 to 2.2 times for non-ASCII names), and a tree with any non-ASCII name keeps a two-byte JSON as large as its count, so plan for up to about 2.4 times `maxBytes` of memory per process with ASCII names and up to about 3.2 times with short non-ASCII names. `false` turns the cache off. |
@@ -363,6 +416,9 @@ In the tree view a folder can be selected as GitHub's file tree does, and the vi
363
416
  | `textMaxBytes?` | `number` | The most bytes of a file the data route's `text` operation reads and answers (a positive integer up to 256 MiB; default 2 MiB): a longer file answers its beginning, marked truncated. The explorer shows a Markdown document's source with it, so a host that renders larger Markdown sets it to its own source limit. |
364
417
  | `logger?` | `{ error(message, detail) }` | Where adapter failures and malformed source output are reported (default `console.error`). A tree or children entry with an empty name, or with a path the browser cannot address (empty, too long, a lone surrogate, a control character or a backslash — for example macOS's `Icon\r`), or outside its source's boundary, is left out together with its subtree and reported with the message `[markdown-explorer] <operation> left out an entry` and the detail `{ operation, sourceId, path, error }`, whose `error` names the reason; any other malformed listing becomes `failed`. A boundary that throws or answers malformed values is reported with the operation `boundary`, and so is the rejection of a promise a `contains` answers (it is not awaited and counts as outside). A failed authentication of a data request is reported with the operation `authenticate` and never quotes a header: `headers` that `Headers` cannot read are reported by a fixed message, and a `Response` that `authenticate` throws (React Router's `throw redirect(...)`) by its status alone; any other exception of your adapters is logged as thrown, so keep secrets out of it. |
365
418
  | `onTreeRefreshed?` | `(key: string) => void` | Called once per tree refresh, after its reload settled (whatever its result) unless the request went away, with the refreshed tree's cache key (opaque). A multi-process host relays the key to its other processes, which call `forgetTree(key)` (see [Hosting notes](#hosting-notes)). Its return value is ignored, but a promise it returns (an asynchronous relay) is observed, never awaited: a throw, or the rejection of that promise, is logged with the operation `refresh` and does not change the response. |
419
+ | `documentIds?` | `ExplorerDocumentIdPorts<P>` | The registry of document IDs, `{ issue, resolve }` (see [Document IDs](#document-ids)): given exactly when the configuration has `documentIds` (either alone throws a `TypeError`, as does a value that is not an object of the two functions). |
420
+
421
+ A reader `authenticate` answers `forbidden` for is refused by the page loader with `@aiquants/auth-core`'s refusal, `accessFailureResponse("forbidden")` thrown with the authentication's headers: a 403 whose body is `{ "accessFailure": "forbidden" }` and whose `Cache-Control` is auth-core's `no-store`, for the page route's error boundary (React Router reads the body into the error's `data`). Data requests answer 403 instead.
366
422
 
367
423
  It returns `{ loader, headers, dataLoader, dataAction, planData, forgetTree }`. `planData` plans a data request for a host that streams a file's bytes itself (see [Streaming files yourself](docs/behavior/hosting.md#streaming-files-yourself)).
368
424
  `forgetTree(key)` drops this process's cached tree for a key another process refreshed and supersedes a load of it that already began (its waiting requests still receive that tree, which is not kept); it starts no load and throws a `TypeError` for a non-string key. Export `headers` from the page route: it carries the loader's `Cache-Control: private, no-store` to both the HTML and the single-fetch responses.
@@ -523,6 +579,28 @@ editMaxBytes: 2 * 1024 * 1024, // the largest source and draft, the default
523
579
  - **Source lines.** The editor opens at the place the reader was reading, or at the word they double-clicked, and the editor and the preview scroll together block by block, through the source lines your converter writes on every block: `data-source-lines="<first>-<last>"` (1-based, both inclusive), `@aiquants/markdown`'s `includeSourceLines`. Without them the editor opens at the start of the document and the two panes scroll together in proportion alone, top with top and bottom with bottom; the sanitizer keeps the attribute only in that form.
524
580
  A ```spreadsheets table needs its source lines to be editable in the preview, and its options need the info string after the language as `data-code-meta` on the `code` element, as `@aiquants/markdown`'s converter writes it.
525
581
 
582
+ ### Document IDs
583
+
584
+ With `documentIds: { slug }` in the configuration, give `createMarkdownExplorer` the registry of document IDs as `documentIds` (`ExplorerDocumentIdPorts`). The registry only records and reads bindings of an ID to a document path: the explorer draws every candidate, checks the reader before it calls a port, and checks every answer.
585
+
586
+ ```ts
587
+ documentIds: {
588
+ // Bind the candidate to the path atomically, unless the path already has an ID or the candidate is another path's
589
+ issue: async (context, path, candidate) => ({ kind: "issued" }), // or { kind: "existing", id } / { kind: "taken" }
590
+ // The path an ID (in its canonical form) is bound to
591
+ resolve: async (context, id) => ({ kind: "bound", path }), // or { kind: "unbound" }
592
+ },
593
+ ```
594
+
595
+ - **Issue.** The data route's `issue-id` operation (`POST <dataPath>/issue-id?path=`, which Copy permalink sends with `X-Markdown-Explorer: document-id` and which passes the cross-origin check of a refresh) calls `issue` only for a document the reader can open now — after the deny rules, the document admission and a check through `asset` that the document exists — with the document path (never the source's `readPath`) and a candidate in its canonical form.
596
+ Answer `issued` when you bound the candidate, `existing` with the path's ID when it already has one, and `taken` when the candidate is another path's ID: the explorer draws another, up to 4 candidates. Keep the bindings unique both ways (a unique key on the ID and on the path) and the binding atomic, so two readers pressing Copy permalink at once get one ID: one `issued`, the other `existing`.
597
+ A registry may bind every spelling of one document as one (its canonical spelling, such as the URI your storage records the document under): `issue` then answers `existing` for any spelling of a document that has an ID, and `resolve` answers the canonical spelling, which the explorer checks as it checks any path.
598
+ - **Resolve.** The page loader for an ID URL, and the `resolve-id` operation (`GET <dataPath>/resolve-id?id=`) the browser asks for one reached without the loader, call `resolve` with an ID in its canonical form: answer `bound` with its path, or `unbound` for an ID never issued or forgotten.
599
+ The explorer then checks the path as it checks a document's and sends the reader to its path URL (a `302` from the loader, `{ status: "ok", path, source }` from the operation), or answers the failure without naming the path (see [Security](docs/behavior/security.md#document-ids)).
600
+ - **Answers.** An `existing` ID must be in its canonical form (`isCanonicalDocumentId`; keep the ID as it was given) and a `bound` path acceptable and with a URL (not ending in a slash); a broken answer is logged and answered `failed`. Refuse with `ExplorerError` as anywhere else (its reason's status); any other exception is logged and answered `failed`.
601
+ `documentIdVectors()` of `@aiquants/markdown-explorer/testing` lists IDs as readers write them with their canonical forms, for your registry's tests.
602
+ - **Erasing and moving.** Forget a document's ID when the document is erased, so the ID never comes to name another document. When a document moves, bind its ID to the new path to keep its permalinks working; until then they answer `not-found`.
603
+
526
604
  ### Revealing the open document
527
605
 
528
606
  The reader's tree setting "Reveal the open document" (`revealDocument`, off in `DEFAULT_TREE_SETTINGS`; turn it on for every reader with `defaultTreeSettings: { revealDocument: true }`) opens the folders down to the open document and brings its row into the tree's window. The open document is the URL's document in the tree view (whatever the selection mode, "Off" included), and in the multi view the maximized panel's document, else the one opened last (a panel's link replaces its document; on load, where no order of opening is known, the last open document in layout order).
@@ -773,11 +851,12 @@ Spread it into the configuration when your application has no sign-in: it provid
773
851
  | `data` | `ExplorerPageData` | `useLoaderData()` of the page route. |
774
852
  | `config` | `ExplorerConfig` | The shared configuration. |
775
853
  | `storageNamespace` | `string` | Prefix of the browser storage keys (tree settings, expansion state, the multi-view layout, the editor's side-by-side setting and share): 1–64 letters, digits, `.`, `_` or `-`, starting with a letter or digit (anything else throws a `RangeError`). |
854
+ | `accessFailure` | `AccessFailurePresenter<ReactNode>` | Draws the explorer's access failures (`@aiquants/auth-core`): a session that ended (`unauthorized`, the kind `unauthenticated`) and something the reader may not read or write (`forbidden`). The explorer words neither: each place hands the presenter one occurrence and draws the node it returns (see [Access failures](#access-failures)). Anything but a function throws a `TypeError` at the first render. |
776
855
  | `locale?` | `"en" \| "ja"` | The UI language (default `"en"`). |
777
856
  | `labels?` | `Partial<MarkdownExplorerLabels>` | Per-key overrides; strings that embed a value are functions, except the multi view's templates for `@aiquants/drag-drop-panels` (`MARKDOWN_EXPLORER_LABEL_TEMPLATES`). |
778
857
  | `theme?` | `"light" \| "dark"` | The colour scheme (default `"light"`), declared as the root's `color-scheme`, so the colours `@aiquants/directory-tree` paints from its `light-dark()` palette and the browser's own controls and scrollbars inside the explorer follow it, whatever the page declares. |
779
858
  | `renderFrame?` | `({ view, children }) => ReactNode` | Wraps each view in your chrome; for example leave the single view without it for embedding. |
780
- | `renderTreeFailure?` | `(failure) => ReactNode \| undefined` | Renders a tree failure you understand better (by its `code`); `undefined` keeps the explorer's own message. Your node replaces the explorer's callout inside the tree-failure element, which keeps its hooks (`data-testid="markdown-explorer-tree-failure"` and `data-aqmx-failure`); the callout is the failure's only announcement (`role="alert"`), so your node must announce itself (for example with `role="alert"`). |
859
+ | `renderTreeFailure?` | `(failure) => ReactNode \| undefined` | Renders a tree failure you understand better (by its `code`); `undefined` keeps the explorer's own message (for an access failure, the presenter's node). Your node replaces the explorer's callout inside the tree-failure element, which keeps its hooks (`data-testid="markdown-explorer-tree-failure"` and `data-aqmx-failure`); the callout is the failure's only announcement (`role="alert"`), so your node must announce itself (for example with `role="alert"`). |
781
860
  | `lockDocumentScroll?` | `boolean` | Stops the page itself from scrolling while the explorer fills the viewport; the explorer must then fit in the viewport (see below). |
782
861
  | `onMathDiagnostics?` | `(path, diagnostics: readonly MarkdownMathDiagnostic[]) => void` | Receives the KaTeX diagnostics of a markdown document once it rendered (never during render), with the document's path; the reader's console never sees them. `MarkdownMathDiagnostic` (`{ code, message, formula, displayMode }`) comes from `@aiquants/markdown`. The explorer reaches your function through one stable function, so passing a new function on every render neither parses the document again nor delivers its diagnostics twice; text documents report none. |
783
862
  | `onEditGrant?` | `(href: string) => Promise<boolean>` | Lets the reader grant what an edit or a save asked for (`{ kind: "grant", href }`, see [Editing](#editing)): open your root-relative `href` as you see fit (a consent popup, for example) and resolve whether the reader came back from it; the editor then asks again. Without it, the editor links to `href` in a new tab beside Try again. |
@@ -788,10 +867,7 @@ Spread it into the configuration when your application has no sign-in: it provid
788
867
  | `hostChangePolicy?` | `"reload" \| "notify"` | What a changed document the reader is not editing does: `"reload"` (default) reads it again and announces it; `"notify"` shows a notice with Reload above it (`data-aqmx-notice="changed"`), which steps aside while the reader edits the document. |
789
868
  | `ref?` | `Ref<MarkdownExplorerHandle>` | Receives the explorer's handle (see [The handle](#the-handle)), which always acts on the current reader's explorer. |
790
869
  | `guardUnload?` | `boolean` | Whether leaving the page while a draft is unsaved asks through `beforeunload` (default `true`; a host that asks on close itself passes `false`). |
791
- | `onReload?` | `() => void` | Reloads after a failure the reader asked to retry (default: the page's reload); a host whose state lives outside the page passes its rebuild. The explorer always calls the latest one given. |
792
- | `onSessionEnded?` | `() => Promise<boolean>` | Restores a session that ended (the `unauthorized` failure) without leaving the page: open your sign-in and resolve `true` once the reader is signed in again, and the failed view tries again; resolve `false` (never reject) when the sign-in fails or is cancelled, and the failure keeps offering it. Calls made while a sign-in is open share its answer. Without it the failure offers the reload. The explorer always calls the latest one given. |
793
870
  | `onDraftChange?` | `(change: ExplorerDraftChange) => void` | Receives the unsaved drafts as the explorer writes them (every 144 ms, those changed since the last call, as `kept`) and the paths whose drafts ended (`ended`: saved, discarded, closed, or back to the text they started from), so a host can keep a copy outside the page that `restoreDrafts` takes back (default: none). Its first call holds every draft unsaved by then; the explorer always calls the latest one given. |
794
- | `accountState?` | `"signed-in" \| "signed-out"` | Whether the reader is signed in to the host's account, which picks the words of an `unauthorized` failure: `"signed-in"` (default) asks to sign in again, `"signed-out"` to sign in. |
795
871
  | `confirmUnversionedSaves?` | `boolean` | Asks before every save that would write a change to a source that keeps no previous versions (an `edit` source answered with `history: false`), so every save can be undone or was confirmed (default `false`). |
796
872
  | `paletteKey?` | `string` | An opaque name of the palette the host binds the explorer's colour roles to; when it changes, the explorer reads again the colours it paints itself (the tree's connector lines, drawn on a canvas), which `theme` alone cannot tell (default: none). |
797
873
 
@@ -915,6 +991,19 @@ export const draftConverter: ExplorerDraftConverter = {
915
991
  - **The shared halves.** Two functions of the root entry hold what does not depend on the converter you run, so every host makes it one way: `draftConversionOf({ deny, conversion })` makes the converter's options from the deny rules and the conversion limits (`{ maxSourceBytes, maxHtmlBytes, deadlineMs }`) your server converts documents with — `{ timeoutMs, options: { deniedPathSegments, maxHtmlBytes, includeSourceLines: true } }` —,
916
992
  and `draftAnswerOf(error)` maps a conversion's failure to the draft answer as your server answers the same conversion: a size limit or the deadline is `too-large`, `invalid_argument` is `invalid`, `internal` is `failed`, and `unavailable` leaves the draft to the server; it rethrows any other error. `@aiquants/markdown`'s browser and service converters throw the same error classes.
917
993
 
994
+ #### Access failures
995
+
996
+ An `unauthorized` failure (the session ended) and a `forbidden` one (the reader may not read or write it) are not the explorer's to word: each place that meets one hands the host's presenter (`accessFailure`) an occurrence, `{ kind, place, deniedSentence, retry }` (`AccessFailureOccurrence` of `@aiquants/auth-core`), and draws the node the presenter returns inside the place's own hooks. The explorer's announcer says nothing of an access failure, since the presenter's node speaks for itself.
997
+
998
+ - **Kind.** `unauthorized` is the kind `unauthenticated`, `forbidden` the kind `forbidden`. The explorer's own reasons (`not-found`, `not-configured`, `invalid`, `too-large`, `unsupported`, `failed`) keep its own callouts and announcements.
999
+ - **Place.** `read` for what the explorer reads (a document, the tree and its refresh, a folder's children, a document's refresh, its source, the editor's text, a revision, the server's preview of a draft), `write` for what the reader writes (a save, Copy permalink, which issues the document's ID). The page itself is the host's: the page loader's refusal goes to the page route's error boundary.
1000
+ - **Denied sentence.** `null` (the presenter's own sentence), except for the `forbidden` answer of an ID URL, which carries the explorer's `documentIdForbidden`.
1001
+ - **Retry.** Where the place can repeat its work once the reader is signed in again it is the place's latest retry (read again, save again, refresh again, load the stopped folders again); `null` for Copy permalink (the reader presses it again) and for the preview (the next pause renders again).
1002
+ - **One occurrence per failure.** A place hands the same frozen occurrence for as long as it shows the same failure, so a presenter may tell one from the next by identity, and a new one for every new failure; a place drawn again after it was gone hands a new one.
1003
+ The folders whose children stop at an access failure, one after another, share one node above the tree, one occurrence while any of them stays stopped (the folders one press of Expand all stops at once share one node that speaks once), whose retry loads them all again; the rows keep their own failure and Try again, and the node goes once no folder is stopped.
1004
+ Copy permalink shows the latest press's failure only, takes it down at the next press and when the bar moves to another document, and the document's bar hides it while the document is edited and draws it again (a new occurrence) once the editing ends.
1005
+ - **The sheet.** While the explorer's sheet is open (a native modal `dialog`, on a frame too narrow for the split) everything behind it is inert and hidden from assistive technology, so the content's places hand their occurrences to the sheet, which draws them at the top of the explorer inside it, in the order they came (`data-testid="markdown-explorer-sheet-access-failures"`), and draws nothing behind; once the sheet closes, each node goes back to its place with the same occurrence. A node that moves is mounted again, and speaks again there.
1006
+
918
1007
  #### The handle
919
1008
 
920
1009
  The handle `ref` receives (`MarkdownExplorerHandle`) lets a host that owns what surrounds the explorer — a desktop shell closing its window, a page routing its announcements — act on the explorer. It always acts on the current reader's explorer.
@@ -934,6 +1023,7 @@ The handle's methods and the props above check what a host gives: a value of the
934
1023
  ### Localization
935
1024
 
936
1025
  `locale` selects a built-in catalog (`MARKDOWN_EXPLORER_LABEL_CATALOGS.en` / `.ja`); `labels` overrides single keys.
1026
+ The catalogs hold no words for an access failure, which the host's `accessFailure` presenter words in its own (see [Access failures](#access-failures)).
937
1027
  The catalogs also name every control of the document viewer (the `viewer…` keys: its toolbar, the table of contents, the style and alignment menus, each Mermaid diagram's controls, full-screen dialog, source view with its copy and type name, a storage SVG image's toolbar, source, copies, notices and full-screen dialog, the notice in place of a block that cannot render, every name, notice and announcement of a ```spreadsheets table, and the titles of embedded frames).
938
1028
  A table's labels are `@aiquants/markdown`'s own: each label of its table block under `viewerSpreadsheet…` (`zoomIn` → `viewerSpreadsheetZoomIn`), with the block's catalog of the UI language as the built-in text and its placeholders; only the ones a host replaces reach the viewer, so a table shows its catalog's text marked with its language, and its grid takes `locale` as its own.
939
1029
  The multi view's labels name everything its drag-and-drop layout shows (the panel headers' buttons and the custom drag mode's badge, the move announcements and a touch or pen drag's lift and cancel announcements, the bar of hidden panels, the columns' names and the drop placeholders), which therefore follow `locale` too.
@@ -1005,6 +1095,7 @@ Every scroller of the explorer that the reader browses gets one pointer scroll b
1005
1095
  - Data responses are `private, no-store` JSON with `nosniff`, a sandboxing content security policy and `same-origin` resource policy, and the data route refuses React Router's single-fetch requests (`.data`), whose answers would carry none of those headers; the tree refresh, and a document request marked as triggered by a refresh (`X-Markdown-Explorer: refresh`, which makes the host skip its caches), require the custom request header and pass the shared cross-origin check of server routes (`@aiquants/request-isolation`).
1006
1096
  - Editing writes only through the host's `edit` ports, after the deny rules and the same admission as a document. A save and a preview need the custom header `X-Markdown-Explorer: edit` and pass the shared cross-origin check, and their draft is read and checked (media type, `editMaxBytes`, UTF-8 without NUL) before any port is called; a grant's `href` must be root-relative and an external editor's `https:`; the preview is sanitized exactly as a document.
1007
1097
  A draft the host's browser converter renders (`draftConverter`) is sanitized in the browser with the same allow-list rules before it is shown, and never leaves the browser; only the existence marks come from the server's answers. The host checks in every port that the reader may edit the document, and writes only over the version the draft started from.
1098
+ - Document IDs are not permissions: an ID URL and the `resolve-id` operation pass the same checks as the document's path and name the path only to a reader who can open it. IDs are issued only for a document the reader can open (`issue-id`, with a proof header and the cross-origin check of a refresh), drawn by the explorer from Web Crypto (about 55 random bits), and every answer of the host's registry is checked.
1008
1099
  - Link cards are read by `@aiquants/markdown`'s handler behind a read-only authentication (no token refresh, no `Set-Cookie`; an authentication that carries headers is refused and logged), and its guards keep every internal address from becoming a card; see [Link cards](#link-cards).
1009
1100
  - Each data response carries an opaque, pseudonymous scope (an HMAC of the principal key under `scopeSecret`); when it changes, the browser drops every cache and remembered path. Browser storage is also checked against the page's scope on every page load, before anything reads it.
1010
1101
 
@@ -1045,7 +1136,8 @@ The source repository holds a runnable demo next to the package (`packages/markd
1045
1136
  the page and data routes, the error boundary, document and asset ports that route each path to the first source whose boundary contains it (no asset route of its own), a Markdown parser that produces document links and image targets, GitHub alerts, Zenn's message and details containers, embed placeholders, and footnotes, task lists and formulas in the Go converter's markup,
1046
1137
  every embed provider and link cards served by the data route (`embeds: { providers, linkCards: true }`; `guide/reference/embeds.md` and `guide/reference/link-cards.md` show them; the end-to-end tests answer the browser's card requests from their own fixtures, so they stay offline),
1047
1138
  editing (the parser writes source lines; the Markdown of `notes` is edited in place and saved to memory, never to the files, per draft space named by a cookie so tests never share saves; `guide/reference/embeds.md` links to an external editor), table files (`notes/tables`: a UTF-8 CSV with quoted cells, a Shift_JIS CSV read through `legacyTextEncoding:
1048
- "Shift_JIS"`, which the demo gives its file-system sources too, a TSV, and a CSV wider than the preview's 1,000 columns), the instant preview with `@aiquants/markdown`'s browser converter as `draftConverter` (`demo/app/draft-converter.client.ts`), and the end-to-end tests' fixtures.
1139
+ "Shift_JIS"`, which the demo gives its file-system sources too, a TSV, and a CSV wider than the preview's 1,000 columns), the instant preview with `@aiquants/markdown`'s browser converter as `draftConverter` (`demo/app/draft-converter.client.ts`),
1140
+ document IDs under `/docs/d/<ID>` with a registry kept in memory (`demo/app/document-ids.server.ts`, starting with a fixed ID for `guide/getting-started.md` and one bound to a path no source admits), and the end-to-end tests' fixtures.
1049
1141
  Its page `/browser-docs` runs the server half inside the page, as a desktop webview does (`demo/app/browser-host.client.ts`, following [Hosting](docs/behavior/hosting.md)): `createExplorerServer` of `./server/core` on the browser runtime of `./server/browser`, over a source of the Markdown documents the page bundles, rendered by the same browser converter, with the display settings kept in the page's storage. It has no server loader and no data route: the in-process fetch answers every data request in the page.
1050
1142
  Run it with `pnpm run demo:dev` from the package folder. The end-to-end tests run every spec in Chromium, and the in-page host's spec (`tests/e2e/browser-core.spec.ts`) in WebKit too.
1051
1143