@blogmcp/sdk 0.14.0 → 0.14.1

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.
@@ -9,7 +9,8 @@
9
9
  * communityMessage every text, cs and en, under the tone test;
10
10
  * links statements, the panel, the notifier's receipt in the fragment; M2: profiles, the
11
11
  * module's pages and the digest's unsubscribe token in the fragment;
12
- * communityMentionSpans `@handle` in a body as text spans a page links (never HTML).
12
+ * communityMentionSpans `@handle` in a body as text spans a page links (never HTML);
13
+ * legalTextBlocks M4: a private surface's legal text (its Markdown subset) as blocks a page renders as text.
13
14
  *
14
15
  * M3, the forum (m3-contracts.md §5.2): the client's `forum.*`, `me.follows.*` and `moderation.*`; createTopicStore
15
16
  * (a topic over the discussion store, with its header) and pollTopicHead; the forum's helpers (follow targets, the
@@ -42,5 +43,7 @@ export { COMMUNITY_CHANNELS } from './channels.js';
42
43
  export { COMMUNITY_ROUTES, COMMUNITY_RECEIPT_RE, statementPath, myCommunityPath, noticeStatusLink, signInLink, receiptFromHash, readReceiptFromHash, profilePath, COMMUNITY_MESSAGE_ANCHOR_PREFIX, communityMessageAnchor, communityMessageSeqFromHash, communityMessageLink, communityArticleLink, COMMUNITY_DIGEST_TOKEN_RE, digestTokenFromHash, readDigestTokenFromHash, forgetDigestToken, categoryPath, topicPath, topicMessageLink, } from './links.js';
43
44
  export { COMMUNITY_MENTION_RE, communityMentionSpans, communityMentionHandles } from './mentions.js';
44
45
  export type { CommunityTextSpan } from './mentions.js';
46
+ export { legalTextBlocks, LEGAL_TEXT_MAX_DEPTH } from './legal-text.js';
47
+ export type { LegalTextBlock, LegalTextHeading, LegalTextParagraph, LegalTextList, LegalTextListItem, LegalTextRun } from './legal-text.js';
45
48
  export { COMMUNITY_MESSAGES, communityMessage, communityMessageLanguage, hasCommunityMessage, warningMessageKey, confirmMessageKey, noteMessageKey, notificationMessageKey, notificationItemMessageKey, trustLabelMessageKey, adverseOutcomeMessageKey, } from './messages.js';
46
49
  export type { CommunityMessageKey, CommunityMessageLanguage } from './messages.js';
@@ -1,17 +1,18 @@
1
1
  import { createCommunityClient as _ } from "./client.js";
2
- import { COMMUNITY_APPEAL_MAX as T, COMMUNITY_BIO_MAX as O, COMMUNITY_CATEGORY_SLUG_RE as E, COMMUNITY_CLIENT_MSG_ID_RE as t, COMMUNITY_DISPLAY_NAME_MAX as S, COMMUNITY_DISPLAY_NAME_MIN as i, COMMUNITY_FOLLOWS_MAX as I, COMMUNITY_GOOD_FAITH as r, COMMUNITY_HANDLE_CHANGE_DAYS as n, COMMUNITY_HANDLE_RE as C, COMMUNITY_HEAD_ARTICLES_MAX as s, COMMUNITY_HEAD_TOPICS_MAX as A, COMMUNITY_MESSAGE_LINKS_MAX as N, COMMUNITY_MESSAGE_MAX as a, COMMUNITY_NOTICE_DESCRIPTION_MAX as m, COMMUNITY_NOTICE_TURNSTILE_ACTION as R, COMMUNITY_NOTIFIER_NAME_MAX as U, COMMUNITY_OPS as c, COMMUNITY_PAGE_SIZE as f, COMMUNITY_REPLIES_MAX as u, COMMUNITY_REPORT_NOTE_MAX as Y, COMMUNITY_SEARCH_PAGES_MAX as L, COMMUNITY_SEARCH_PAGE_SIZE as p, COMMUNITY_SEARCH_QUERY_MAX as D, COMMUNITY_SEARCH_QUERY_MIN as y, COMMUNITY_TOPICS_PAGE_MAX as K, COMMUNITY_TOPICS_PAGE_SIZE as P, COMMUNITY_TOPIC_TITLE_MAX as g, communityOpPath as l, newClientMsgId as F } from "./routes.js";
3
- import { COMMUNITY_API_CODES as G, COMMUNITY_HOST_CODES as d, COMMUNITY_OUTCOME_OF_HOST as w, COMMUNITY_OUTCOME_OF_KB as h, COMMUNITY_UI_CODES as X, CommunityTransportError as x, communityFailureOf as B, communityOutcomeOf as k, isCommunityTransportError as v, isCommunityUiCode as V, isLoggedCommunityOutcome as W } from "./outcome.js";
2
+ import { COMMUNITY_APPEAL_MAX as T, COMMUNITY_BIO_MAX as O, COMMUNITY_CATEGORY_SLUG_RE as E, COMMUNITY_CLIENT_MSG_ID_RE as t, COMMUNITY_DISPLAY_NAME_MAX as S, COMMUNITY_DISPLAY_NAME_MIN as i, COMMUNITY_FOLLOWS_MAX as I, COMMUNITY_GOOD_FAITH as r, COMMUNITY_HANDLE_CHANGE_DAYS as n, COMMUNITY_HANDLE_RE as s, COMMUNITY_HEAD_ARTICLES_MAX as C, COMMUNITY_HEAD_TOPICS_MAX as A, COMMUNITY_MESSAGE_LINKS_MAX as N, COMMUNITY_MESSAGE_MAX as a, COMMUNITY_NOTICE_DESCRIPTION_MAX as m, COMMUNITY_NOTICE_TURNSTILE_ACTION as R, COMMUNITY_NOTIFIER_NAME_MAX as U, COMMUNITY_OPS as c, COMMUNITY_PAGE_SIZE as f, COMMUNITY_REPLIES_MAX as u, COMMUNITY_REPORT_NOTE_MAX as Y, COMMUNITY_SEARCH_PAGES_MAX as L, COMMUNITY_SEARCH_PAGE_SIZE as p, COMMUNITY_SEARCH_QUERY_MAX as D, COMMUNITY_SEARCH_QUERY_MIN as y, COMMUNITY_TOPICS_PAGE_MAX as K, COMMUNITY_TOPICS_PAGE_SIZE as P, COMMUNITY_TOPIC_TITLE_MAX as g, communityOpPath as l, newClientMsgId as H } from "./routes.js";
3
+ import { COMMUNITY_API_CODES as G, COMMUNITY_HOST_CODES as d, COMMUNITY_OUTCOME_OF_HOST as w, COMMUNITY_OUTCOME_OF_KB as X, COMMUNITY_UI_CODES as h, CommunityTransportError as x, communityFailureOf as B, communityOutcomeOf as k, isCommunityTransportError as v, isCommunityUiCode as V, isLoggedCommunityOutcome as W } from "./outcome.js";
4
4
  import { assertCommunityBase as Q, communityOpUrl as Z, fetchTransport as q, isRelativeCommunityBase as j } from "./transport.js";
5
5
  import { IN_APP_BROWSER_RE as J, isInAppBrowser as $ } from "./ua.js";
