@mainsoft/agent-cms 0.0.0-stage → 0.6.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.
Files changed (108) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/LICENSE +21 -0
  3. package/README.md +347 -2
  4. package/TODO.md +178 -0
  5. package/UPGRADE-0.6.md +236 -0
  6. package/dist/agent.cjs +250 -0
  7. package/dist/agent.d.cts +88 -0
  8. package/dist/agent.d.ts +88 -0
  9. package/dist/agent.js +24 -0
  10. package/dist/ai.cjs +555 -0
  11. package/dist/ai.d.cts +48 -0
  12. package/dist/ai.d.ts +48 -0
  13. package/dist/ai.js +73 -0
  14. package/dist/bin.js +1556 -0
  15. package/dist/chunk-2NTK7H4W.js +10 -0
  16. package/dist/chunk-52NUUZC7.js +1446 -0
  17. package/dist/chunk-6K5ZTGHQ.js +30 -0
  18. package/dist/chunk-AKN7SUXU.js +281 -0
  19. package/dist/chunk-BTO42652.js +249 -0
  20. package/dist/chunk-CRDW6Q72.js +188 -0
  21. package/dist/chunk-DD56PTZ4.js +78 -0
  22. package/dist/chunk-DOADAH4L.js +52 -0
  23. package/dist/chunk-IGL2V6US.js +324 -0
  24. package/dist/chunk-IW3D4I7Q.js +317 -0
  25. package/dist/chunk-OQ55GEF3.js +6 -0
  26. package/dist/chunk-QC2M4NZY.js +158 -0
  27. package/dist/chunk-QIUXAUQ6.js +6 -0
  28. package/dist/chunk-QQV6VLYJ.js +204 -0
  29. package/dist/chunk-T66ZKBHF.js +25 -0
  30. package/dist/chunk-VICZ76TR.js +118 -0
  31. package/dist/cli.cjs +1596 -0
  32. package/dist/cli.d.cts +89 -0
  33. package/dist/cli.d.ts +89 -0
  34. package/dist/cli.js +534 -0
  35. package/dist/client.cjs +185 -0
  36. package/dist/client.d.cts +228 -0
  37. package/dist/client.d.ts +228 -0
  38. package/dist/client.js +13 -0
  39. package/dist/cms-BPp01z-8.d.ts +411 -0
  40. package/dist/cms-D6D89-qZ.d.cts +411 -0
  41. package/dist/config.cjs +61 -0
  42. package/dist/config.d.cts +36 -0
  43. package/dist/config.d.ts +36 -0
  44. package/dist/config.js +11 -0
  45. package/dist/diff.cjs +316 -0
  46. package/dist/diff.d.cts +122 -0
  47. package/dist/diff.d.ts +122 -0
  48. package/dist/diff.js +29 -0
  49. package/dist/drizzle-repo-B1rt7r4j.d.ts +90 -0
  50. package/dist/drizzle-repo-Cn-kL2FK.d.cts +90 -0
  51. package/dist/errors.cjs +193 -0
  52. package/dist/errors.d.cts +109 -0
  53. package/dist/errors.d.ts +109 -0
  54. package/dist/errors.js +16 -0
  55. package/dist/frontmatter.cjs +103 -0
  56. package/dist/frontmatter.d.cts +32 -0
  57. package/dist/frontmatter.d.ts +32 -0
  58. package/dist/frontmatter.js +9 -0
  59. package/dist/http.cjs +1104 -0
  60. package/dist/http.d.cts +67 -0
  61. package/dist/http.d.ts +67 -0
  62. package/dist/http.js +321 -0
  63. package/dist/index.cjs +3066 -0
  64. package/dist/index.d.cts +19 -0
  65. package/dist/index.d.ts +19 -0
  66. package/dist/index.js +263 -0
  67. package/dist/markdown.cjs +220 -0
  68. package/dist/markdown.d.cts +88 -0
  69. package/dist/markdown.d.ts +88 -0
  70. package/dist/markdown.js +23 -0
  71. package/dist/mcp.cjs +649 -0
  72. package/dist/mcp.d.cts +33 -0
  73. package/dist/mcp.d.ts +33 -0
  74. package/dist/mcp.js +24 -0
  75. package/dist/messages/en.cjs +76 -0
  76. package/dist/messages/en.d.cts +7 -0
  77. package/dist/messages/en.d.ts +7 -0
  78. package/dist/messages/en.js +7 -0
  79. package/dist/messages/ko.cjs +76 -0
  80. package/dist/messages/ko.d.cts +7 -0
  81. package/dist/messages/ko.d.ts +7 -0
  82. package/dist/messages/ko.js +53 -0
  83. package/dist/registry/cms-audit.json +25 -0
  84. package/dist/registry/cms-command.json +23 -0
  85. package/dist/registry/cms-doc-editor.json +36 -0
  86. package/dist/registry/cms-doc-list.json +29 -0
  87. package/dist/registry/cms-empty.json +22 -0
  88. package/dist/registry/cms-keys.json +29 -0
  89. package/dist/registry/cms-lib.json +33 -0
  90. package/dist/registry/cms-merge.json +26 -0
  91. package/dist/registry/cms-shell.json +22 -0
  92. package/dist/registry/cms-versions.json +26 -0
  93. package/dist/registry/registry.json +255 -0
  94. package/dist/repo-BWI2Pkrv.d.ts +162 -0
  95. package/dist/repo-CeDxUxO6.d.cts +162 -0
  96. package/dist/tables.cjs +356 -0
  97. package/dist/tables.d.cts +3515 -0
  98. package/dist/tables.d.ts +3515 -0
  99. package/dist/tables.js +35 -0
  100. package/dist/tools.cjs +420 -0
  101. package/dist/tools.d.cts +27 -0
  102. package/dist/tools.d.ts +27 -0
  103. package/dist/tools.js +18 -0
  104. package/dist/types.cjs +226 -0
  105. package/dist/types.d.cts +286 -0
  106. package/dist/types.d.ts +286 -0
  107. package/dist/types.js +28 -0
  108. package/package.json +277 -4
