@jsb188/mday 1.1.8 → 1.1.11

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 (123) hide show
  1. package/package.json +105 -35
  2. package/src/constants/agentDoc.ts +12 -0
  3. package/src/constants/agentMemory.ts +154 -0
  4. package/src/constants/aiChat.ts +5 -0
  5. package/src/constants/campaign.ts +127 -0
  6. package/src/constants/dataTable.ts +48 -0
  7. package/src/constants/dataTableFieldTypes.generated.ts +63 -0
  8. package/src/constants/docAccess.ts +32 -0
  9. package/src/constants/email.ts +44 -0
  10. package/src/constants/fieldDoc.ts +34 -0
  11. package/src/constants/graphqlReactivity.ts +113 -0
  12. package/src/constants/inboundContact.ts +8 -0
  13. package/src/constants/integration.ts +13 -0
  14. package/src/constants/log.ts +7 -366
  15. package/src/constants/logActivityGroupColors.generated.ts +19 -0
  16. package/src/constants/logTaxonomy.generated.ts +1103 -0
  17. package/src/constants/noteDoc.ts +77 -0
  18. package/src/constants/organization.ts +18 -11
  19. package/src/constants/pageRoute.ts +23 -0
  20. package/src/constants/schedule.ts +220 -0
  21. package/src/constants/scheduleRuleTemplateSeed.ts +138 -0
  22. package/src/constants/scheduleRuleTemplates.generated.ts +145 -0
  23. package/src/constants/sheet.ts +168 -0
  24. package/src/constants/sheetRegionSources.generated.ts +578 -0
  25. package/src/constants/square.ts +16 -0
  26. package/src/constants/storage.ts +61 -0
  27. package/src/constants/usage.ts +79 -0
  28. package/src/schemas/editLogEntry.ts +1017 -738
  29. package/src/schemas/fieldDocsQuery.ts +12 -0
  30. package/src/schemas/inboundContact.ts +77 -0
  31. package/src/schemas/logsQuery.ts +57 -316
  32. package/src/schemas/organization.ts +53 -213
  33. package/src/types/account.d.ts +81 -0
  34. package/src/types/agentDoc.d.ts +64 -0
  35. package/src/types/agentMemory.d.ts +74 -0
  36. package/src/types/campaign.d.ts +683 -0
  37. package/src/types/dataTable.d.ts +366 -0
  38. package/src/types/docAccess.d.ts +96 -0
  39. package/src/types/email.d.ts +142 -0
  40. package/src/types/fieldDoc.d.ts +273 -0
  41. package/src/types/inboundContact.d.ts +57 -0
  42. package/src/types/integration.d.ts +42 -0
  43. package/src/types/log.d.ts +169 -190
  44. package/src/types/noteDoc.d.ts +86 -0
  45. package/src/types/organization.d.ts +175 -76
  46. package/src/types/pageRoute.d.ts +48 -0
  47. package/src/types/schedule.d.ts +391 -0
  48. package/src/types/sheet.d.ts +1130 -0
  49. package/src/types/storage.d.ts +242 -0
  50. package/src/types/usage.d.ts +106 -0
  51. package/src/types/workflow.d.ts +305 -0
  52. package/src/utils/agentDoc.ts +109 -0
  53. package/src/utils/aiChat.ts +26 -0
  54. package/src/utils/campaign.ts +741 -0
  55. package/src/utils/campaignFormEditor.ts +871 -0
  56. package/src/utils/dataTable.ts +849 -0
  57. package/src/utils/dataTableFieldTypeRegistry.ts +105 -0
  58. package/src/utils/dataTableRealtimeAuthority.ts +209 -0
  59. package/src/utils/dataTableRealtimeSelection.ts +134 -0
  60. package/src/utils/dataTableRowDocument.ts +508 -0
  61. package/src/utils/dataTableSource.ts +230 -0
  62. package/src/utils/docAccess.ts +383 -0
  63. package/src/utils/documentName.ts +53 -0
  64. package/src/utils/email.ts +172 -0
  65. package/src/utils/fieldDoc.ts +113 -0
  66. package/src/utils/log.ts +173 -778
  67. package/src/utils/logRegistryValue.ts +90 -0
  68. package/src/utils/logStoreRead.ts +266 -0
  69. package/src/utils/logTaxonomy.ts +76 -0
  70. package/src/utils/logTaxonomyDisplay.ts +439 -0
  71. package/src/utils/noteDoc.ts +827 -0
  72. package/src/utils/organization.ts +683 -81
  73. package/src/utils/pageRoute.ts +71 -0
  74. package/src/utils/schedule.ts +799 -0
  75. package/src/utils/scheduleEvaluation.ts +1994 -0
  76. package/src/utils/scheduleICS.ts +246 -0
  77. package/src/utils/scheduleRuleTemplates.ts +188 -0
  78. package/src/utils/sheet.ts +4973 -0
  79. package/src/utils/sheetAxisMove.ts +830 -0
  80. package/src/utils/sheetBootstrap.ts +1769 -0
  81. package/src/utils/sheetCommand.ts +423 -0
  82. package/src/utils/sheetExport.ts +238 -0
  83. package/src/utils/sheetFormulaEvaluation.ts +914 -0
  84. package/src/utils/sheetFormulaEvaluator.ts +852 -0
  85. package/src/utils/sheetJournal.ts +78 -0
  86. package/src/utils/sheetNumberFormat.ts +1211 -0
  87. package/src/utils/sheetRegion.ts +374 -0
  88. package/src/utils/sheetRegionFilter.ts +1259 -0
  89. package/src/utils/sheetRegionSourceRegistry.ts +594 -0
  90. package/src/utils/sheetSequence.ts +148 -0
  91. package/src/utils/sheetSnapshot.ts +992 -0
  92. package/src/utils/sheetStructureEdit.ts +1284 -0
  93. package/src/utils/square.ts +32 -0
  94. package/src/utils/storage.ts +152 -0
  95. package/src/utils/table-route.ts +262 -0
  96. package/src/utils/workflow.ts +380 -0
  97. package/tests/dataTableFieldTypeRegistry.test.ts +110 -0
  98. package/tests/docAccess.test.ts +525 -0
  99. package/tests/editLogEntry.test.ts +112 -0
  100. package/tests/noteDoc.test.ts +669 -0
  101. package/tests/schedule.test.ts +693 -0
  102. package/tests/scheduleEvaluation.test.ts +1970 -0
  103. package/tests/scheduleICS.test.ts +208 -0
  104. package/tests/scheduleRuleTemplates.test.ts +176 -0
  105. package/tests/scheduleSweepInvariants.test.ts +428 -0
  106. package/tests/sheetAxisMove.test.ts +343 -0
  107. package/tests/sheetFormulaEvaluator.test.ts +575 -0
  108. package/tests/sheetRegionFilter.test.ts +1135 -0
  109. package/tests/sheetSequence.test.ts +41 -0
  110. package/tests/sheetStructureEdit.test.ts +82 -0
  111. package/tsconfig.json +12 -0
  112. package/vitest.config.ts +8 -0
  113. package/src/constants/log-activityTexts.ts +0 -209
  114. package/src/constants/product.ts +0 -66
  115. package/src/constants/report.ts +0 -25
  116. package/src/schemas/childOrganizationsQuery.ts +0 -44
  117. package/src/schemas/productsQuery.ts +0 -145
  118. package/src/schemas/reportsQuery.ts +0 -107
  119. package/src/types/action.d.ts +0 -42
  120. package/src/types/product.d.ts +0 -173
  121. package/src/types/report.d.ts +0 -203
  122. package/src/utils/product-calEvent.ts +0 -508
  123. package/src/utils/route-helpers.ts +0 -583