6
- import { ADVERSE_EVENT_OUTCOMES as oe, AGE_BANDS as _e, ART9_CONSENT_LAYOUTS as Me, ART9_CONTROLLERS_MAX as Te, ART9_REFUSALS as Oe, AUTHOR_KINDS as Ee, BRAKE_SURFACES as te, CASE_CATEGORIES as Se, CATEGORY_WITHOUT_NOTIFIER as ie, ESCALATION_CATEGORIES as Ie, FOLLOW_TARGET_KINDS as re, FORUM_CATEGORY_KINDS as ne, FORUM_CATEGORY_MODES as Ce, FORUM_SORTS as se, FORUM_SPACES as Ae, LEGAL_TEXT_KINDS as Ne, MESSAGE_STATES as ae, MODERATION_BASES as me, MODERATION_CASE_STATUSES as Re, MODERATION_ITEM_KINDS as Ue, MODERATION_RESTRICTIONS as ce, MODERATION_SOURCES as fe, MODERATOR_TOPIC_STATES as ue, MODULE_STATES as Ye, MUTE_TARGET_KINDS as Le, NEEDS as pe, NOTIFICATION_CODES as De, PREMOD_OUTCOMES as ye, PUSH_USER_AGENT_CLASSES as Ke, REALTIME_EVENT_KINDS as Pe, RESTRICTION_KINDS as ge, SEARCH_RESULT_KINDS as le, TOPIC_CREATIONS as Fe, TOPIC_ITEM_KINDS as He, TOPIC_STATES as Ge, TRUST_LABELS as de, art9ConsentLayoutOf as we, art9ControllersOf as he, art9RefusalOf as Xe, communityLegalSectionsOf as xe, communityRulesOf as Be, isCaseCategory as ke, isKnownAdverseEventOutcome as ve, isKnownAuthor as Ve, isKnownAuthorKind as We, isKnownBrakeSurface as be, isKnownForumCategoryKind as Qe, isKnownForumCategoryMode as Ze, isKnownModuleState as qe, isKnownNeed as je, isKnownNotificationCode as ze, isKnownRestrictionKind as Je, isKnownState as $e, isKnownTopicState as eo, isKnownTrustLabel as oo } from "./shapes.js";
6
+ import { ADVERSE_EVENT_OUTCOMES as oe, AGE_BANDS as _e, ART9_CONSENT_LAYOUTS as Me, ART9_CONTROLLERS_MAX as Te, ART9_REFUSALS as Oe, AUTHOR_KINDS as Ee, BRAKE_SURFACES as te, CASE_CATEGORIES as Se, CATEGORY_WITHOUT_NOTIFIER as ie, ESCALATION_CATEGORIES as Ie, FOLLOW_TARGET_KINDS as re, FORUM_CATEGORY_KINDS as ne, FORUM_CATEGORY_MODES as se, FORUM_SORTS as Ce, FORUM_SPACES as Ae, LEGAL_TEXT_KINDS as Ne, MESSAGE_STATES as ae, MODERATION_BASES as me, MODERATION_CASE_STATUSES as Re, MODERATION_ITEM_KINDS as Ue, MODERATION_RESTRICTIONS as ce, MODERATION_SOURCES as fe, MODERATOR_TOPIC_STATES as ue, MODULE_STATES as Ye, MUTE_TARGET_KINDS as Le, NEEDS as pe, NOTIFICATION_CODES as De, PREMOD_OUTCOMES as ye, PUSH_USER_AGENT_CLASSES as Ke, REALTIME_EVENT_KINDS as Pe, RESTRICTION_KINDS as ge, SEARCH_RESULT_KINDS as le, TOPIC_CREATIONS as He, TOPIC_ITEM_KINDS as Fe, TOPIC_STATES as Ge, TRUST_LABELS as de, art9ConsentLayoutOf as we, art9ControllersOf as Xe, art9RefusalOf as he, communityLegalSectionsOf as xe, communityRulesOf as Be, isCaseCategory as ke, isKnownAdverseEventOutcome as ve, isKnownAuthor as Ve, isKnownAuthorKind as We, isKnownBrakeSurface as be, isKnownForumCategoryKind as Qe, isKnownForumCategoryMode as Ze, isKnownModuleState as qe, isKnownNeed as je, isKnownNotificationCode as ze, isKnownRestrictionKind as Je, isKnownState as $e, isKnownTopicState as eo, isKnownTrustLabel as oo } from "./shapes.js";
7
7
  import { createDiscussionStore as Mo, findMessage as To, isOwnMessage as Oo, loadMoreDiscussion as Eo, reactionAfter as to, reactionsFor as So, refreshDiscussion as io, viewerNeeds as Io } from "./store.js";
8
- import { POLL_INTERVAL_MS as no, POLL_MAX_BACKOFF_MS as Co, pollDiscussionHead as so, pollTopicHead as Ao } from "./poll.js";
8
+ import { POLL_INTERVAL_MS as no, POLL_MAX_BACKOFF_MS as so, pollDiscussionHead as Co, pollTopicHead as Ao } from "./poll.js";
9
9
  import { createTopicStore as ao, isTopicOpen as mo, isTopicStore as Ro, loadMoreTopic as Uo, refreshTopic as co, settleTopicFailure as fo, topicHeaderOf as uo, topicTitleOf as Yo } from "./topic.js";
10
- import { brakedSurfaceOf as po, communityAwayOf as Do, followKeyOf as yo, followTargetOf as Ko, followTargetParts as Po, forumSearchQueryOf as go, forumTopicTitleOf as lo, isCategoryModerator as Fo, isKnownTopicItem as Ho, knownTopicItemsOf as Go, nextSearchPage as wo, surfaceInfoOf as ho, topicTitleLength as Xo } from "./forum.js";
10
+ import { brakedSurfaceOf as po, communityAwayOf as Do, followKeyOf as yo, followTargetOf as Ko, followTargetParts as Po, forumSearchQueryOf as go, forumTopicTitleOf as lo, isCategoryModerator as Ho, isKnownTopicItem as Fo, knownTopicItemsOf as Go, nextSearchPage as wo, surfaceInfoOf as Xo, topicTitleLength as ho } from "./forum.js";
11
11
  import { COMMUNITY_CHANNELS as Bo } from "./channels.js";
12
12
  import { COMMUNITY_DIGEST_TOKEN_RE as vo, COMMUNITY_MESSAGE_ANCHOR_PREFIX as Vo, COMMUNITY_RECEIPT_RE as Wo, COMMUNITY_ROUTES as bo, categoryPath as Qo, communityArticleLink as Zo, communityMessageAnchor as qo, communityMessageLink as jo, communityMessageSeqFromHash as zo, digestTokenFromHash as Jo, forgetDigestToken as $o, myCommunityPath as e_, noticeStatusLink as o_, profilePath as __, readDigestTokenFromHash as M_, readReceiptFromHash as T_, receiptFromHash as O_, signInLink as E_, statementPath as t_, topicMessageLink as S_, topicPath as i_ } from "./links.js";