@@ -0,0 +1,19 @@
1
+ export { A as AgentChange, a as AnyCollection, B as BULK_ACTIONS, b as BulkAction, c as BulkResult, d as ChangeInfo, e as Cms, f as CmsCore, C as CmsLike, g as CollectionName, h as CreateCmsOptions, D as DocDiff, i as DocInput, F as FieldsOf, j as FieldsPatch, L as LIMITS, k as ListOptions, P as PREVIEW_TTLS, l as PatchOp, m as PreviewLink, n as PreviewRead, o as PreviewTtl, S as SLUG_RE, p as SearchOptions, q as SearchResult, r as SectionRange, T as TypedDoc, W as WriteOptions, s as applyPatch, t as coreOf, u as createCms, v as createCmsCore, w as dayIn, x as defineCollection, y as mergePatch, z as normalizeQuery, E as sectionRanges } from './cms-D6D89-qZ.cjs';
2
+ export { D as DoctorReport, a as DrizzleRepo, b as DrizzleRepoOptions } from './drizzle-repo-Cn-kL2FK.cjs';
3
+ export { A as AuditQuery, C as CmsRepo, D as DocPatch, K as KeyRow, M as MemoryRepo, N as NewDoc, a as NewVersion, S as StoredVersion } from './repo-CeDxUxO6.cjs';
4
+ export { CmsTables, CmsTablesOptions, SCHEMA_VERSION, cmsApiKeys, cmsAudit, cmsDdl, cmsDocuments, cmsHits, cmsMeta, cmsTables, cmsVersions, defaultTables, schemaVersionSql, splitSql, upgradeSteps } from './tables.cjs';
5
+ export { AgentLink, AgentLookup, AgentSection, Citation, ENVELOPE_PREAMBLE, LookupOptions, citationId, envelope, lookupForAgent, verifyCitations } from './agent.cjs';
6
+ export { CMS_TOOLS, CMS_TOOL_NAMES, CmsToolDef, toolsFor } from './tools.cjs';
7
+ export { CmsClient, CmsClientOptions, CmsRemoteError, RestClient, RestClientOptions, createCmsClient, createRestClient, isCmsRemoteError } from './client.cjs';
8
+ export { docFromMarkdown, parseFrontmatter } from './frontmatter.cjs';
9
+ export { AUDIT_ACTIONS, AccessArgs, Actor, AuditAction, AuditEntry, AutosaveState, CmsDoc, CmsKey, CmsVersion, CollectionConfig, DOC_STATUSES, DocContent, DocCounts, DocState, DocStatus, DocSummary, FieldAdmin, KEY_SCOPES, KeyScope, ReviewMark, SearchMissEvent, VIAS, VersionChange, VersionSummary, Via, docState } from './types.cjs';
10
+ export { CmsError, CmsErrorCode, CmsErrorKind, CmsErrorOptions, Diagnostic, ERROR_CODES, ERROR_KINDS, ErrorParams, MessageTemplate, Messages, formatMessage, isCmsError } from './errors.cjs';
11
+ import 'zod';
12
+ import './diff.cjs';
13
+ import 'drizzle-orm/pg-core';
14
+ import './markdown.cjs';
15
+
16
+ /** Package version (kept in step with package.json by `src/parts.test.ts`). */
17
+ declare const VERSION = "0.6.1";
18
+
19
+ export { VERSION };
@@ -0,0 +1,19 @@
1
+ export { A as AgentChange, a as AnyCollection, B as BULK_ACTIONS, b as BulkAction, c as BulkResult, d as ChangeInfo, e as Cms, f as CmsCore, C as CmsLike, g as CollectionName, h as CreateCmsOptions, D as DocDiff, i as DocInput, F as FieldsOf, j as FieldsPatch, L as LIMITS, k as ListOptions, P as PREVIEW_TTLS, l as PatchOp, m as PreviewLink, n as PreviewRead, o as PreviewTtl, S as SLUG_RE, p as SearchOptions, q as SearchResult, r as SectionRange, T as TypedDoc, W as WriteOptions, s as applyPatch, t as coreOf, u as createCms, v as createCmsCore, w as dayIn, x as defineCollection, y as mergePatch, z as normalizeQuery, E as sectionRanges } from './cms-BPp01z-8.js';
2
+ export { D as DoctorReport, a as DrizzleRepo, b as DrizzleRepoOptions } from './drizzle-repo-B1rt7r4j.js';
3
+ export { A as AuditQuery, C as CmsRepo, D as DocPatch, K as KeyRow, M as MemoryRepo, N as NewDoc, a as NewVersion, S as StoredVersion } from './repo-BWI2Pkrv.js';
4
+ export { CmsTables, CmsTablesOptions, SCHEMA_VERSION, cmsApiKeys, cmsAudit, cmsDdl, cmsDocuments, cmsHits, cmsMeta, cmsTables, cmsVersions, defaultTables, schemaVersionSql, splitSql, upgradeSteps } from './tables.js';
5
+ export { AgentLink, AgentLookup, AgentSection, Citation, ENVELOPE_PREAMBLE, LookupOptions, citationId, envelope, lookupForAgent, verifyCitations } from './agent.js';
6
+ export { CMS_TOOLS, CMS_TOOL_NAMES, CmsToolDef, toolsFor } from './tools.js';
7
+ export { CmsClient, CmsClientOptions, CmsRemoteError, RestClient, RestClientOptions, createCmsClient, createRestClient, isCmsRemoteError } from './client.js';
8
+ export { docFromMarkdown, parseFrontmatter } from './frontmatter.js';
9
+ export { AUDIT_ACTIONS, AccessArgs, Actor, AuditAction, AuditEntry, AutosaveState, CmsDoc, CmsKey, CmsVersion, CollectionConfig, DOC_STATUSES, DocContent, DocCounts, DocState, DocStatus, DocSummary, FieldAdmin, KEY_SCOPES, KeyScope, ReviewMark, SearchMissEvent, VIAS, VersionChange, VersionSummary, Via, docState } from './types.js';
10
+ export { CmsError, CmsErrorCode, CmsErrorKind, CmsErrorOptions, Diagnostic, ERROR_CODES, ERROR_KINDS, ErrorParams, MessageTemplate, Messages, formatMessage, isCmsError } from './errors.js';
11
+ import 'zod';
12
+ import './diff.js';
13
+ import 'drizzle-orm/pg-core';
14
+ import './markdown.js';
15
+
16
+ /** Package version (kept in step with package.json by `src/parts.test.ts`). */
17
+ declare const VERSION = "0.6.1";
18
+
19
+ export { VERSION };
package/dist/index.js ADDED
@@ -0,0 +1,263 @@
1
+ import {
2
+ DrizzleRepo
3
+ } from "./chunk-IGL2V6US.js";
4
+ import {
5
+ docFromMarkdown,
6
+ parseFrontmatter
7
+ } from "./chunk-DD56PTZ4.js";
8
+ import {
9
+ cmsApiKeys,
10
+ cmsAudit,
11
+ cmsDdl,
12
+ cmsDocuments,
13
+ cmsHits,
14
+ cmsMeta,
15
+ cmsTables,
16
+ cmsVersions,
17
+ defaultTables,
18
+ schemaVersionSql,
19
+ splitSql,
20
+ upgradeSteps
21
+ } from "./chunk-IW3D4I7Q.js";
22
+ import {
23
+ VERSION
24
+ } from "./chunk-QIUXAUQ6.js";
25
+ import {
26
+ CmsRemoteError,
27
+ createCmsClient,
28
+ createRestClient,
29
+ isCmsRemoteError
30
+ } from "./chunk-QC2M4NZY.js";
31
+ import {
32
+ CMS_TOOLS,
33
+ CMS_TOOL_NAMES,
34
+ toolsFor
35
+ } from "./chunk-QQV6VLYJ.js";
36
+ import {
37
+ BULK_ACTIONS,
38
+ ENVELOPE_PREAMBLE,
39
+ LIMITS,
40
+ PREVIEW_TTLS,
41
+ SLUG_RE,
42
+ applyPatch,
43
+ citationId,
44
+ coreOf,
45
+ createCms,
46
+ createCmsCore,
47
+ dayIn,
48
+ defineCollection,
49
+ envelope,
50
+ lookupForAgent,
51
+ mergePatch,
52
+ normalizeQuery,
53
+ sectionRanges,
54
+ verifyCitations
55
+ } from "./chunk-52NUUZC7.js";
56
+ import {
57
+ AUDIT_ACTIONS,
58
+ DOC_STATUSES,
59
+ KEY_SCOPES,
60
+ VIAS,
61
+ docState
62
+ } from "./chunk-6K5ZTGHQ.js";
63
+ import {
64
+ SCHEMA_VERSION
65
+ } from "./chunk-OQ55GEF3.js";
66
+ import "./chunk-AKN7SUXU.js";
67
+ import {
68
+ CmsError,
69
+ ERROR_CODES,
70
+ ERROR_KINDS,
71
+ formatMessage,
72
+ isCmsError
73
+ } from "./chunk-VICZ76TR.js";
74
+ import "./chunk-DOADAH4L.js";
75
+ import "./chunk-CRDW6Q72.js";
76
+ import "./chunk-2NTK7H4W.js";
77
+
78
+ // src/repo.ts
79
+ var MemoryRepo = class {
80
+ docs = /* @__PURE__ */ new Map();
81
+ versions = [];
82
+ keys = [];
83
+ hits = /* @__PURE__ */ new Map();
84
+ audit = [];
85
+ meta = /* @__PURE__ */ new Map([["schema_version", SCHEMA_VERSION]]);
86
+ seq = 0;
87
+ id = () => `00000000-0000-4000-8000-${String(++this.seq).padStart(12, "0")}`;
88
+ async tx(fn) {
89
+ const snap = { docs: new Map([...this.docs].map(([k, v]) => [k, structuredClone(v)])), versions: this.versions.map((v) => structuredClone(v)) };
90
+ try {
91
+ return await fn(this);
92
+ } catch (e) {
93
+ this.docs = snap.docs;
94
+ this.versions = snap.versions;
95
+ throw e;
96
+ }
97
+ }
98
+ async findDoc(collection, slug) {
99
+ for (const d of this.docs.values()) if (d.collection === collection && d.slug === slug) return structuredClone(d);
100
+ return null;
101
+ }
102
+ async findDocById(id) {
103
+ const d = this.docs.get(id);
104
+ return d ? structuredClone(d) : null;
105
+ }
106
+ async listDocs(f) {
107
+ return [...this.docs.values()].filter(
108
+ (d) => (!f.collection || d.collection === f.collection) && (!f.statuses || f.statuses.includes(d.status)) && (f.published === void 0 || (d.publishedVersion !== null && d.status !== "archived") === f.published)
109
+ ).map((d) => structuredClone(d));
110
+ }
111
+ async insertDoc(doc) {
112
+ for (const d of this.docs.values()) if (d.collection === doc.collection && d.slug === doc.slug) throw new Error("duplicate slug");
113
+ const now = (/* @__PURE__ */ new Date()).toISOString();
114
+ const row = { republishedAt: null, autosave: null, ...doc, id: doc.id ?? this.id(), createdAt: doc.createdAt ?? now, updatedAt: doc.updatedAt ?? now };
115
+ this.docs.set(row.id, structuredClone(row));
116
+ return structuredClone(row);
117
+ }
118
+ async updateDoc(id, patch, expectedVersion) {
119
+ const d = this.docs.get(id);
120
+ if (!d) return null;
121
+ if (expectedVersion !== void 0 && d.version !== expectedVersion) return null;
122
+ if (patch.slug && patch.slug !== d.slug) {
123
+ for (const o of this.docs.values()) if (o.id !== id && o.collection === d.collection && o.slug === patch.slug) throw new Error("duplicate slug");
124
+ }
125
+ const clean = Object.fromEntries(Object.entries(patch).filter(([, v]) => v !== void 0));
126
+ Object.assign(d, structuredClone(clean), { updatedAt: patch.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString() });
127
+ return structuredClone(d);
128
+ }
129
+ async deleteDoc(id) {
130
+ this.docs.delete(id);
131
+ this.versions = this.versions.filter((v) => v.documentId !== id);
132
+ for (const k of [...this.hits.keys()]) if (k.startsWith(`${id}|`)) this.hits.delete(k);
133
+ }
134
+ async insertVersion(v) {
135
+ if (this.versions.some((x) => x.documentId === v.documentId && x.version === v.version)) throw new Error("duplicate version");
136
+ this.versions.push({ changed: null, ...structuredClone(v), reviewed: [], id: this.id(), createdAt: v.createdAt ?? (/* @__PURE__ */ new Date()).toISOString() });
137
+ }
138
+ async listVersions(documentId) {
139
+ return this.versions.filter((v) => v.documentId === documentId).sort((a, b) => b.version - a.version).map((v) => structuredClone(v));
140
+ }
141
+ async getVersion(documentId, version) {
142
+ const v = this.versions.find((x) => x.documentId === documentId && x.version === version);
143
+ return v ? structuredClone(v) : null;
144
+ }
145
+ async setVersionReviewed(documentId, version, reviewed) {
146
+ const v = this.versions.find((x) => x.documentId === documentId && x.version === version);
147
+ if (v) v.reviewed = structuredClone(reviewed);
148
+ }
149
+ async pruneVersions(documentId, keep, protect) {
150
+ const mine = this.versions.filter((v) => v.documentId === documentId).sort((a, b) => b.version - a.version);
151
+ const drop = new Set(mine.slice(keep).filter((v) => !protect.includes(v.version)).map((v) => v.id));
152
+ this.versions = this.versions.filter((v) => !drop.has(v.id));
153
+ }
154
+ async insertKey(k) {
155
+ const row = { ...k, id: this.id(), lastUsedAt: null, revokedAt: null, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
156
+ this.keys.push(row);
157
+ return { ...row };
158
+ }
159
+ async listKeys() {
160
+ return this.keys.map((k) => ({ ...k }));
161
+ }
162
+ async findKeyByHash(hash) {
163
+ const k = this.keys.find((x) => x.hash === hash);
164
+ return k ? { ...k } : null;
165
+ }
166
+ async touchKey(id, at) {
167
+ const k = this.keys.find((x) => x.id === id);
168
+ if (k) k.lastUsedAt = at;
169
+ }
170
+ async revokeKey(id, at) {
171
+ const k = this.keys.find((x) => x.id === id);
172
+ if (!k || k.revokedAt) return false;
173
+ k.revokedAt = at;
174
+ return true;
175
+ }
176
+ async addHits(ids, day, source) {
177
+ for (const id of ids) {
178
+ const key = `${id}|${day}|${source}`;
179
+ this.hits.set(key, (this.hits.get(key) ?? 0) + 1);
180
+ }
181
+ }
182
+ async hitCounts(sinceDay, collection) {
183
+ const out = /* @__PURE__ */ new Map();
184
+ for (const [k, n] of this.hits) {
185
+ const [id, day] = k.split("|");
186
+ if (collection && this.docs.get(id)?.collection !== collection) continue;
187
+ if (day >= sinceDay) out.set(id, (out.get(id) ?? 0) + n);
188
+ }
189
+ return out;
190
+ }
191
+ async insertAudit(e) {
192
+ this.audit.push({ ...structuredClone(e), id: this.id() });
193
+ }
194
+ async listAudit(q) {
195
+ return this.audit.filter((e) => (!q.before || `${e.at}|${e.id}` < q.before) && (!q.action || e.action === q.action) && (!q.outcome || e.outcome === q.outcome) && (!q.actorKind || e.actorKind === q.actorKind)).sort((a, b) => `${b.at}|${b.id}`.localeCompare(`${a.at}|${a.id}`)).slice(0, q.limit).map((e) => structuredClone(e));
196
+ }
197
+ async changeStamp() {
198
+ let max = "";
199
+ for (const d of this.docs.values()) if (d.updatedAt > max) max = d.updatedAt;
200
+ return `${this.docs.size}:${max}`;
201
+ }
202
+ async getMeta(key) {
203
+ return this.meta.get(key) ?? null;
204
+ }
205
+ async setMeta(key, value) {
206
+ this.meta.set(key, value);
207
+ }
208
+ };
209
+ export {
210
+ AUDIT_ACTIONS,
211
+ BULK_ACTIONS,
212
+ CMS_TOOLS,
213
+ CMS_TOOL_NAMES,
214
+ CmsError,
215
+ CmsRemoteError,
216
+ DOC_STATUSES,
217
+ DrizzleRepo,
218
+ ENVELOPE_PREAMBLE,
219
+ ERROR_CODES,
220
+ ERROR_KINDS,
221
+ KEY_SCOPES,
222
+ LIMITS,
223
+ MemoryRepo,
224
+ PREVIEW_TTLS,
225
+ SCHEMA_VERSION,
226
+ SLUG_RE,
227
+ VERSION,
228
+ VIAS,
229
+ applyPatch,
230
+ citationId,
231
+ cmsApiKeys,
232
+ cmsAudit,
233
+ cmsDdl,
234
+ cmsDocuments,
235
+ cmsHits,
236
+ cmsMeta,
237
+ cmsTables,
238
+ cmsVersions,
239
+ coreOf,
240
+ createCms,
241
+ createCmsClient,
242
+ createCmsCore,
243
+ createRestClient,
244
+ dayIn,
245
+ defaultTables,
246
+ defineCollection,
247
+ docFromMarkdown,
248
+ docState,
249
+ envelope,
250
+ formatMessage,
251
+ isCmsError,
252
+ isCmsRemoteError,
253
+ lookupForAgent,
254
+ mergePatch,
255
+ normalizeQuery,
256
+ parseFrontmatter,
257
+ schemaVersionSql,
258
+ sectionRanges,
259
+ splitSql,
260
+ toolsFor,
261
+ upgradeSteps,
262
+ verifyCitations
263
+ };
@@ -0,0 +1,220 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/markdown.ts
21
+ var markdown_exports = {};
22
+ __export(markdown_exports, {
23
+ APP_LINK_RE: () => APP_LINK_RE,
24
+ anchorOf: () => anchorOf,
25
+ appLinkKeys: () => appLinkKeys,
26
+ extractToc: () => extractToc,
27
+ inlineText: () => inlineText,
28
+ parseInline: () => parseInline,
29
+ parseMarkdown: () => parseMarkdown,
30
+ plainText: () => plainText,
31
+ splitSections: () => splitSections
32
+ });
33
+ module.exports = __toCommonJS(markdown_exports);
34
+ var APP_LINK_RE = /\[\[link:([a-z0-9][a-z0-9._-]*)\|([^\]]+)\]\]/gi;
35
+ function anchorOf(text) {
36
+ const base = text.trim().toLowerCase().replace(/[`*_[\]()<>!?.,:;'"“”‘’/\\|]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
37
+ return base || "section";
38
+ }
39
+ function parseInline(src) {
40
+ const out = [];
41
+ const re = /(\[\[link:([a-z0-9][a-z0-9._-]*)\|([^\]]+)\]\]|\*\*([^*]+)\*\*|`([^`]+)`|\[([^\]]+)\]\(((?:[^()\s]|\([^()\s]*\))+)\))/gi;
42
+ let last = 0;
43
+ let m;
44
+ while (m = re.exec(src)) {
45
+ if (m.index > last) out.push({ t: "text", v: src.slice(last, m.index) });
46
+ if (m[2]) out.push({ t: "applink", key: m[2], v: m[3] });
47
+ else if (m[4] !== void 0) out.push({ t: "strong", v: m[4] });
48
+ else if (m[5] !== void 0) out.push({ t: "code", v: m[5] });
49
+ else if (m[6] !== void 0) {
50
+ const href = m[7];
51
+ if (/^(https?:\/\/|mailto:|\/(?!\/)|#)/i.test(href)) out.push({ t: "link", href, v: m[6] });
52
+ else out.push({ t: "text", v: m[6] });
53
+ }
54
+ last = m.index + m[0].length;
55
+ }
56
+ if (last < src.length) out.push({ t: "text", v: src.slice(last) });
57
+ return out;
58
+ }
59
+ function inlineText(inline) {
60
+ return inline.map((i) => i.v).join("");
61
+ }
62
+ function parseMarkdown(source) {
63
+ const lines = source.replace(/\r/g, "").split("\n");
64
+ const blocks = [];
65
+ const used = /* @__PURE__ */ new Map();
66
+ let para = [];
67
+ let list = null;
68
+ const uniqueId = (text) => {
69
+ const base = anchorOf(text);
70
+ const n = used.get(base) ?? 0;
71
+ used.set(base, n + 1);
72
+ return n ? `${base}-${n}` : base;
73
+ };
74
+ const flushPara = () => {
75
+ if (!para.length) return;
76
+ const text = para.join(" ").trim();
77
+ para = [];
78
+ if (!text) return;
79
+ const inline = parseInline(text);
80
+ const onlyLinks = inline.every((i) => i.t === "applink" || i.t === "text" && !i.v.trim());
81
+ if (onlyLinks && inline.some((i) => i.t === "applink")) {
82
+ blocks.push({
83
+ t: "links",
84
+ items: inline.filter((i) => i.t === "applink").map((i) => ({ key: i.key, v: i.v }))
85
+ });
86
+ } else blocks.push({ t: "p", inline });
87
+ };
88
+ const flushList = () => {
89
+ if (!list) return;
90
+ blocks.push({ t: "list", ordered: list.ordered, items: list.items.map(parseInline) });
91
+ list = null;
92
+ };
93
+ const flush = () => {
94
+ flushPara();
95
+ flushList();
96
+ };
97
+ for (let i = 0; i < lines.length; i++) {
98
+ const line = lines[i];
99
+ const fence = /^```(\S*)\s*$/.exec(line);
100
+ if (fence) {
101
+ flush();
102
+ const buf = [];
103
+ i++;
104
+ while (i < lines.length && !/^```\s*$/.test(lines[i])) buf.push(lines[i++]);
105
+ blocks.push({ t: "code", lang: fence[1] ?? "", v: buf.join("\n") });
106
+ continue;
107
+ }
108
+ const h = /^(#{2,3})\s+(.+?)\s*#*\s*$/.exec(line);
109
+ if (h) {
110
+ flush();
111
+ const text = h[2];
112
+ const inline = parseInline(text);
113
+ blocks.push({ t: "heading", level: h[1].length, id: uniqueId(inlineText(inline)), text: inlineText(inline), inline });
114
+ continue;
115
+ }
116
+ if (/^#\s+/.test(line)) {
117
+ flush();
118
+ const inline = parseInline(line.replace(/^#\s+/, ""));
119
+ blocks.push({ t: "heading", level: 2, id: uniqueId(inlineText(inline)), text: inlineText(inline), inline });
120
+ continue;
121
+ }
122
+ if (/^\s*(---|\*\*\*)\s*$/.test(line)) {
123
+ flush();
124
+ blocks.push({ t: "hr" });
125
+ continue;
126
+ }
127
+ if (/^>\s?/.test(line)) {
128
+ flush();
129
+ const buf = [];
130
+ while (i < lines.length && /^>\s?/.test(lines[i])) buf.push(lines[i++].replace(/^>\s?/, ""));
131
+ i--;
132
+ let callout = null;
133
+ const tag = /^\[!(note|tip|warning)\]\s*$/i.exec(buf[0] ?? "");
134
+ if (tag) {
135
+ callout = tag[1].toLowerCase();
136
+ buf.shift();
137
+ }
138
+ const inner = parseMarkdown(buf.join("\n")).map((b) => b.t === "heading" ? { t: "p", inline: b.inline } : b);
139
+ blocks.push({ t: "quote", callout, blocks: inner });
140
+ continue;
141
+ }
142
+ const ul = /^\s*[-*]\s+(.*)$/.exec(line);
143
+ const ol = /^\s*\d+[.)]\s+(.*)$/.exec(line);
144
+ if (ul || ol) {
145
+ flushPara();
146
+ const ordered = !!ol;
147
+ if (list && list.ordered !== ordered) flushList();
148
+ if (!list) list = { ordered, items: [] };
149
+ list.items.push((ul ?? ol)[1]);
150
+ continue;
151
+ }
152
+ if (!line.trim()) {
153
+ flush();
154
+ continue;
155
+ }
156
+ if (list && /^\s{2,}\S/.test(line)) {
157
+ list.items[list.items.length - 1] += " " + line.trim();
158
+ continue;
159
+ }
160
+ flushList();
161
+ para.push(line.trim());
162
+ }
163
+ flush();
164
+ return blocks;
165
+ }
166
+ function extractToc(blocks) {
167
+ return blocks.flatMap((b) => b.t === "heading" ? [{ id: b.id, text: b.text, level: b.level }] : []);
168
+ }
169
+ function appLinkKeys(body) {
170
+ const keys = /* @__PURE__ */ new Set();
171
+ for (const m of body.matchAll(APP_LINK_RE)) keys.add(m[1]);
172
+ return [...keys];
173
+ }
174
+ function plainText(body) {
175
+ return body.replace(/```[\s\S]*?```/g, " ").replace(APP_LINK_RE, "$2").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/^>\s?\[![a-z]+\]\s*$/gim, "").replace(/[*`>#]/g, "").replace(/^\s*(\d+[.)]|[-*])\s+/gm, "").replace(/[ \t]+/g, " ").trim();
176
+ }
177
+ function splitSections(body) {
178
+ const lines = body.replace(/\r/g, "").split("\n");
179
+ const out = [];
180
+ const used = /* @__PURE__ */ new Map();
181
+ let cur = { anchor: "", heading: "", markdown: "" };
182
+ let inFence = false;
183
+ const push = () => {
184
+ cur.markdown = cur.markdown.trim();
185
+ if (cur.markdown || cur.heading) out.push(cur);
186
+ };
187
+ for (const line of lines) {
188
+ if (/^```/.test(line)) inFence = !inFence;
189
+ const h = !inFence ? /^#{1,2}\s+(.+?)\s*#*\s*$/.exec(line) : null;
190
+ if (h) {
191
+ push();
192
+ const text = inlineText(parseInline(h[1]));
193
+ const base = anchorOf(text);
194
+ const n = used.get(base) ?? 0;
195
+ used.set(base, n + 1);
196
+ cur = { anchor: n ? `${base}-${n}` : base, heading: text, markdown: "" };
197
+ continue;
198
+ }
199
+ const h3 = !inFence ? /^###\s+(.+?)\s*#*\s*$/.exec(line) : null;
200
+ if (h3) {
201
+ const base = anchorOf(inlineText(parseInline(h3[1])));
202
+ used.set(base, (used.get(base) ?? 0) + 1);
203
+ }
204
+ cur.markdown += line + "\n";
205
+ }
206
+ push();
207
+ return out;
208
+ }
209
+ // Annotate the CommonJS export names for ESM import in node:
210
+ 0 && (module.exports = {
211
+ APP_LINK_RE,
212
+ anchorOf,
213
+ appLinkKeys,
214
+ extractToc,
215
+ inlineText,
216
+ parseInline,
217
+ parseMarkdown,
218
+ plainText,
219
+ splitSections
220
+ });
@@ -0,0 +1,88 @@
1
+ /**
2
+ * The markdown subset documents are written in, parsed to a small block tree.
3
+ * Framework-free: the app renders the tree with its own components, so a doc
4
+ * looks native wherever it shows (public page, admin preview, chat).
5
+ *
6
+ * Supported: `## / ###` headings, paragraphs, `-`/`*` and `1.` lists, `>`
7
+ * quotes and `> [!note]` callouts, fenced code, `---`, and inline **bold**,
8
+ * `code`, [text](url) and the CMS link `[[link:key|label]]`.
9
+ */
10
+ type Inline = {
11
+ t: "text";
12
+ v: string;
13
+ } | {
14
+ t: "strong";
15
+ v: string;
16
+ } | {
17
+ t: "code";
18
+ v: string;
19
+ } | {
20
+ t: "link";
21
+ href: string;
22
+ v: string;
23
+ }
24
+ /** `[[link:key|label]]` — an app screen, resolved by the collection. */
25
+ | {
26
+ t: "applink";
27
+ key: string;
28
+ v: string;
29
+ };
30
+ type Block = {
31
+ t: "heading";
32
+ level: 2 | 3;
33
+ id: string;
34
+ text: string;
35
+ inline: Inline[];
36
+ } | {
37
+ t: "p";
38
+ inline: Inline[];
39
+ } | {
40
+ t: "list";
41
+ ordered: boolean;
42
+ items: Inline[][];
43
+ } | {
44
+ t: "quote";
45
+ callout: "note" | "tip" | "warning" | null;
46
+ blocks: Block[];
47
+ } | {
48
+ t: "code";
49
+ lang: string;
50
+ v: string;
51
+ } | {
52
+ t: "hr";
53
+ }
54
+ /** A paragraph that is only app links: drawn as link cards. */
55
+ | {
56
+ t: "links";
57
+ items: {
58
+ key: string;
59
+ v: string;
60
+ }[];
61
+ };
62
+ interface TocItem {
63
+ id: string;
64
+ text: string;
65
+ level: 2 | 3;
66
+ }
67
+ declare const APP_LINK_RE: RegExp;
68
+ /** Heading anchor: lowercase, spaces → '-', keeps Hangul; stable across renders. */
69
+ declare function anchorOf(text: string): string;
70
+ declare function parseInline(src: string): Inline[];
71
+ declare function inlineText(inline: Inline[]): string;
72
+ declare function parseMarkdown(source: string): Block[];
73
+ declare function extractToc(blocks: Block[]): TocItem[];
74
+ /** Every `[[link:key|…]]` key in a body. */
75
+ declare function appLinkKeys(body: string): string[];
76
+ /** Plain text of a body (for search and summaries): no markup, links as labels. */
77
+ declare function plainText(body: string): string;
78
+ interface Section {
79
+ /** Heading anchor, or "" for the text before the first heading. */
80
+ anchor: string;
81
+ heading: string;
82
+ /** Markdown of the section (heading line excluded). */
83
+ markdown: string;
84
+ }
85
+ /** Split a body at `##` headings (### stays inside its section). */
86
+ declare function splitSections(body: string): Section[];
87
+
88
+ export { APP_LINK_RE, type Block, type Inline, type Section, type TocItem, anchorOf, appLinkKeys, extractToc, inlineText, parseInline, parseMarkdown, plainText, splitSections };