@@ -0,0 +1,827 @@
1
+ /**
2
+ * Pure helpers for note "content" documents. No DOM/browser APIs: the same
3
+ * code runs on the Deno server (sanitizing mutation input, filtering image
4
+ * blocks on read) and on the web client (sanitizing before save).
5
+ */
6
+
7
+ import {
8
+ NOTE_BLOCK_TYPES,
9
+ NOTE_COLOR_TOKENS,
10
+ NOTE_CONTAINER_BLOCK_TYPES,
11
+ NOTE_DOC_VERSION,
12
+ NOTE_LINK_HREF_REGEX,
13
+ NOTE_MARK_TYPES,
14
+ NOTE_MAX_BLOCKS,
15
+ NOTE_MAX_DEPTH,
16
+ NOTE_MAX_TEXT_CHARS,
17
+ NOTE_NESTING_RULES,
18
+ } from '../constants/noteDoc.ts';
19
+ import type {
20
+ NoteBlockNode,
21
+ NoteBlockType,
22
+ NoteDoc,
23
+ NoteHeadingLevel,
24
+ NoteInlineNode,
25
+ NoteMark,
26
+ NoteMarkType,
27
+ } from '../types/noteDoc.d.ts';
28
+
29
+ const FILE_CONSTANTS = {
30
+ // Maximum raw JSON nesting levels one sanitize walk may descend; beyond
31
+ // this the input is hostile and the remainder is dropped (legal documents
32
+ // stay far below it because NOTE_MAX_DEPTH caps the output tree)
33
+ maxRawNesting: 64,
34
+ // Maximum raw nodes the iterative over-deep-container flattener visits
35
+ flattenVisitCap: 10000,
36
+ };
37
+
38
+ /**
39
+ * Mutable doc-wide caps shared across one sanitize walk; both counters only
40
+ * ever decrease, so the tail of an oversized document is truncated.
41
+ */
42
+
43
+ interface SanitizeBudget {
44
+ blocks: number;
45
+ textChars: number;
46
+ }
47
+
48
+ /**
49
+ * Check whether one unknown value is a plain object (a JSON node candidate).
50
+ */
51
+
52
+ function isNodeObj(value: unknown): value is Record<string, any> {
53
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
54
+ }
55
+
56
+ /**
57
+ * Check whether one block type holds block children.
58
+ */
59
+
60
+ function isContainerBlockType(type: string): boolean {
61
+ return (NOTE_CONTAINER_BLOCK_TYPES as readonly string[]).includes(type);
62
+ }
63
+
64
+ /**
65
+ * Build one empty paragraph block (the non-empty guarantee filler).
66
+ */
67
+
68
+ function createEmptyParagraph(): NoteBlockNode {
69
+ return {
70
+ type: 'paragraph',
71
+ content: [],
72
+ };
73
+ }
74
+
75
+ /**
76
+ * Build one empty note document: a single empty paragraph, current version.
77
+ */
78
+
79
+ export function createEmptyNoteDoc(): NoteDoc {
80
+ return {
81
+ type: 'doc',
82
+ version: NOTE_DOC_VERSION,
83
+ content: [createEmptyParagraph()],
84
+ };
85
+ }
86
+
87
+ /**
88
+ * Sanitize one raw mark list: whitelist mark types, validate color/highlight
89
+ * tokens against the palette, restrict link hrefs to http(s)/mailto (which
90
+ * kills javascript: URLs), rebuild attrs from scratch (stripping unknown
91
+ * props), and drop duplicate mark types. Returns undefined when nothing
92
+ * survives so clean runs omit the "marks" key entirely.
93
+ */
94
+
95
+ function sanitizeMarks(rawMarks: unknown): NoteMark[] | undefined {
96
+ if (!Array.isArray(rawMarks)) {
97
+ return undefined;
98
+ }
99
+
100
+ const marks: NoteMark[] = [];
101
+ const seenTypes = new Set<string>();
102
+
103
+ for (const raw of rawMarks) {
104
+ if (!isNodeObj(raw) || typeof raw.type !== 'string') {
105
+ continue;
106
+ }
107
+
108
+ const type = raw.type;
109
+ if (
110
+ !(NOTE_MARK_TYPES as readonly string[]).includes(type) ||
111
+ seenTypes.has(type)
112
+ ) {
113
+ continue;
114
+ }
115
+
116
+ if (type === 'color' || type === 'highlight') {
117
+ // Palette marks must carry a known color token
118
+ const token = isNodeObj(raw.attrs) ? raw.attrs.token : undefined;
119
+ if (typeof token !== 'string' || !NOTE_COLOR_TOKENS.includes(token)) {
120
+ continue;
121
+ }
122
+ marks.push({ type: type as NoteMarkType, attrs: { token } });
123
+ } else if (type === 'link') {
124
+ // Only http(s)/mailto links survive; anything else is dropped
125
+ const rawHref = isNodeObj(raw.attrs) ? raw.attrs.href : undefined;
126
+ const href = typeof rawHref === 'string' ? rawHref.trim() : '';
127
+ if (!NOTE_LINK_HREF_REGEX.test(href)) {
128
+ continue;
129
+ }
130
+ marks.push({ type: 'link', attrs: { href } });
131
+ } else {
132
+ // bold/italic/underline/strike/code carry no attrs
133
+ marks.push({ type: type as NoteMarkType });
134
+ }
135
+
136
+ seenTypes.add(type);
137
+ }
138
+
139
+ return marks.length ? marks : undefined;
140
+ }
141
+
142
+ /**
143
+ * Build one order-insensitive identity key for a text run's mark set, used
144
+ * to merge adjacent runs with identical styling.
145
+ */
146
+
147
+ function getMarkSetKey(marks?: NoteMark[]): string {
148
+ if (!marks?.length) {
149
+ return '';
150
+ }
151
+ return marks
152
+ .map(
153
+ (mark) => mark.type + ':' + (mark.attrs?.token || mark.attrs?.href || ''),
154
+ )
155
+ .sort()
156
+ .join('|');
157
+ }
158
+
159
+ /**
160
+ * Sanitize one raw inline list: whitelist text/hardBreak nodes, sanitize
161
+ * marks, spend the doc-wide text budget (truncating the tail; hardBreaks
162
+ * cost 1 char each, matching the offset model, so a hardBreak flood cannot
163
+ * evade the caps), drop empty runs, and merge adjacent runs with identical
164
+ * mark sets.
165
+ */
166
+
167
+ function sanitizeInlineContent(
168
+ rawContent: unknown,
169
+ budget: SanitizeBudget,
170
+ ): NoteInlineNode[] {
171
+ const inline: NoteInlineNode[] = [];
172
+ if (!Array.isArray(rawContent)) {
173
+ return inline;
174
+ }
175
+
176
+ for (const raw of rawContent) {
177
+ if (!isNodeObj(raw)) {
178
+ continue;
179
+ }
180
+
181
+ if (raw.type === 'hardBreak') {
182
+ // A hardBreak counts as 1 char in the offset model; spend the
183
+ // doc-wide text budget so unbounded hardBreak floods truncate
184
+ if (budget.textChars <= 0) {
185
+ continue;
186
+ }
187
+ budget.textChars -= 1;
188
+ inline.push({ type: 'hardBreak' });
189
+ continue;
190
+ }
191
+
192
+ if (raw.type !== 'text' || typeof raw.text !== 'string' || !raw.text) {
193
+ continue;
194
+ }
195
+
196
+ // Truncate the tail once the doc-wide character cap is spent
197
+ const text =
198
+ raw.text.length > budget.textChars
199
+ ? raw.text.slice(0, budget.textChars)
200
+ : raw.text;
201
+ if (!text) {
202
+ continue;
203
+ }
204
+ budget.textChars -= text.length;
205
+
206
+ const marks = sanitizeMarks(raw.marks);
207
+ const prev = inline[inline.length - 1];
208
+
209
+ if (
210
+ prev?.type === 'text' &&
211
+ getMarkSetKey(prev.marks) === getMarkSetKey(marks)
212
+ ) {
213
+ // Merge adjacent runs with identical styling
214
+ prev.text += text;
215
+ } else if (marks) {
216
+ inline.push({ type: 'text', text, marks });
217
+ } else {
218
+ inline.push({ type: 'text', text });
219
+ }
220
+ }
221
+
222
+ return inline;
223
+ }
224
+
225
+ /**
226
+ * Collect the raw inline nodes of one raw block subtree in document order,
227
+ * inserting one hardBreak between text-bearing blocks. Used to flatten an
228
+ * over-deep container into a single paragraph without losing its text.
229
+ * Walks with an explicit stack so hostile deeply-nested input cannot
230
+ * overflow the call stack; the returned nodes are still raw (they go
231
+ * through sanitizeInlineContent exactly once afterwards).
232
+ */
233
+
234
+ function collectRawInlineNodes(rawBlock: Record<string, any>): any[] {
235
+ const out: any[] = [];
236
+ const stack: any[] = [rawBlock];
237
+ let visited = 0;
238
+
239
+ while (stack.length && visited < FILE_CONSTANTS.flattenVisitCap) {
240
+ const node = stack.pop();
241
+ visited += 1;
242
+
243
+ if (!isNodeObj(node) || !Array.isArray(node.content)) {
244
+ continue;
245
+ }
246
+
247
+ // Text-bearing blocks contribute their inline children as one chunk
248
+ const inlineChildren = node.content.filter(
249
+ (child: any) =>
250
+ isNodeObj(child) &&
251
+ (child.type === 'text' || child.type === 'hardBreak'),
252
+ );
253
+ if (inlineChildren.length) {
254
+ if (out.length) {
255
+ out.push({ type: 'hardBreak' });
256
+ }
257
+ out.push(...inlineChildren);
258
+ }
259
+
260
+ // Descend into block children in document order (reverse push)
261
+ for (let i = node.content.length - 1; i >= 0; i--) {
262
+ const child = node.content[i];
263
+ if (
264
+ isNodeObj(child) &&
265
+ child.type !== 'text' &&
266
+ child.type !== 'hardBreak'
267
+ ) {
268
+ stack.push(child);
269
+ }
270
+ }
271
+ }
272
+
273
+ return out;
274
+ }
275
+
276
+ /**
277
+ * Sanitize one raw block node whose type is legal at its position. Returns
278
+ * zero or one blocks: void leaves missing required attrs and lists left
279
+ * with no listItems come back empty. depth is the node's own depth (doc
280
+ * children sit at depth 1); rawDepth counts raw JSON descents.
281
+ */
282
+
283
+ function sanitizeBlockNode(
284
+ raw: Record<string, any>,
285
+ type: NoteBlockType,
286
+ depth: number,
287
+ rawDepth: number,
288
+ budget: SanitizeBudget,
289
+ ): NoteBlockNode[] {
290
+ if (budget.blocks <= 0) {
291
+ // Block cap reached; truncate the tail
292
+ return [];
293
+ }
294
+ budget.blocks -= 1;
295
+
296
+ if (type === 'paragraph') {
297
+ return [
298
+ {
299
+ type: 'paragraph',
300
+ content: sanitizeInlineContent(raw.content, budget),
301
+ },
302
+ ];
303
+ }
304
+
305
+ if (type === 'heading') {
306
+ // Clamp the heading level into 1-3 (garbage coerces to 1)
307
+ const rawLevel = isNodeObj(raw.attrs) ? Number(raw.attrs.level) : NaN;
308
+ const level = (
309
+ Number.isFinite(rawLevel)
310
+ ? Math.min(3, Math.max(1, Math.round(rawLevel)))
311
+ : 1
312
+ ) as NoteHeadingLevel;
313
+ return [
314
+ {
315
+ type: 'heading',
316
+ attrs: { level },
317
+ content: sanitizeInlineContent(raw.content, budget),
318
+ },
319
+ ];
320
+ }
321
+
322
+ if (type === 'divider') {
323
+ return [{ type: 'divider' }];
324
+ }
325
+
326
+ if (type === 'image') {
327
+ // Image blocks must carry a storage id and file uri; everything else
328
+ // (alt, width) is optional and anything unknown (_uploading, etc)
329
+ // is stripped by rebuilding attrs from scratch
330
+ const rawAttrs = isNodeObj(raw.attrs) ? raw.attrs : {};
331
+ const storageId =
332
+ typeof rawAttrs.storageId === 'string' ||
333
+ typeof rawAttrs.storageId === 'number'
334
+ ? String(rawAttrs.storageId)
335
+ : '';
336
+ const fileUri =
337
+ typeof rawAttrs.fileUri === 'string' ? rawAttrs.fileUri : '';
338
+
339
+ if (!storageId || !fileUri) {
340
+ // Unclaimed/incomplete images (mid-upload) never persist
341
+ budget.blocks += 1;
342
+ return [];
343
+ }
344
+
345
+ const block: NoteBlockNode = {
346
+ type: 'image',
347
+ attrs: { storageId, fileUri },
348
+ };
349
+ if (typeof rawAttrs.alt === 'string' && rawAttrs.alt) {
350
+ block.attrs!.alt = rawAttrs.alt;
351
+ }
352
+ if (
353
+ typeof rawAttrs.width === 'number' &&
354
+ Number.isFinite(rawAttrs.width) &&
355
+ rawAttrs.width > 0
356
+ ) {
357
+ block.attrs!.width = rawAttrs.width;
358
+ }
359
+ return [block];
360
+ }
361
+
362
+ if (type === 'bulletList' || type === 'orderedList') {
363
+ const children = sanitizeBlockContent(
364
+ raw.content,
365
+ type,
366
+ depth + 1,
367
+ rawDepth + 1,
368
+ budget,
369
+ );
370
+ if (!children.length) {
371
+ // A list with no surviving listItems renders nothing; drop it
372
+ return [];
373
+ }
374
+ return [{ type, content: children }];
375
+ }
376
+
377
+ // listItem/blockquote: containers that must never be left empty
378
+ const children = sanitizeBlockContent(
379
+ raw.content,
380
+ type,
381
+ depth + 1,
382
+ rawDepth + 1,
383
+ budget,
384
+ );
385
+ if (!children.length) {
386
+ children.push(createEmptyParagraph());
387
+ }
388
+ return [{ type, content: children }];
389
+ }
390
+
391
+ /**
392
+ * Sanitize one raw child list against a container's nesting rules; depth is
393
+ * the depth the produced children live at (doc children sit at depth 1).
394
+ * Illegal children are never kept as-is: headings become paragraphs where
395
+ * only paragraphs fit, illegal containers are unwrapped (their children
396
+ * re-processed against the same container), text blocks inside lists are
397
+ * wrapped into their own listItem, stray inline nodes are collected into a
398
+ * paragraph, containers past NOTE_MAX_DEPTH are flattened into a paragraph
399
+ * carrying their text, and void leaves with no legal spot are dropped.
400
+ */
401
+
402
+ function sanitizeBlockContent(
403
+ rawContent: unknown,
404
+ containerType: 'doc' | NoteBlockType,
405
+ depth: number,
406
+ rawDepth: number,
407
+ budget: SanitizeBudget,
408
+ ): NoteBlockNode[] {
409
+ if (!Array.isArray(rawContent) || rawDepth > FILE_CONSTANTS.maxRawNesting) {
410
+ return [];
411
+ }
412
+
413
+ const allowedTypes = NOTE_NESTING_RULES[containerType] || [];
414
+ const blocks: NoteBlockNode[] = [];
415
+ let strayInline: any[] = [];
416
+
417
+ /*
418
+ * Wrap buffered stray inline nodes (text in block position) into one
419
+ * paragraph, wherever a paragraph — or a listItem to hold it — fits.
420
+ */
421
+ const flushStrayInline = () => {
422
+ if (!strayInline.length) {
423
+ return;
424
+ }
425
+ const rawParagraph = { type: 'paragraph', content: strayInline };
426
+ strayInline = [];
427
+ if (allowedTypes.includes('paragraph')) {
428
+ blocks.push(
429
+ ...sanitizeBlockNode(
430
+ rawParagraph,
431
+ 'paragraph',
432
+ depth,
433
+ rawDepth,
434
+ budget,
435
+ ),
436
+ );
437
+ } else if (allowedTypes.includes('listItem')) {
438
+ blocks.push(
439
+ ...sanitizeBlockNode(
440
+ { type: 'listItem', content: [rawParagraph] },
441
+ 'listItem',
442
+ depth,
443
+ rawDepth,
444
+ budget,
445
+ ),
446
+ );
447
+ }
448
+ };
449
+
450
+ for (const rawChild of rawContent) {
451
+ if (!isNodeObj(rawChild) || typeof rawChild.type !== 'string') {
452
+ continue;
453
+ }
454
+
455
+ // Stray inline nodes in block position buffer up into one paragraph
456
+ if (rawChild.type === 'text' || rawChild.type === 'hardBreak') {
457
+ strayInline.push(rawChild);
458
+ continue;
459
+ }
460
+ flushStrayInline();
461
+
462
+ if (!(NOTE_BLOCK_TYPES as readonly string[]).includes(rawChild.type)) {
463
+ // Unknown block type; drop it
464
+ continue;
465
+ }
466
+
467
+ let raw = rawChild;
468
+ let type = rawChild.type as NoteBlockType;
469
+
470
+ if (isContainerBlockType(type) && depth >= NOTE_MAX_DEPTH) {
471
+ // Container past the depth cap: flatten its subtree into one
472
+ // paragraph carrying the text (hardBreaks between blocks)
473
+ raw = { type: 'paragraph', content: collectRawInlineNodes(raw) };
474
+ type = 'paragraph';
475
+ }
476
+
477
+ if (allowedTypes.includes(type)) {
478
+ blocks.push(...sanitizeBlockNode(raw, type, depth, rawDepth, budget));
479
+ } else if (
480
+ (type === 'heading' || type === 'paragraph') &&
481
+ allowedTypes.includes('paragraph')
482
+ ) {
483
+ // Text block where only paragraphs fit converts to a paragraph
484
+ blocks.push(
485
+ ...sanitizeBlockNode(
486
+ { ...raw, type: 'paragraph' },
487
+ 'paragraph',
488
+ depth,
489
+ rawDepth,
490
+ budget,
491
+ ),
492
+ );
493
+ } else if (isContainerBlockType(type)) {
494
+ // Illegal container: unwrap it and re-process its children
495
+ // against this same container (lists in blockquotes end up as
496
+ // paragraphs, listItems under doc splice their children in, ...)
497
+ blocks.push(
498
+ ...sanitizeBlockContent(
499
+ raw.content,
500
+ containerType,
501
+ depth,
502
+ rawDepth + 1,
503
+ budget,
504
+ ),
505
+ );
506
+ } else if (
507
+ (type === 'heading' || type === 'paragraph') &&
508
+ allowedTypes.includes('listItem')
509
+ ) {
510
+ // Text block directly inside a list wraps into its own listItem
511
+ blocks.push(
512
+ ...sanitizeBlockNode(
513
+ { type: 'listItem', content: [raw] },
514
+ 'listItem',
515
+ depth,
516
+ rawDepth,
517
+ budget,
518
+ ),
519
+ );
520
+ }
521
+ // Anything left (divider/image with no legal spot here) is dropped
522
+ }
523
+
524
+ flushStrayInline();
525
+ return blocks;
526
+ }
527
+
528
+ /**
529
+ * Sanitize one untrusted note document into the closed noteDoc vocabulary.
530
+ * Guarantees: only whitelisted node/mark types and attrs survive, nesting
531
+ * follows NOTE_NESTING_RULES, heading levels are clamped to 1-3, color and
532
+ * highlight tokens come from the palette, link hrefs are http(s)/mailto
533
+ * only, client-only fields (_key, _uploading) are gone, the doc respects
534
+ * NOTE_MAX_DEPTH / NOTE_MAX_BLOCKS / NOTE_MAX_TEXT_CHARS (tail truncated),
535
+ * adjacent identical-mark text runs are merged, empty runs are dropped, the
536
+ * doc is never empty, and version is stamped with NOTE_DOC_VERSION. The
537
+ * client runs this before save; the server runs it on mutation input.
538
+ */
539
+
540
+ export function sanitizeNoteDoc(input: unknown): NoteDoc {
541
+ if (!isNodeObj(input) || input.type !== 'doc') {
542
+ // Unknown roots coerce to a fresh empty document
543
+ return createEmptyNoteDoc();
544
+ }
545
+
546
+ const budget: SanitizeBudget = {
547
+ blocks: NOTE_MAX_BLOCKS,
548
+ textChars: NOTE_MAX_TEXT_CHARS,
549
+ };
550
+ const content = sanitizeBlockContent(input.content, 'doc', 1, 0, budget);
551
+
552
+ return {
553
+ type: 'doc',
554
+ version: NOTE_DOC_VERSION,
555
+ content: content.length ? content : [createEmptyParagraph()],
556
+ };
557
+ }
558
+
559
+ /**
560
+ * Recursively drop image blocks whose storageId is missing from the rels
561
+ * id set, keeping the container non-empty guarantees: a listItem or
562
+ * blockquote emptied by the filter gets one empty paragraph and a list
563
+ * emptied of its listItems is dropped.
564
+ */
565
+
566
+ function filterImageBlocksDeep(
567
+ blocks: NoteBlockNode[],
568
+ storageIdSet: Set<string>,
569
+ ): NoteBlockNode[] {
570
+ const out: NoteBlockNode[] = [];
571
+
572
+ for (const block of blocks) {
573
+ if (!isNodeObj(block)) {
574
+ continue;
575
+ }
576
+
577
+ if (block.type === 'image') {
578
+ // notes_storage_rels is the source of truth: no rel, no image
579
+ const storageId = block.attrs?.storageId;
580
+ if (
581
+ storageId === undefined ||
582
+ storageId === null ||
583
+ !storageIdSet.has(String(storageId))
584
+ ) {
585
+ continue;
586
+ }
587
+ out.push(block);
588
+ continue;
589
+ }
590
+
591
+ if (isContainerBlockType(block.type) && Array.isArray(block.content)) {
592
+ const children = filterImageBlocksDeep(
593
+ block.content as NoteBlockNode[],
594
+ storageIdSet,
595
+ );
596
+ if (
597
+ (block.type === 'bulletList' || block.type === 'orderedList') &&
598
+ !children.length
599
+ ) {
600
+ continue;
601
+ }
602
+ if (!children.length) {
603
+ children.push(createEmptyParagraph());
604
+ }
605
+ out.push({ ...block, content: children });
606
+ continue;
607
+ }
608
+
609
+ out.push(block);
610
+ }
611
+
612
+ return out;
613
+ }
614
+
615
+ /**
616
+ * Drop every image block whose storageId (string-compared) has no row in
617
+ * notes_storage_rels — the rels table is the source of truth for embedded
618
+ * files. Pure: returns a new document, never leaves the doc (or any
619
+ * container) empty, and never mutates the input.
620
+ */
621
+
622
+ export function filterImageNodesByStorageRels(
623
+ doc: NoteDoc,
624
+ storageIdSet: Set<string>,
625
+ ): NoteDoc {
626
+ const blocks =
627
+ isNodeObj(doc) && Array.isArray(doc.content) ? doc.content : [];
628
+ const content = filterImageBlocksDeep(blocks, storageIdSet);
629
+
630
+ return {
631
+ type: 'doc',
632
+ version:
633
+ isNodeObj(doc) && typeof doc.version === 'number'
634
+ ? doc.version
635
+ : NOTE_DOC_VERSION,
636
+ content: content.length ? content : [createEmptyParagraph()],
637
+ };
638
+ }
639
+
640
+ /**
641
+ * Collect the storageId of every image block in document order, deduped.
642
+ * The client sends this list with every content save so the server can
643
+ * reconcile notes_storage_rels.
644
+ */
645
+
646
+ export function collectNoteImageStorageIds(doc: NoteDoc): string[] {
647
+ const ids: string[] = [];
648
+ const seen = new Set<string>();
649
+
650
+ /*
651
+ * Walk one block list depth-first, gathering image storage ids.
652
+ */
653
+ const walk = (blocks: Array<NoteBlockNode | NoteInlineNode>) => {
654
+ for (const node of blocks) {
655
+ if (!isNodeObj(node)) {
656
+ continue;
657
+ }
658
+ const block = node as NoteBlockNode;
659
+ const storageId = block.attrs?.storageId;
660
+ if (
661
+ block.type === 'image' &&
662
+ storageId !== undefined &&
663
+ storageId !== null &&
664
+ String(storageId)
665
+ ) {
666
+ const id = String(storageId);
667
+ if (!seen.has(id)) {
668
+ seen.add(id);
669
+ ids.push(id);
670
+ }
671
+ } else if (
672
+ isContainerBlockType(block.type) &&
673
+ Array.isArray(block.content)
674
+ ) {
675
+ walk(block.content);
676
+ }
677
+ }
678
+ };
679
+
680
+ if (isNodeObj(doc) && Array.isArray(doc.content)) {
681
+ walk(doc.content);
682
+ }
683
+ return ids;
684
+ }
685
+
686
+ /**
687
+ * Extract one plain-text rendition of a note document, for previews and
688
+ * search indexing: text runs concatenate, hardBreaks become newlines, each
689
+ * text-bearing block becomes its own line, and void blocks (divider, image)
690
+ * plus empty blocks contribute nothing.
691
+ */
692
+
693
+ export function noteDocToPlainText(doc: NoteDoc): string {
694
+ const lines: string[] = [];
695
+
696
+ /*
697
+ * Walk one block list depth-first, pushing one line per text-bearing block.
698
+ */
699
+ const walk = (blocks: Array<NoteBlockNode | NoteInlineNode>) => {
700
+ for (const node of blocks) {
701
+ if (!isNodeObj(node)) {
702
+ continue;
703
+ }
704
+ const block = node as NoteBlockNode;
705
+ if (isContainerBlockType(block.type) && Array.isArray(block.content)) {
706
+ walk(block.content);
707
+ continue;
708
+ }
709
+ if (
710
+ (block.type === 'paragraph' || block.type === 'heading') &&
711
+ Array.isArray(block.content)
712
+ ) {
713
+ let line = '';
714
+ for (const inline of block.content as NoteInlineNode[]) {
715
+ if (!isNodeObj(inline)) {
716
+ continue;
717
+ }
718
+ if (inline.type === 'hardBreak') {
719
+ line += '\n';
720
+ } else if (
721
+ inline.type === 'text' &&
722
+ typeof inline.text === 'string'
723
+ ) {
724
+ line += inline.text;
725
+ }
726
+ }
727
+ if (line) {
728
+ lines.push(line);
729
+ }
730
+ }
731
+ }
732
+ };
733
+
734
+ if (isNodeObj(doc) && Array.isArray(doc.content)) {
735
+ walk(doc.content);
736
+ }
737
+ return lines.join('\n');
738
+ }
739
+
740
+ /**
741
+ * Build one text inline node, or an empty content list for a blank line.
742
+ */
743
+
744
+ function createTextContent(text: string): NoteInlineNode[] {
745
+ return text ? [{ type: 'text', text }] : [];
746
+ }
747
+
748
+ /**
749
+ * Convert markdown-lite plain text into a note document, for agent-written
750
+ * documents: '#'/'##'/'###' lines become headings, '- '/'* ' runs become
751
+ * bulletList items, '1. '-style runs become orderedList items, '---' lines
752
+ * become dividers, and every other non-blank line becomes a paragraph.
753
+ * The result always passes through sanitizeNoteDoc, so caps and nesting
754
+ * rules apply exactly as they do for human-written documents.
755
+ */
756
+
757
+ export function plainTextToNoteDoc(text: string): NoteDoc {
758
+ const blocks: NoteBlockNode[] = [];
759
+ let listType: 'bulletList' | 'orderedList' | null = null;
760
+ let listItems: NoteBlockNode[] = [];
761
+
762
+ /*
763
+ * Close the open list run, if any, into a single list block.
764
+ */
765
+ const flushList = () => {
766
+ if (listType && listItems.length) {
767
+ blocks.push({ type: listType, content: listItems });
768
+ }
769
+ listType = null;
770
+ listItems = [];
771
+ };
772
+
773
+ for (const rawLine of String(text ?? '').split('\n')) {
774
+ const line = rawLine.trim();
775
+
776
+ if (!line) {
777
+ flushList();
778
+ continue;
779
+ }
780
+
781
+ const headingMatch = line.match(/^(#{1,3})\s+(.*)$/);
782
+ if (headingMatch) {
783
+ flushList();
784
+ blocks.push({
785
+ type: 'heading',
786
+ attrs: { level: headingMatch[1].length as NoteHeadingLevel },
787
+ content: createTextContent(headingMatch[2].trim()),
788
+ });
789
+ continue;
790
+ }
791
+
792
+ if (/^(-{3,}|\*{3,})$/.test(line)) {
793
+ flushList();
794
+ blocks.push({ type: 'divider' });
795
+ continue;
796
+ }
797
+
798
+ const bulletMatch = line.match(/^[-*]\s+(.*)$/);
799
+ const orderedMatch = line.match(/^\d+[.)]\s+(.*)$/);
800
+ const itemText = bulletMatch?.[1] ?? orderedMatch?.[1];
801
+ if (typeof itemText === 'string') {
802
+ const nextListType = bulletMatch ? 'bulletList' : 'orderedList';
803
+ if (listType !== nextListType) {
804
+ flushList();
805
+ listType = nextListType;
806
+ }
807
+ listItems.push({
808
+ type: 'listItem',
809
+ content: [
810
+ { type: 'paragraph', content: createTextContent(itemText.trim()) },
811
+ ],
812
+ });
813
+ continue;
814
+ }
815
+
816
+ flushList();
817
+ blocks.push({ type: 'paragraph', content: createTextContent(line) });
818
+ }
819
+
820
+ flushList();
821
+
822
+ return sanitizeNoteDoc({
823
+ type: 'doc',
824
+ version: NOTE_DOC_VERSION,
825
+ content: blocks,
826
+ });
827
+ }