13
- import { COMMUNITY_MENTION_RE as r_, communityMentionHandles as n_, communityMentionSpans as C_ } from "./mentions.js";
14
- import { COMMUNITY_MESSAGES as A_, adverseOutcomeMessageKey as N_, communityMessage as a_, communityMessageLanguage as m_, confirmMessageKey as R_, hasCommunityMessage as U_, noteMessageKey as c_, notificationItemMessageKey as f_, notificationMessageKey as u_, trustLabelMessageKey as Y_, warningMessageKey as L_ } from "./messages.js";
13
+ import { COMMUNITY_MENTION_RE as r_, communityMentionHandles as n_, communityMentionSpans as s_ } from "./mentions.js";
14
+ import { LEGAL_TEXT_MAX_DEPTH as A_, legalTextBlocks as N_ } from "./legal-text.js";
15
+ import { COMMUNITY_MESSAGES as m_, adverseOutcomeMessageKey as R_, communityMessage as U_, communityMessageLanguage as c_, confirmMessageKey as f_, hasCommunityMessage as u_, noteMessageKey as Y_, notificationItemMessageKey as L_, notificationMessageKey as p_, trustLabelMessageKey as D_, warningMessageKey as y_ } from "./messages.js";
15
16
  export {
16
17
  oe as ADVERSE_EVENT_OUTCOMES,
17
18
  _e as AGE_BANDS,
@@ -34,12 +35,12 @@ export {
34
35
  I as COMMUNITY_FOLLOWS_MAX,
35
36
  r as COMMUNITY_GOOD_FAITH,
36
37
  n as COMMUNITY_HANDLE_CHANGE_DAYS,
37
- C as COMMUNITY_HANDLE_RE,
38
- s as COMMUNITY_HEAD_ARTICLES_MAX,
38
+ s as COMMUNITY_HANDLE_RE,
39
+ C as COMMUNITY_HEAD_ARTICLES_MAX,
39
40
  A as COMMUNITY_HEAD_TOPICS_MAX,
40
41
  d as COMMUNITY_HOST_CODES,
41
42
  r_ as COMMUNITY_MENTION_RE,
42
- A_ as COMMUNITY_MESSAGES,
43
+ m_ as COMMUNITY_MESSAGES,
43
44
  Vo as COMMUNITY_MESSAGE_ANCHOR_PREFIX,
44
45
  N as COMMUNITY_MESSAGE_LINKS_MAX,
45
46
  a as COMMUNITY_MESSAGE_MAX,
@@ -48,7 +49,7 @@ export {
48
49
  U as COMMUNITY_NOTIFIER_NAME_MAX,
49
50
  c as COMMUNITY_OPS,
50
51
  w as COMMUNITY_OUTCOME_OF_HOST,
51
- h as COMMUNITY_OUTCOME_OF_KB,
52
+ X as COMMUNITY_OUTCOME_OF_KB,
52
53
  f as COMMUNITY_PAGE_SIZE,
53
54
  Wo as COMMUNITY_RECEIPT_RE,
54
55
  u as COMMUNITY_REPLIES_MAX,
@@ -61,16 +62,17 @@ export {
61
62
  K as COMMUNITY_TOPICS_PAGE_MAX,
62
63
  P as COMMUNITY_TOPICS_PAGE_SIZE,
63
64
  g as COMMUNITY_TOPIC_TITLE_MAX,
64
- X as COMMUNITY_UI_CODES,
65
+ h as COMMUNITY_UI_CODES,
65
66
  x as CommunityTransportError,
66
67
  Ie as ESCALATION_CATEGORIES,
67
68
  re as FOLLOW_TARGET_KINDS,
68
69
  ne as FORUM_CATEGORY_KINDS,
69
- Ce as FORUM_CATEGORY_MODES,
70
- se as FORUM_SORTS,
70
+ se as FORUM_CATEGORY_MODES,
71
+ Ce as FORUM_SORTS,
71
72
  Ae as FORUM_SPACES,
72
73
  J as IN_APP_BROWSER_RE,
73
74
  Ne as LEGAL_TEXT_KINDS,
75
+ A_ as LEGAL_TEXT_MAX_DEPTH,
74
76
  ae as MESSAGE_STATES,
75
77
  me as MODERATION_BASES,
76
78
  Re as MODERATION_CASE_STATUSES,
@@ -83,20 +85,20 @@ export {
83
85
  pe as NEEDS,
84
86
  De as NOTIFICATION_CODES,
85
87
  no as POLL_INTERVAL_MS,
86
- Co as POLL_MAX_BACKOFF_MS,
88
+ so as POLL_MAX_BACKOFF_MS,
87
89
  ye as PREMOD_OUTCOMES,
88
90
  Ke as PUSH_USER_AGENT_CLASSES,
89
91
  Pe as REALTIME_EVENT_KINDS,
90
92
  ge as RESTRICTION_KINDS,
91
93
  le as SEARCH_RESULT_KINDS,
92
- Fe as TOPIC_CREATIONS,
93
- He as TOPIC_ITEM_KINDS,
94
+ He as TOPIC_CREATIONS,
95
+ Fe as TOPIC_ITEM_KINDS,
94
96
  Ge as TOPIC_STATES,
95
97
  de as TRUST_LABELS,
96
- N_ as adverseOutcomeMessageKey,
98
+ R_ as adverseOutcomeMessageKey,
97
99
  we as art9ConsentLayoutOf,
98
- he as art9ControllersOf,
99
- Xe as art9RefusalOf,
100
+ Xe as art9ControllersOf,
101
+ he as art9RefusalOf,
100
102
  Q as assertCommunityBase,
101
103
  po as brakedSurfaceOf,
102
104
  Qo as categoryPath,
@@ -105,17 +107,17 @@ export {
105
107
  B as communityFailureOf,
106
108
  xe as communityLegalSectionsOf,
107
109
  n_ as communityMentionHandles,
108
- C_ as communityMentionSpans,
109
- a_ as communityMessage,
110
+ s_ as communityMentionSpans,
111
+ U_ as communityMessage,
110
112
  qo as communityMessageAnchor,
111
- m_ as communityMessageLanguage,
113
+ c_ as communityMessageLanguage,
112
114
  jo as communityMessageLink,
113
115
  zo as communityMessageSeqFromHash,
114
116
  l as communityOpPath,
115
117
  Z as communityOpUrl,
116
118
  k as communityOutcomeOf,
117
119
  Be as communityRulesOf,
118
- R_ as confirmMessageKey,
120
+ f_ as confirmMessageKey,
119
121
  _ as createCommunityClient,
120
122
  Mo as createDiscussionStore,
121
123
  ao as createTopicStore,
@@ -128,9 +130,9 @@ export {
128
130
  $o as forgetDigestToken,
129
131
  go as forumSearchQueryOf,
130
132
  lo as forumTopicTitleOf,
131
- U_ as hasCommunityMessage,
133
+ u_ as hasCommunityMessage,
132
134
  ke as isCaseCategory,
133
- Fo as isCategoryModerator,
135
+ Ho as isCategoryModerator,
134
136
  v as isCommunityTransportError,
135
137
  V as isCommunityUiCode,
136
138
  $ as isInAppBrowser,
@@ -145,7 +147,7 @@ export {
145
147
  ze as isKnownNotificationCode,
146
148
  Je as isKnownRestrictionKind,
147
149
  $e as isKnownState,
148
- Ho as isKnownTopicItem,
150
+ Fo as isKnownTopicItem,
149
151
  eo as isKnownTopicState,
150
152
  oo as isKnownTrustLabel,
151
153
  W as isLoggedCommunityOutcome,
@@ -154,16 +156,17 @@ export {
154
156
  mo as isTopicOpen,
155
157
  Ro as isTopicStore,
156
158
  Go as knownTopicItemsOf,
159
+ N_ as legalTextBlocks,
157
160
  Eo as loadMoreDiscussion,
158
161
  Uo as loadMoreTopic,
159
162
  e_ as myCommunityPath,
160
- F as newClientMsgId,
163
+ H as newClientMsgId,
161
164
  wo as nextSearchPage,
162
- c_ as noteMessageKey,
165
+ Y_ as noteMessageKey,
163
166
  o_ as noticeStatusLink,
164
- f_ as notificationItemMessageKey,
165
- u_ as notificationMessageKey,
166
- so as pollDiscussionHead,
167
+ L_ as notificationItemMessageKey,
168
+ p_ as notificationMessageKey,
169
+ Co as pollDiscussionHead,
167
170
  Ao as pollTopicHead,
168
171
  __ as profilePath,
169
172
  to as reactionAfter,
@@ -176,13 +179,13 @@ export {
176
179
  fo as settleTopicFailure,
177
180
  E_ as signInLink,
178
181
  t_ as statementPath,
179
- ho as surfaceInfoOf,
182
+ Xo as surfaceInfoOf,
180
183
  uo as topicHeaderOf,
181
184
  S_ as topicMessageLink,
182
185
  i_ as topicPath,
183
- Xo as topicTitleLength,
186
+ ho as topicTitleLength,
184
187
  Yo as topicTitleOf,
185
- Y_ as trustLabelMessageKey,
188
+ D_ as trustLabelMessageKey,
186
189
  Io as viewerNeeds,
187
- L_ as warningMessageKey
190
+ y_ as warningMessageKey
188
191
  };
@@ -0,0 +1,65 @@
1
+ /**
2
+ * A legal text of the private surfaces as blocks (docs/internal/m4-contracts.md §5.11 "Formatting"): the body kb-api
3
+ * serves — `PrivateLegalText.body`, the account host's text pages — is written in a small subset of Markdown, and a
4
+ * page renders the blocks this function returns as elements with text in them, never as markup. Nothing here produces
5
+ * HTML, and the blocks carry no HTML: a `<b>` in a body is the four characters `<b>`.
6
+ *
7
+ * The subset (the legal lane's drafts use exactly this):
8
+ *
9
+ * - `#`…`######` headings, with an optional `{#anchor}` at the end (the anchor becomes the heading's `id`);
10
+ * - paragraphs: lines up to a blank line, joined with a space; a line ending in two spaces or `\` breaks the line
11
+ * (`\n` in a run's text);
12
+ * - lists: `-`, `*` or `+` bullets and `1.` / `1)` numbers, items continued by lines indented to the item's text
13
+ * (or by lazy lines right after it), lists nested by that indentation (at most LEGAL_TEXT_MAX_DEPTH deep); a
14
+ * number list starts after a blank line or a heading, never inside a paragraph (write `1\.` for a paragraph
15
+ * that starts with a number and a period);
16
+ * - inline: `**strong**`, `*emphasis*`, `***both***`, `` `code` ``, `[label](https://…)`, a bare `https://…`
17
+ * address, and `\` before a punctuation character to write it literally;
18
+ * - HTML comments (`<!-- … -->`, the drafts' markers) are dropped.
19
+ *
20
+ * A link's target is an `https:` address or a `mailto:` one and nothing else; any other target (an unfilled
21
+ * `{{placeholder}}`, `javascript:`, a relative path) leaves the label as text. Everything outside the subset —
22
+ * tables, quotes, images, raw HTML, `_underscores_` — is text as written.
23
+ *
24
+ * Fill a session's placeholders (`{{approval_email}}`, …) in the runs AFTER parsing, never in the body before it:
25
+ * a masked address (`l***@…`) would otherwise be read as emphasis.
26
+ *
27
+ * Import-free and the same code as kb-api's `services/legal-texts/legal-text-blocks.ts`, which renders the account
28
+ * host's text pages from it (test/community/legal-text-drift.spec.ts compares the two files).
29
+ */
30
+ /** A piece of text with its marks; consecutive runs of one link share its `href`. */
31
+ export interface LegalTextRun {
32
+ /** The text; a `\n` is a hard line break. */
33
+ readonly text: string;
34
+ readonly strong?: true;
35
+ readonly em?: true;
36
+ readonly code?: true;
37
+ /** An `https:` or `mailto:` address — never anything else. */
38
+ readonly href?: string;
39
+ }
40
+ export interface LegalTextHeading {
41
+ readonly type: 'heading';
42
+ readonly level: 1 | 2 | 3 | 4 | 5 | 6;
43
+ /** From a trailing `{#anchor}`: letters, digits, `-` and `_`, at most 64. */
44
+ readonly id: string | null;
45
+ readonly runs: readonly LegalTextRun[];
46
+ }
47
+ export interface LegalTextParagraph {
48
+ readonly type: 'paragraph';
49
+ readonly runs: readonly LegalTextRun[];
50
+ }
51
+ export interface LegalTextList {
52
+ readonly type: 'list';
53
+ readonly ordered: boolean;
54
+ /** The first item's number (1 for a bullet list). */
55
+ readonly start: number;
56
+ readonly items: readonly LegalTextListItem[];
57
+ }
58
+ export interface LegalTextListItem {
59
+ readonly blocks: readonly LegalTextBlock[];
60
+ }
61
+ export type LegalTextBlock = LegalTextHeading | LegalTextParagraph | LegalTextList;
62
+ /** How deep lists nest; a deeper item's line is paragraph text. */
63
+ export declare const LEGAL_TEXT_MAX_DEPTH = 8;
64
+ /** The blocks of a legal text's body (see the module comment). Never throws. */
65
+ export declare function legalTextBlocks(body: string): LegalTextBlock[];
@@ -0,0 +1,247 @@
1
+ const B = 8, L = /^(?:https:\/\/[^\s"'<>\\`\u0000-\u001f\u007f]+|mailto:[^\s"'<>\\`@\u0000-\u001f\u007f]+@[^\s"'<>\\`\u0000-\u001f\u007f]+)$/;
2
+ const X = /[ \t]*\{#([A-Za-z0-9][A-Za-z0-9_-]{0,63})\}$/, M = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?[ \t]*$/, N = /^( {0,3})([-*+]|(\d{1,9})([.)]))([ \t]+)(\S.*)$/, T = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", $ = `.,;:!?…'"»”’]*`, x = /https:\/\/[^\s<>"'`„“”‘’]+/y;
3
+ function y(e) {
4
+ if (typeof e != "string" || e === "") return [];
5
+ const t = e.replace(/\r\n?/g, `
6
+ `).replace(/<!--[\s\S]*?-->/g, "").split(`
7
+ `).map((n) => n.replace(/^[ \t]+/, (i) => i.replace(/\t/g, " ")));
8
+ return H(t, 0);
9
+ }
10
+ const a = (e) => e.trim() === "", O = (e) => e.length - e.trimStart().length;
11
+ function E(e) {
12
+ const t = N.exec(e);
13
+ if (!t) return null;
14
+ const n = t[5].length > 4 ? 1 : t[5].length, i = t[3] !== void 0;
15
+ return {
16
+ ordered: i,
17
+ delimiter: i ? t[4] : t[2],
18
+ start: i ? Number(t[3]) : 1,
19
+ contentIndent: t[1].length + t[2].length + n,
20
+ content: t[5].length > 4 ? t[5].slice(1) + t[6] : t[6]
21
+ };
22
+ }
23
+ function A(e) {
24
+ const t = M.exec(e);
25
+ if (!t) return null;
26
+ let n = (t[2] ?? "").replace(/(?:^|[ \t]+)#+$/, ""), i = null;
27
+ const l = X.exec(n);
28
+ return l && (i = l[1], n = n.slice(0, l.index)), n = n.trim(), n === "" ? null : { type: "heading", level: t[1].length, id: i, runs: I(n) };
29
+ }
30
+ function b(e, t) {
31
+ if (t >= 8) return !1;
32
+ const n = E(e);
33
+ return n !== null && !n.ordered;
34
+ }
35
+ function H(e, t) {
36
+ const n = [];
37
+ let i = 0;
38
+ for (; i < e.length; ) {
39
+ const l = e[i];
40
+ if (a(l)) {
41
+ i++;
42
+ continue;
43
+ }
44
+ const s = A(l);
45
+ if (s) {
46
+ n.push(s), i++;
47
+ continue;
48
+ }
49
+ const o = t < 8 ? E(l) : null;
50
+ if (o) {
51
+ const [d, f] = D(e, i, o, t);
52
+ n.push(d), i = f;
53
+ continue;
54
+ }
55
+ const r = [l];
56
+ for (i++; i < e.length && !a(e[i]) && !A(e[i]) && !b(e[i], t); )
57
+ r.push(e[i]), i++;
58
+ n.push({ type: "paragraph", runs: I(P(r)) });
59
+ }
60
+ return n;
61
+ }
62
+ function D(e, t, n, i) {
63
+ const l = [];
64
+ let s = n, o = t;
65
+ for (; ; ) {
66
+ const r = [s.content];
67
+ o++;
68
+ let d = !1;
69
+ for (; o < e.length; ) {
70
+ const c = e[o];
71
+ if (a(c)) {
72
+ r.push(""), d = !0, o++;
73
+ continue;
74
+ }
75
+ if (O(c) >= s.contentIndent) {
76
+ r.push(c.slice(s.contentIndent)), d = !1, o++;
77
+ continue;
78
+ }
79
+ if (!d && !E(c) && !A(c)) {
80
+ r.push(c.trimStart()), o++;
81
+ continue;
82
+ }
83
+ break;
84
+ }
85
+ if (l.push({ blocks: H(r, i + 1) }), o >= e.length) break;
86
+ const f = E(e[o]);
87
+ if (!f || f.ordered !== n.ordered || f.delimiter !== n.delimiter) break;
88
+ s = f;
89
+ }
90
+ for (; o > t && a(e[o - 1]); ) o--;
91
+ return [{ type: "list", ordered: n.ordered, start: n.start, items: l }, o];
92
+ }
93
+ function P(e) {
94
+ let t = "";
95
+ return e.forEach((n, i) => {
96
+ const l = n.trimStart();
97
+ if (i === e.length - 1) {
98
+ t += l.trimEnd();
99
+ return;
100
+ }
101
+ / {2,}$/.test(l) ? t += l.trimEnd() + `
102
+ ` : /(?:^|[^\\])(?:\\\\)*\\$/.test(l) ? t += l.slice(0, -1).trimEnd() + `
103
+ ` : t += l.trimEnd() + " ";
104
+ }), t;
105
+ }
106
+ function I(e) {
107
+ const t = [];
108
+ return w(e, {}, t, !1, 0), t;
109
+ }
110
+ function p(e, t, n, i = !1) {
111
+ if (t === "") return;
112
+ const l = {
113
+ text: t,
114
+ ...n.strong ? { strong: !0 } : {},
115
+ ...n.em ? { em: !0 } : {},
116
+ ...i ? { code: !0 } : {},
117
+ ...n.href ? { href: n.href } : {}
118
+ }, s = e[e.length - 1];
119
+ s && !i && !s.code && s.strong === l.strong && s.em === l.em && s.href === l.href ? e[e.length - 1] = { ...s, text: s.text + t } : e.push(l);
120
+ }
121
+ const R = (e) => e.length <= 2048 && L.test(e) ? e : null;
122
+ function S(e) {
123
+ let t = e;
124
+ for (; t.length > 0; ) {
125
+ const n = t[t.length - 1];
126
+ if (n === ")") {
127
+ if (t.split(")").length - 1 <= t.split("(").length - 1) break;
128
+ } else if (!$.includes(n))
129
+ break;
130
+ t = t.slice(0, -1);
131
+ }
132
+ return t;
133
+ }
134
+ function F(e, t) {
135
+ if (e[t] !== "(") return null;
136
+ let n = 0;
137
+ for (let i = t + 1; i < e.length && i - t <= 2049; i++) {
138
+ const l = e[i];
139
+ if (/\s/.test(l)) return null;
140
+ if (l === "(") n++;
141
+ else if (l === ")")
142
+ if (n > 0) n--;
143
+ else return i === t + 1 ? null : { raw: e.slice(t + 1, i), end: i + 1 };
144
+ }
145
+ return null;
146
+ }
147
+ function G(e) {
148
+ const t = [[], [], []], n = [], i = [];
149
+ let l = 0;
150
+ for (; l < e.length; ) {
151
+ const s = e[l];
152
+ if (s === "\\" && l + 1 < e.length && T.includes(e[l + 1])) {
153
+ l += 2;
154
+ continue;
155
+ }
156
+ if (s === "*") {
157
+ let o = 1;
158
+ for (; e[l + o] === "*"; ) o++;
159
+ o <= 3 && l > 0 && !/\s/.test(e[l - 1]) && t[o - 1].push(l), l += o;
160
+ continue;
161
+ }
162
+ s === "[" ? n.push(l) : s === "]" && i.push(l), l++;
163
+ }
164
+ return { closers: t, opens: n, closes: i };
165
+ }
166
+ function _(e, t) {
167
+ let n = 0, i = e.length;
168
+ for (; n < i; ) {
169
+ const l = n + i >> 1;
170
+ e[l] < t ? n = l + 1 : i = l;
171
+ }
172
+ return n < e.length ? e[n] : -1;
173
+ }
174
+ function w(e, t, n, i, l) {
175
+ if (l >= 6) {
176
+ p(n, e, t);
177
+ return;
178
+ }
179
+ const s = G(e);
180
+ let o = "", r = 0;
181
+ const d = () => {
182
+ p(n, o, t), o = "";
183
+ };
184
+ for (; r < e.length; ) {
185
+ const f = e[r];
186
+ if (f === "\\" && r + 1 < e.length && T.includes(e[r + 1])) {
187
+ o += e[r + 1], r += 2;
188
+ continue;
189
+ }
190
+ if (f === "`") {
191
+ let c = 1;
192
+ for (; e[r + c] === "`"; ) c++;
193
+ const h = "`".repeat(c);
194
+ let u = e.indexOf(h, r + c);
195
+ for (; u !== -1 && e[u + c] === "`"; ) {
196
+ let m = c;
197
+ for (; e[u + m] === "`"; ) m++;
198
+ u = e.indexOf(h, u + m);
199
+ }
200
+ if (u === -1) {
201
+ o += h, r += c;
202
+ continue;
203
+ }
204
+ let g = e.slice(r + c, u).replace(/\n/g, " ");
205
+ g.length > 1 && g.startsWith(" ") && g.endsWith(" ") && g.trim() !== "" && (g = g.slice(1, -1)), d(), p(n, g, t, !0), r = u + c;
206
+ continue;
207
+ }
208
+ if (f === "*") {
209
+ let c = 1;
210
+ for (; e[r + c] === "*"; ) c++;
211
+ const u = c <= 3 && r + c < e.length && !/\s/.test(e[r + c]) ? _(s.closers[c - 1], r + c + 1) : -1;
212
+ if (u === -1) {
213
+ o += "*".repeat(c), r += c;
214
+ continue;
215
+ }
216
+ d();
217
+ const g = { ...t, ...c !== 1 ? { strong: !0 } : {}, ...c !== 2 ? { em: !0 } : {} };
218
+ w(e.slice(r + c, u), g, n, i, l + 1), r = u + c;
219
+ continue;
220
+ }
221
+ if (f === "[" && !i) {
222
+ const c = _(s.closes, r + 1), h = _(s.opens, r + 1), u = c !== -1 && (h === -1 || h > c) ? F(e, c + 1) : null;
223
+ if (!u) {
224
+ o += "[", r++;
225
+ continue;
226
+ }
227
+ d();
228
+ const g = R(u.raw);
229
+ w(e.slice(r + 1, c), g ? { ...t, href: g } : t, n, !0, l + 1), r = u.end;
230
+ continue;
231
+ }
232
+ if (f === "h" && !i && (r === 0 || /[\s(\[<„"“'‘]/.test(e[r - 1]))) {
233
+ x.lastIndex = r;
234
+ const c = x.exec(e), h = c ? S(c[0]) : "", u = h.length > 8 ? R(h) : null;
235
+ if (u) {
236
+ d(), p(n, h, { ...t, href: u }), r += h.length;
237
+ continue;
238
+ }
239
+ }
240
+ o += f, r++;
241
+ }
242
+ d();
243
+ }
244
+ export {
245
+ B as LEGAL_TEXT_MAX_DEPTH,
246
+ y as legalTextBlocks
247
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blogmcp/sdk",
3
- "version": "0.14.0",
3
+ "version": "0.14.1",
4
4
  "description": "Headless SDK for Knowledge Base blog — core client, Vue composables, Nuxt adapter",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -102,8 +102,8 @@
102
102
  }
103
103
  },
104
104
  "dependencies": {
105
- "@blogmcp/mdx-schema": "^0.14.0",
106
- "@blogmcp/sanitize": "^0.14.0",
105
+ "@blogmcp/mdx-schema": "^0.14.1",
106
+ "@blogmcp/sanitize": "^0.14.1",
107
107
  "marked": "^15.0.7"
108
108
  },
109
109
  "optionalDependencies": {
@@ -9,7 +9,8 @@
9
9
  * communityMessage every text, cs and en, under the tone test;
10
10
  * links statements, the panel, the notifier's receipt in the fragment; M2: profiles, the
11
11
  * module's pages and the digest's unsubscribe token in the fragment;
12
- * communityMentionSpans `@handle` in a body as text spans a page links (never HTML).
12
+ * communityMentionSpans `@handle` in a body as text spans a page links (never HTML);
13
+ * legalTextBlocks M4: a private surface's legal text (its Markdown subset) as blocks a page renders as text.
13
14
  *
14
15
  * M3, the forum (m3-contracts.md §5.2): the client's `forum.*`, `me.follows.*` and `moderation.*`; createTopicStore
15
16
  * (a topic over the discussion store, with its header) and pollTopicHead; the forum's helpers (follow targets, the
@@ -378,6 +379,10 @@ export {
378
379
  export { COMMUNITY_MENTION_RE, communityMentionSpans, communityMentionHandles } from './mentions'
379
380
  export type { CommunityTextSpan } from './mentions'
380
381
 
382
+ // M4 (m4-contracts.md §5.11 "Formatting"): a private surface's legal text as blocks — rendered as text, never as HTML.
383
+ export { legalTextBlocks, LEGAL_TEXT_MAX_DEPTH } from './legal-text'
384
+ export type { LegalTextBlock, LegalTextHeading, LegalTextParagraph, LegalTextList, LegalTextListItem, LegalTextRun } from './legal-text'
385
+
381
386
  export {
382
387
  COMMUNITY_MESSAGES,
383
388
  communityMessage,
@@ -0,0 +1,438 @@
1
+ /**
2
+ * A legal text of the private surfaces as blocks (docs/internal/m4-contracts.md §5.11 "Formatting"): the body kb-api
3
+ * serves — `PrivateLegalText.body`, the account host's text pages — is written in a small subset of Markdown, and a
4
+ * page renders the blocks this function returns as elements with text in them, never as markup. Nothing here produces
5
+ * HTML, and the blocks carry no HTML: a `<b>` in a body is the four characters `<b>`.
6
+ *
7
+ * The subset (the legal lane's drafts use exactly this):
8
+ *
9
+ * - `#`…`######` headings, with an optional `{#anchor}` at the end (the anchor becomes the heading's `id`);
10
+ * - paragraphs: lines up to a blank line, joined with a space; a line ending in two spaces or `\` breaks the line
11
+ * (`\n` in a run's text);
12
+ * - lists: `-`, `*` or `+` bullets and `1.` / `1)` numbers, items continued by lines indented to the item's text
13
+ * (or by lazy lines right after it), lists nested by that indentation (at most LEGAL_TEXT_MAX_DEPTH deep); a
14
+ * number list starts after a blank line or a heading, never inside a paragraph (write `1\.` for a paragraph
15
+ * that starts with a number and a period);
16
+ * - inline: `**strong**`, `*emphasis*`, `***both***`, `` `code` ``, `[label](https://…)`, a bare `https://…`
17
+ * address, and `\` before a punctuation character to write it literally;
18
+ * - HTML comments (`<!-- … -->`, the drafts' markers) are dropped.
19
+ *
20
+ * A link's target is an `https:` address or a `mailto:` one and nothing else; any other target (an unfilled
21
+ * `{{placeholder}}`, `javascript:`, a relative path) leaves the label as text. Everything outside the subset —
22
+ * tables, quotes, images, raw HTML, `_underscores_` — is text as written.
23
+ *
24
+ * Fill a session's placeholders (`{{approval_email}}`, …) in the runs AFTER parsing, never in the body before it:
25
+ * a masked address (`l***@…`) would otherwise be read as emphasis.
26
+ *
27
+ * Import-free and the same code as kb-api's `services/legal-texts/legal-text-blocks.ts`, which renders the account
28
+ * host's text pages from it (test/community/legal-text-drift.spec.ts compares the two files).
29
+ */
30
+
31
+ // ── shared code: @blogmcp/sdk's community/legal-text.ts and kb-api's services/legal-texts/legal-text-blocks.ts are identical below this line ──
32
+
33
+ /** A piece of text with its marks; consecutive runs of one link share its `href`. */
34
+ export interface LegalTextRun {
35
+ /** The text; a `\n` is a hard line break. */
36
+ readonly text: string
37
+ readonly strong?: true
38
+ readonly em?: true
39
+ readonly code?: true
40
+ /** An `https:` or `mailto:` address — never anything else. */
41
+ readonly href?: string
42
+ }
43
+
44
+ export interface LegalTextHeading {
45
+ readonly type: 'heading'
46
+ readonly level: 1 | 2 | 3 | 4 | 5 | 6
47
+ /** From a trailing `{#anchor}`: letters, digits, `-` and `_`, at most 64. */
48
+ readonly id: string | null
49
+ readonly runs: readonly LegalTextRun[]
50
+ }
51
+
52
+ export interface LegalTextParagraph {
53
+ readonly type: 'paragraph'
54
+ readonly runs: readonly LegalTextRun[]
55
+ }
56
+
57
+ export interface LegalTextList {
58
+ readonly type: 'list'
59
+ readonly ordered: boolean
60
+ /** The first item's number (1 for a bullet list). */
61
+ readonly start: number
62
+ readonly items: readonly LegalTextListItem[]
63
+ }
64
+
65
+ export interface LegalTextListItem {
66
+ readonly blocks: readonly LegalTextBlock[]
67
+ }
68
+
69
+ export type LegalTextBlock = LegalTextHeading | LegalTextParagraph | LegalTextList
70
+
71
+ /** How deep lists nest; a deeper item's line is paragraph text. */
72
+ export const LEGAL_TEXT_MAX_DEPTH = 8
73
+
74
+ /** A link target the blocks may carry. */
75
+ const HREF_RE = /^(?:https:\/\/[^\s"'<>\\`\u0000-\u001f\u007f]+|mailto:[^\s"'<>\\`@\u0000-\u001f\u007f]+@[^\s"'<>\\`\u0000-\u001f\u007f]+)$/
76
+ const HREF_MAX = 2048
77
+ const ANCHOR_RE = /[ \t]*\{#([A-Za-z0-9][A-Za-z0-9_-]{0,63})\}$/
78
+ const HEADING_RE = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?[ \t]*$/
79
+ const ITEM_RE = /^( {0,3})([-*+]|(\d{1,9})([.)]))([ \t]+)(\S.*)$/
80
+ const ESCAPABLE = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
81
+ /** Characters that end a sentence more often than an address. */
82
+ const URL_TRAILING = '.,;:!?…\'"»”’]*'
83
+ const URL_RE = /https:\/\/[^\s<>"'`„“”‘’]+/y
84
+ /** How deep marks nest inside one another (beyond it, the rest is text). */
85
+ const INLINE_MAX_DEPTH = 6
86
+
87
+ /** The blocks of a legal text's body (see the module comment). Never throws. */
88
+ export function legalTextBlocks(body: string): LegalTextBlock[] {
89
+ if (typeof body !== 'string' || body === '') return []
90
+ const lines = body
91
+ .replace(/\r\n?/g, '\n')
92
+ .replace(/<!--[\s\S]*?-->/g, '')
93
+ .split('\n')
94
+ .map((line) => line.replace(/^[ \t]+/, (ws) => ws.replace(/\t/g, ' ')))
95
+ return blocksOf(lines, 0)
96
+ }
97
+
98
+ const isBlank = (line: string): boolean => line.trim() === ''
99
+ const indentOf = (line: string): number => line.length - line.trimStart().length
100
+
101
+ interface ItemStart {
102
+ readonly ordered: boolean
103
+ readonly delimiter: string
104
+ readonly start: number
105
+ /** Where the item's text starts: its continuation lines are indented at least this far. */
106
+ readonly contentIndent: number
107
+ readonly content: string
108
+ }
109
+
110
+ function itemOf(line: string): ItemStart | null {
111
+ const m = ITEM_RE.exec(line)
112
+ if (!m) return null
113
+ const spaces = m[5]!.length > 4 ? 1 : m[5]!.length
114
+ const ordered = m[3] !== undefined
115
+ return {
116
+ ordered,
117
+ delimiter: ordered ? m[4]! : m[2]!,
118
+ start: ordered ? Number(m[3]) : 1,
119
+ contentIndent: m[1]!.length + m[2]!.length + spaces,
120
+ content: m[5]!.length > 4 ? m[5]!.slice(1) + m[6]! : m[6]!,
121
+ }
122
+ }
123
+
124
+ function headingOf(line: string): LegalTextHeading | null {
125
+ const m = HEADING_RE.exec(line)
126
+ if (!m) return null
127
+ let text = (m[2] ?? '').replace(/(?:^|[ \t]+)#+$/, '')
128
+ let id: string | null = null
129
+ const anchor = ANCHOR_RE.exec(text)
130
+ if (anchor) {
131
+ id = anchor[1]!
132
+ text = text.slice(0, anchor.index)
133
+ }
134
+ text = text.trim()
135
+ if (text === '') return null
136
+ return { type: 'heading', level: m[1]!.length as LegalTextHeading['level'], id, runs: inlineRuns(text) }
137
+ }
138
+
139
+ /**
140
+ * A list item that may start in the middle of a paragraph: a bullet only. Unlike CommonMark, not even a number list
141
+ * that starts at 1 — a hard-wrapped Czech sentence puts „1. ledna“ at the start of a line.
142
+ */
143
+ function interrupts(line: string, depth: number): boolean {
144
+ if (depth >= LEGAL_TEXT_MAX_DEPTH) return false
145
+ const item = itemOf(line)
146
+ return item !== null && !item.ordered
147
+ }
148
+
149
+ function blocksOf(lines: readonly string[], depth: number): LegalTextBlock[] {
150
+ const out: LegalTextBlock[] = []
151
+ let i = 0
152
+ while (i < lines.length) {
153
+ const line = lines[i]!
154
+ if (isBlank(line)) {
155
+ i++
156
+ continue
157
+ }
158
+ const heading = headingOf(line)
159
+ if (heading) {
160
+ out.push(heading)
161
+ i++
162
+ continue
163
+ }
164
+ const item = depth < LEGAL_TEXT_MAX_DEPTH ? itemOf(line) : null
165
+ if (item) {
166
+ const [list, next] = listFrom(lines, i, item, depth)
167
+ out.push(list)
168
+ i = next
169
+ continue
170
+ }
171
+ const paragraph = [line]
172
+ i++
173
+ while (i < lines.length && !isBlank(lines[i]!) && !headingOf(lines[i]!) && !interrupts(lines[i]!, depth)) {
174
+ paragraph.push(lines[i]!)
175
+ i++
176
+ }
177
+ out.push({ type: 'paragraph', runs: inlineRuns(joinLines(paragraph)) })
178
+ }
179
+ return out
180
+ }
181
+
182
+ /** A list from line `at` (an item's line), and the index of the first line after it. */
183
+ function listFrom(lines: readonly string[], at: number, first: ItemStart, depth: number): [LegalTextList, number] {
184
+ const items: LegalTextListItem[] = []
185
+ let item = first
186
+ let i = at
187
+ for (;;) {
188
+ const own: string[] = [item.content]
189
+ i++
190
+ let afterBlank = false
191
+ while (i < lines.length) {
192
+ const line = lines[i]!
193
+ if (isBlank(line)) {
194
+ own.push('')
195
+ afterBlank = true
196
+ i++
197
+ continue
198
+ }
199
+ if (indentOf(line) >= item.contentIndent) {
200
+ own.push(line.slice(item.contentIndent))
201
+ afterBlank = false
202
+ i++
203
+ continue
204
+ }
205
+ // A lazy line: right after the item's text, and nothing that starts a block of its own.
206
+ if (!afterBlank && !itemOf(line) && !headingOf(line)) {
207
+ own.push(line.trimStart())
208
+ i++
209
+ continue
210
+ }
211
+ break
212
+ }
213
+ items.push({ blocks: blocksOf(own, depth + 1) })
214
+ if (i >= lines.length) break
215
+ const next = itemOf(lines[i]!)
216
+ if (!next || next.ordered !== first.ordered || next.delimiter !== first.delimiter) break
217
+ item = next
218
+ }
219
+ // The blank lines the last item collected belong to no one; the caller skips them.
220
+ while (i > at && isBlank(lines[i - 1]!)) i--
221
+ return [{ type: 'list', ordered: first.ordered, start: first.start, items }, i]
222
+ }
223
+
224
+ /** A paragraph's lines as one string: a soft break is a space, a hard one (two spaces or `\` at the end) a `\n`. */
225
+ function joinLines(lines: readonly string[]): string {
226
+ let out = ''
227
+ lines.forEach((raw, k) => {
228
+ const line = raw.trimStart()
229
+ if (k === lines.length - 1) {
230
+ out += line.trimEnd()
231
+ return
232
+ }
233
+ if (/ {2,}$/.test(line)) out += line.trimEnd() + '\n'
234
+ else if (/(?:^|[^\\])(?:\\\\)*\\$/.test(line)) out += line.slice(0, -1).trimEnd() + '\n'
235
+ else out += line.trimEnd() + ' '
236
+ })
237
+ return out
238
+ }
239
+
240
+ interface Marks {
241
+ readonly strong?: true
242
+ readonly em?: true
243
+ readonly href?: string
244
+ }
245
+
246
+ /** The runs of one block's text, adjacent runs with the same marks merged. */
247
+ function inlineRuns(text: string): LegalTextRun[] {
248
+ const out: LegalTextRun[] = []
249
+ inline(text, {}, out, false, 0)
250
+ return out
251
+ }
252
+
253
+ function push(out: LegalTextRun[], text: string, marks: Marks, code = false): void {
254
+ if (text === '') return
255
+ const run: LegalTextRun = {
256
+ text,
257
+ ...(marks.strong ? { strong: true as const } : {}),
258
+ ...(marks.em ? { em: true as const } : {}),
259
+ ...(code ? { code: true as const } : {}),
260
+ ...(marks.href ? { href: marks.href } : {}),
261
+ }
262
+ const last = out[out.length - 1]
263
+ if (last && !code && !last.code && last.strong === run.strong && last.em === run.em && last.href === run.href) {
264
+ out[out.length - 1] = { ...last, text: last.text + text }
265
+ } else {
266
+ out.push(run)
267
+ }
268
+ }
269
+
270
+ const safeHref = (raw: string): string | null => (raw.length <= HREF_MAX && HREF_RE.test(raw) ? raw : null)
271
+
272
+ /** An address without the punctuation after it; a `)` stays when it closes a `(` inside the address. */
273
+ function trimUrl(raw: string): string {
274
+ let url = raw
275
+ while (url.length > 0) {
276
+ const last = url[url.length - 1]!
277
+ if (last === ')') {
278
+ if (url.split(')').length - 1 <= url.split('(').length - 1) break
279
+ } else if (!URL_TRAILING.includes(last)) {
280
+ break
281
+ }
282
+ url = url.slice(0, -1)
283
+ }
284
+ return url
285
+ }
286
+
287
+ /**
288
+ * A link's `(target)` at `at`: no whitespace, parentheses balanced, at most HREF_MAX characters (so an unclosed one
289
+ * costs a bounded scan); null when there is none.
290
+ */
291
+ function targetAt(s: string, at: number): { raw: string; end: number } | null {
292
+ if (s[at] !== '(') return null
293
+ let depth = 0
294
+ for (let k = at + 1; k < s.length && k - at <= HREF_MAX + 1; k++) {
295
+ const c = s[k]!
296
+ if (/\s/.test(c)) return null
297
+ if (c === '(') depth++
298
+ else if (c === ')') {
299
+ if (depth > 0) depth--
300
+ else return k === at + 1 ? null : { raw: s.slice(at + 1, k), end: k + 1 }
301
+ }
302
+ }
303
+ return null
304
+ }
305
+
306
+ /** The positions of the delimiter runs a span can close at, per run length (1–3), and of the unescaped brackets. */
307
+ interface Scan {
308
+ readonly closers: readonly [number[], number[], number[]]
309
+ readonly opens: number[]
310
+ readonly closes: number[]
311
+ }
312
+
313
+ function scan(s: string): Scan {
314
+ const closers: [number[], number[], number[]] = [[], [], []]
315
+ const opens: number[] = []
316
+ const closes: number[] = []
317
+ let i = 0
318
+ while (i < s.length) {
319
+ const c = s[i]!
320
+ if (c === '\\' && i + 1 < s.length && ESCAPABLE.includes(s[i + 1]!)) {
321
+ i += 2
322
+ continue
323
+ }
324
+ if (c === '*') {
325
+ let n = 1
326
+ while (s[i + n] === '*') n++
327
+ if (n <= 3 && i > 0 && !/\s/.test(s[i - 1]!)) closers[n - 1]!.push(i)
328
+ i += n
329
+ continue
330
+ }
331
+ if (c === '[') opens.push(i)
332
+ else if (c === ']') closes.push(i)
333
+ i++
334
+ }
335
+ return { closers, opens, closes }
336
+ }
337
+
338
+ /** The first position in a sorted list that is at least `min`, or -1. */
339
+ function firstAtLeast(list: readonly number[], min: number): number {
340
+ let lo = 0
341
+ let hi = list.length
342
+ while (lo < hi) {
343
+ const mid = (lo + hi) >> 1
344
+ if (list[mid]! < min) lo = mid + 1
345
+ else hi = mid
346
+ }
347
+ return lo < list.length ? list[lo]! : -1
348
+ }
349
+
350
+ function inline(s: string, marks: Marks, out: LegalTextRun[], inLink: boolean, depth: number): void {
351
+ if (depth >= INLINE_MAX_DEPTH) {
352
+ push(out, s, marks)
353
+ return
354
+ }
355
+ const found = scan(s)
356
+ let text = ''
357
+ let i = 0
358
+ const flush = () => {
359
+ push(out, text, marks)
360
+ text = ''
361
+ }
362
+ while (i < s.length) {
363
+ const c = s[i]!
364
+ if (c === '\\' && i + 1 < s.length && ESCAPABLE.includes(s[i + 1]!)) {
365
+ text += s[i + 1]
366
+ i += 2
367
+ continue
368
+ }
369
+ if (c === '`') {
370
+ let n = 1
371
+ while (s[i + n] === '`') n++
372
+ const fence = '`'.repeat(n)
373
+ let end = s.indexOf(fence, i + n)
374
+ while (end !== -1 && s[end + n] === '`') {
375
+ let m = n
376
+ while (s[end + m] === '`') m++
377
+ end = s.indexOf(fence, end + m)
378
+ }
379
+ if (end === -1) {
380
+ text += fence
381
+ i += n
382
+ continue
383
+ }
384
+ let code = s.slice(i + n, end).replace(/\n/g, ' ')
385
+ if (code.length > 1 && code.startsWith(' ') && code.endsWith(' ') && code.trim() !== '') code = code.slice(1, -1)
386
+ flush()
387
+ push(out, code, marks, true)
388
+ i = end + n
389
+ continue
390
+ }
391
+ if (c === '*') {
392
+ let n = 1
393
+ while (s[i + n] === '*') n++
394
+ const opens = n <= 3 && i + n < s.length && !/\s/.test(s[i + n]!)
395
+ const close = opens ? firstAtLeast(found.closers[n - 1]!, i + n + 1) : -1
396
+ if (close === -1) {
397
+ text += '*'.repeat(n)
398
+ i += n
399
+ continue
400
+ }
401
+ flush()
402
+ const inner: Marks = { ...marks, ...(n !== 1 ? { strong: true as const } : {}), ...(n !== 2 ? { em: true as const } : {}) }
403
+ inline(s.slice(i + n, close), inner, out, inLink, depth + 1)
404
+ i = close + n
405
+ continue
406
+ }
407
+ if (c === '[' && !inLink) {
408
+ const close = firstAtLeast(found.closes, i + 1)
409
+ const nested = firstAtLeast(found.opens, i + 1)
410
+ const target = close !== -1 && (nested === -1 || nested > close) ? targetAt(s, close + 1) : null
411
+ if (!target) {
412
+ text += '['
413
+ i++
414
+ continue
415
+ }
416
+ flush()
417
+ const href = safeHref(target.raw)
418
+ inline(s.slice(i + 1, close), href ? { ...marks, href } : marks, out, true, depth + 1)
419
+ i = target.end
420
+ continue
421
+ }
422
+ if (c === 'h' && !inLink && (i === 0 || /[\s(\[<„"“'‘]/.test(s[i - 1]!))) {
423
+ URL_RE.lastIndex = i
424
+ const m = URL_RE.exec(s)
425
+ const url = m ? trimUrl(m[0]) : ''
426
+ const href = url.length > 'https://'.length ? safeHref(url) : null
427
+ if (href) {
428
+ flush()
429
+ push(out, url, { ...marks, href })
430
+ i += url.length
431
+ continue
432
+ }
433
+ }
434
+ text += c
435
+ i++
436
+ }
437
+ flush()
438
+ }