@wirecat/notion-cli 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +10 -4
  3. package/contracts/wirecat.json +650 -1
  4. package/dist/bin/notion.js +2 -2
  5. package/dist/bundle/{all-profiles-OETMCOLN.js → all-profiles-JGYLQZ5C.js} +9 -9
  6. package/dist/bundle/{anthropic-5Y3O2TYM.js → anthropic-S2VSMIKQ.js} +5 -5
  7. package/dist/bundle/{app-server-IVWBIVHC.js → app-server-SASYDBCA.js} +55 -46
  8. package/dist/bundle/{bun-EO636SAD.js → bun-LU5LP3JI.js} +2 -2
  9. package/dist/bundle/{bun-sqlite-C2T7QJ2M.js → bun-sqlite-JBSINB4O.js} +6 -6
  10. package/dist/bundle/{chunk-DIM5YWBU.js → chunk-22QQUKWA.js} +1 -1
  11. package/dist/bundle/{chunk-B4B65XIO.js → chunk-2F4QQ7WB.js} +3 -3
  12. package/dist/bundle/{chunk-2YR3RYT4.js → chunk-2F6VO5HA.js} +3 -3
  13. package/dist/bundle/chunk-2LWO3PDX.js +726 -0
  14. package/dist/bundle/{chunk-RSIS7BR7.js → chunk-3AL7QUS3.js} +20 -20
  15. package/dist/bundle/{chunk-RDZ7SVBZ.js → chunk-3Z4YTSRY.js} +3 -3
  16. package/dist/bundle/{chunk-QBC23NHD.js → chunk-4HWJOU7N.js} +1 -1
  17. package/dist/bundle/{chunk-WM7663C2.js → chunk-4IPURN72.js} +8 -8
  18. package/dist/bundle/{chunk-CLG2ISQH.js → chunk-4ZTVJHWU.js} +4 -4
  19. package/dist/bundle/{chunk-IQWEJEB5.js → chunk-5IYKVRH2.js} +26157 -21070
  20. package/dist/bundle/{chunk-7FII4DCE.js → chunk-5NFK5EM2.js} +7 -7
  21. package/dist/bundle/{chunk-K5TWMQSY.js → chunk-5QIQEUOG.js} +8 -8
  22. package/dist/bundle/{chunk-F6MLJ3V5.js → chunk-5RDNBG7D.js} +2 -2
  23. package/dist/bundle/{chunk-ST2UC7FS.js → chunk-5RSC54NA.js} +30 -26
  24. package/dist/bundle/{chunk-7N5QB6NL.js → chunk-6EVKHZKN.js} +5 -3
  25. package/dist/bundle/{chunk-EU5WCOMQ.js → chunk-6RA3EABS.js} +45 -34
  26. package/dist/bundle/{chunk-JKIN5TOU.js → chunk-AOCUKEAX.js} +4 -4
  27. package/dist/bundle/{chunk-OWJDC4CB.js → chunk-B26TQZKZ.js} +12 -12
  28. package/dist/bundle/{chunk-WK3OSDNV.js → chunk-B7ON6KPT.js} +7 -7
  29. package/dist/bundle/{chunk-RLSFOR2D.js → chunk-BNPTZ5ZB.js} +4 -4
  30. package/dist/bundle/{chunk-WVZFXI36.js → chunk-D7QSEEYW.js} +4 -4
  31. package/dist/bundle/{chunk-JK44XO2S.js → chunk-DH5PRHT4.js} +56 -56
  32. package/dist/bundle/chunk-EUIVXFLJ.js +259 -0
  33. package/dist/bundle/{chunk-64D5VUZ4.js → chunk-FPY6EJ7B.js} +67 -63
  34. package/dist/bundle/{chunk-EGTBL3MJ.js → chunk-FT3LN3HP.js} +1 -1
  35. package/dist/bundle/{chunk-NLDYZBTC.js → chunk-FWVBPRL4.js} +1129 -2555
  36. package/dist/bundle/{chunk-UWIA2G6Q.js → chunk-FXEJY4OL.js} +329 -528
  37. package/dist/bundle/{chunk-R6ZM45NF.js → chunk-G3EZFRSS.js} +88 -30
  38. package/dist/bundle/{chunk-B2XKEEFX.js → chunk-GZOUFX3C.js} +4 -4
  39. package/dist/bundle/{chunk-WWMB4UHF.js → chunk-HL52XXZX.js} +1 -1
  40. package/dist/bundle/{chunk-4GC5DBHW.js → chunk-KCLOUUYF.js} +3 -3
  41. package/dist/bundle/chunk-KFVDL2QS.js +146 -0
  42. package/dist/bundle/{chunk-35K5T6WV.js → chunk-KGERXYTV.js} +1 -1
  43. package/dist/bundle/{chunk-BWICUW7W.js → chunk-KM6WHPHI.js} +2 -2
  44. package/dist/bundle/{chunk-AE2KQ37N.js → chunk-LAYPFBOM.js} +6 -6
  45. package/dist/bundle/chunk-LLG2POQ7.js +170 -0
  46. package/dist/bundle/{chunk-B2WFKFYL.js → chunk-M3KB25D3.js} +20 -116
  47. package/dist/bundle/{chunk-RAZKIHGH.js → chunk-M7S2NDWB.js} +3 -3
  48. package/dist/bundle/chunk-MGUEZYFA.js +5546 -0
  49. package/dist/bundle/chunk-MY742GAD.js +1977 -0
  50. package/dist/bundle/chunk-MZU2YFBZ.js +823 -0
  51. package/dist/bundle/{chunk-AQZO3ITW.js → chunk-NOQ7B5N7.js} +2 -2
  52. package/dist/bundle/{chunk-QC3KOJT4.js → chunk-NQWV4WQO.js} +6 -6
  53. package/dist/bundle/{chunk-FF4DDBCB.js → chunk-ODBZNSZ6.js} +6 -6
  54. package/dist/bundle/{chunk-TR7R5DL4.js → chunk-OTV53F34.js} +9 -9
  55. package/dist/bundle/{chunk-KHOVVPLC.js → chunk-P7CUM5IB.js} +1 -1
  56. package/dist/bundle/{chunk-CWVAYQXI.js → chunk-RV64YUQX.js} +8 -8
  57. package/dist/bundle/{chunk-TSCIIXN3.js → chunk-SHJQ6JKG.js} +2 -2
  58. package/dist/bundle/{chunk-24FAYAML.js → chunk-SWAOWNKW.js} +3 -3
  59. package/dist/bundle/chunk-SZOVLP44.js +29 -0
  60. package/dist/bundle/chunk-TPX2M45D.js +385 -0
  61. package/dist/bundle/{chunk-UWW24JQF.js → chunk-TSDBSIFM.js} +3 -3
  62. package/dist/bundle/{chunk-YA4LSSDZ.js → chunk-VBHETQVV.js} +1435 -1788
  63. package/dist/bundle/{chunk-HRTIRRXR.js → chunk-VCIALTEM.js} +33 -6
  64. package/dist/bundle/{chunk-ESZT4WW3.js → chunk-WCSOH4JS.js} +3 -3
  65. package/dist/bundle/{chunk-HWRKURQH.js → chunk-WF4D56CA.js} +2 -2
  66. package/dist/bundle/chunk-WJHZMR2W.js +335 -0
  67. package/dist/bundle/chunk-X4TIMMKJ.js +16 -0
  68. package/dist/bundle/{chunk-XL2HXHP3.js → chunk-XF26XKTS.js} +2 -2
  69. package/dist/bundle/chunk-XFLCVHSQ.js +50 -0
  70. package/dist/bundle/{chunk-47R43UVJ.js → chunk-YMYUBZWT.js} +19 -19
  71. package/dist/bundle/{chunk-3D3PFXBP.js → chunk-YNTLT3Z3.js} +10 -15
  72. package/dist/bundle/{chunk-GA3URWIF.js → chunk-YVI5SQPY.js} +1 -1
  73. package/dist/bundle/{chunk-XC5CKHX2.js → chunk-Z56QFOBR.js} +1 -1
  74. package/dist/bundle/{chunk-EPAZ7DJB.js → chunk-ZKAEZXUP.js} +42 -38
  75. package/dist/bundle/{chunk-66PL7P4C.js → chunk-ZZ32DXTH.js} +1 -1
  76. package/dist/bundle/command-contract-JS5V27NX.js +38 -0
  77. package/dist/bundle/{command-server-entry-A66DJ3MH.js → command-server-entry-UFSG7KRO.js} +26 -23
  78. package/dist/bundle/decode-7LLWTSPT.js +297 -0
  79. package/dist/bundle/{dispatch-FEKU5UXC.js → dispatch-2GY6JIJH.js} +8 -8
  80. package/dist/bundle/{dist-YFKABFFF.js → dist-ILNOLGYN.js} +1 -1
  81. package/dist/bundle/{echarts-XD2JSWU4.js → echarts-BXX4OQWC.js} +2 -2
  82. package/dist/bundle/{embed-F3HYGAF7.js → embed-JXFNBTKH.js} +6 -6
  83. package/dist/bundle/{embedder-GSEDDUH7.js → embedder-57YZ44KO.js} +9 -9
  84. package/dist/bundle/{failure-HDJLR2YJ.js → failure-MYT4HPE3.js} +2 -2
  85. package/dist/bundle/{first-run-TXNTIUSP.js → first-run-3PF7T74J.js} +12 -11
  86. package/dist/bundle/first-screen-7BEROEQR.js +36 -0
  87. package/dist/bundle/{instructions-NZGJ4FW5.js → instructions-2VECIDXF.js} +1 -1
  88. package/dist/bundle/{mcp-VFIOZDVY.js → mcp-O6ACR2DX.js} +2 -2
  89. package/dist/bundle/mdast-util-from-markdown-R66F4HZA.js +1958 -0
  90. package/dist/bundle/mdast-util-gfm-LN2ELINH.js +2699 -0
  91. package/dist/bundle/meeting-combined-PPUQ3KBR.js +24 -0
  92. package/dist/bundle/meeting-model-ZNMYKMCD.js +26 -0
  93. package/dist/bundle/meeting-semantic-ETN3A4BJ.js +22 -0
  94. package/dist/bundle/micromark-extension-gfm-5X7YT43T.js +1838 -0
  95. package/dist/bundle/{node-RPKPDYQS.js → node-MPEQSFI3.js} +2 -2
  96. package/dist/bundle/{node-sqlite-KH2UUYVO.js → node-sqlite-WA32MYSJ.js} +7 -7
  97. package/dist/bundle/notion.js +13 -13
  98. package/dist/bundle/{oauth-NKAI7TQD.js → oauth-IAFZG3IR.js} +7 -7
  99. package/dist/bundle/{open-WSAEAA2V.js → open-M3JQUC5G.js} +5 -5
  100. package/dist/bundle/{openai-JPVDGHG5.js → openai-HXUEHUSD.js} +30 -28
  101. package/dist/bundle/{process-5ZFVKOQX.js → process-F6TKXWWA.js} +1 -1
  102. package/dist/bundle/{program-M3D56D6T.js → program-Y7JAB6TG.js} +5289 -924
  103. package/dist/bundle/{prompt-FROYQ5LV.js → prompt-IMUQLZD2.js} +5 -5
  104. package/dist/bundle/{recognize-NYCHQMCX.js → recognize-2MZAYHAA.js} +4 -4
  105. package/dist/bundle/{remote-4OERF3Z4.js → remote-OV4LB6VR.js} +10 -10
  106. package/dist/bundle/{rerank-TEGXFUWY.js → rerank-ZIULUS34.js} +7 -7
  107. package/dist/bundle/{schemas-MZNNOEYN.js → schemas-DIVZS6TU.js} +1 -1
  108. package/dist/bundle/{serve-HLYYBAXY.js → serve-YU7QBP6L.js} +9 -9
  109. package/dist/bundle/server-FKQET4ZO.js +71 -0
  110. package/dist/bundle/{server-D5OYNEUW.js → server-LGMNONSB.js} +47 -38
  111. package/dist/bundle/services-5WY4DCPJ.js +581 -0
  112. package/dist/bundle/{sqlite-runtime-H2S5RR2F.js → sqlite-runtime-5MXZDETH.js} +6 -6
  113. package/dist/bundle/{state-OPOXCDZL.js → state-LWMZH2KI.js} +6 -6
  114. package/dist/bundle/{store-NHMXEJPD.js → store-EPZYV4VW.js} +17 -13
  115. package/dist/bundle/{store-Y3KRLCJ7.js → store-QE6FEIZD.js} +25 -20
  116. package/dist/bundle/store-maintenance-command-ZUUUFCHL.js +62 -0
  117. package/dist/commands/documents.d.ts +2 -1
  118. package/dist/commands/documents.d.ts.map +1 -1
  119. package/dist/commands/documents.js +2 -2
  120. package/dist/commands/documents.js.map +1 -1
  121. package/dist/commands/library.d.ts +10 -0
  122. package/dist/commands/library.d.ts.map +1 -0
  123. package/dist/commands/library.js +468 -0
  124. package/dist/commands/library.js.map +1 -0
  125. package/dist/commands/session.d.ts.map +1 -1
  126. package/dist/commands/session.js +4 -3
  127. package/dist/commands/session.js.map +1 -1
  128. package/dist/context.d.ts +5 -0
  129. package/dist/context.d.ts.map +1 -1
  130. package/dist/context.js +12 -3
  131. package/dist/context.js.map +1 -1
  132. package/dist/identity.d.ts.map +1 -1
  133. package/dist/identity.js +1 -0
  134. package/dist/identity.js.map +1 -1
  135. package/dist/knowledge.d.ts +27 -0
  136. package/dist/knowledge.d.ts.map +1 -0
  137. package/dist/knowledge.js +87 -0
  138. package/dist/knowledge.js.map +1 -0
  139. package/dist/library.d.ts +44 -0
  140. package/dist/library.d.ts.map +1 -0
  141. package/dist/library.js +149 -0
  142. package/dist/library.js.map +1 -0
  143. package/dist/notion/client.d.ts +4 -1
  144. package/dist/notion/client.d.ts.map +1 -1
  145. package/dist/notion/client.js +5 -2
  146. package/dist/notion/client.js.map +1 -1
  147. package/dist/notion/errors.d.ts.map +1 -1
  148. package/dist/notion/errors.js +26 -1
  149. package/dist/notion/errors.js.map +1 -1
  150. package/dist/notion/reads.d.ts +4 -0
  151. package/dist/notion/reads.d.ts.map +1 -1
  152. package/dist/program.js +2 -2
  153. package/dist/program.js.map +1 -1
  154. package/dist/sync/cursor.d.ts +81 -0
  155. package/dist/sync/cursor.d.ts.map +1 -1
  156. package/dist/sync/cursor.js +63 -2
  157. package/dist/sync/cursor.js.map +1 -1
  158. package/dist/sync/files.d.ts +77 -0
  159. package/dist/sync/files.d.ts.map +1 -0
  160. package/dist/sync/files.js +12 -0
  161. package/dist/sync/files.js.map +1 -0
  162. package/dist/sync/markdown.d.ts +4 -1
  163. package/dist/sync/markdown.d.ts.map +1 -1
  164. package/dist/sync/markdown.js +8 -6
  165. package/dist/sync/markdown.js.map +1 -1
  166. package/dist/sync/source.d.ts +6 -59
  167. package/dist/sync/source.d.ts.map +1 -1
  168. package/dist/sync/source.js +616 -255
  169. package/dist/sync/source.js.map +1 -1
  170. package/dist/version.d.ts +1 -1
  171. package/dist/version.js +1 -1
  172. package/package.json +3 -3
  173. package/skills/notion-cli/SKILL.md +12 -1
  174. package/dist/bundle/command-contract-6G5DC2FN.js +0 -35
  175. package/dist/bundle/decode-7XOFRAAT.js +0 -163
  176. package/dist/bundle/first-screen-JZPJND7J.js +0 -33
  177. package/dist/bundle/server-LWZGVMNW.js +0 -62
  178. package/dist/bundle/store-maintenance-command-D4W7WSLQ.js +0 -53
  179. package/dist/commands/comments.d.ts +0 -3
  180. package/dist/commands/comments.d.ts.map +0 -1
  181. package/dist/commands/comments.js +0 -114
  182. package/dist/commands/comments.js.map +0 -1
  183. package/dist/sample/comments.d.ts +0 -61
  184. package/dist/sample/comments.d.ts.map +0 -1
  185. package/dist/sample/comments.js +0 -39
  186. package/dist/sample/comments.js.map +0 -1
  187. package/dist/sample/records.d.ts +0 -16
  188. package/dist/sample/records.d.ts.map +0 -1
  189. package/dist/sample/records.js +0 -22
  190. package/dist/sample/records.js.map +0 -1
  191. package/dist/sample/transport.d.ts +0 -42
  192. package/dist/sample/transport.d.ts.map +0 -1
  193. package/dist/sample/transport.js +0 -153
  194. package/dist/sample/transport.js.map +0 -1
  195. /package/dist/bundle/{chunk-ZI3YTXSF.js → chunk-VKE77B3F.js} +0 -0
@@ -1,21 +1,17 @@
1
1
  import { CliError, isCliError } from "@wirecat/cli-base";
2
+ import { deadlineMargin } from "@wirecat/cli-core/background";
2
3
  import { withoutSignedLinks } from "../notion/links.js";
3
- import { decodeCursor, encodeCursor } from "./cursor.js";
4
+ import { decodeCursor, decodeListPosition, encodeCursor, encodeListPosition, } from "./cursor.js";
5
+ import { UNTITLED, WORKSPACE_ROOT, } from "./files.js";
4
6
  import { frontMatter, frontMatterLines, titleOf } from "./front-matter.js";
5
7
  import { pageText } from "./markdown.js";
6
- /** The folder that stands for everything the token sees, the scope when no folder is chosen. */
7
- export const WORKSPACE_ROOT = "notion-workspace";
8
+ export { isNotionDocument, isNotionFolder, UNTITLED, WORKSPACE_ROOT, } from "./files.js";
8
9
  const MINUTE = 60_000;
9
10
  /** Notion rounds `last_edited_time` to the minute; a read this soon after an edit may miss another in that minute. */
10
11
  export const SETTLE_MS = 3 * MINUTE;
11
12
  export const MIN_OVERLAP_MS = 2 * MINUTE;
12
13
  const DEFAULTS = { overlapMs: 10 * MINUTE, walkEveryMs: 24 * 60 * MINUTE, maxRequests: 2000 };
13
14
  const PAGE_SIZE = 100;
14
- /**
15
- * Until cli-core plans a page with children as both a folder and a document (C2), only the workspace and databases
16
- * are folders: the engine syncs top-level pages and database rows, not pages under pages.
17
- */
18
- export const isNotionFolder = (file) => file.providerMetadata.kind === "workspace" || file.providerMetadata.kind === "database";
19
15
  const parentId = (parent) => {
20
16
  switch (parent.type) {
21
17
  case "workspace":
@@ -35,7 +31,12 @@ const later = (a, b) => (!a ? b : !b ? a : Date.parse(a) >= Date.parse(b) ? a :
35
31
  const isNotFound = (error) => isCliError(error) && error.code === "not_found";
36
32
  /** Answers about one item, not the sync: a linked database view answers 404 by design, a restricted page 403. */
37
33
  const isItemError = (error) => isCliError(error) && (error.code === "not_found" || error.code === "permission_error");
34
+ /** Notion's own 400, such as a list position it no longer takes; not this code's refusals, which carry no status. */
35
+ const isRefused = (error) => isCliError(error) && error.code === "validation_error" && error.details.status === 400;
38
36
  const text = (parts) => parts.map((part) => part.plain_text).join("");
37
+ const OUT_OF_TIME = new Error("the run's deadline is near");
38
+ /** Whether a Notion pass is still under way: the next `changes()` goes on with its tasks. */
39
+ export const passUnderWay = (token) => token !== undefined && decodeCursor(token).pass !== undefined;
39
40
  export const notionSource = (notion, options = {}) => {
40
41
  const overlapMs = options.overlapMs ?? DEFAULTS.overlapMs;
41
42
  if (overlapMs < MIN_OVERLAP_MS)
@@ -45,10 +46,24 @@ export const notionSource = (notion, options = {}) => {
45
46
  const roots = options.roots?.length ? options.roots : [WORKSPACE_ROOT];
46
47
  const now = options.now ?? Date.now;
47
48
  const warn = options.warn ?? (() => undefined);
49
+ const clock = options.clock ?? Date.now;
50
+ const deadline = options.deadline;
51
+ const margin = deadline ? deadlineMargin(deadline) : 0;
48
52
  let requests = 0;
49
- const counted = (call) => (...args) => {
53
+ /** Set while `changes()` runs: a request that could end past the deadline is not sent. */
54
+ let timed = false;
55
+ let slowest = 0;
56
+ const counted = (call) => async (...args) => {
57
+ const started = clock();
58
+ if (timed && deadline && started + slowest + margin >= deadline.endsAt)
59
+ throw OUT_OF_TIME;
50
60
  requests++;
51
- return call.apply(notion, args);
61
+ try {
62
+ return await call.apply(notion, args);
63
+ }
64
+ finally {
65
+ slowest = Math.max(slowest, clock() - started);
66
+ }
52
67
  };
53
68
  const reads = {
54
69
  self: counted(notion.self),
@@ -60,14 +75,18 @@ export const notionSource = (notion, options = {}) => {
60
75
  blockChildren: counted(notion.blockChildren),
61
76
  pageMarkdown: counted(notion.pageMarkdown),
62
77
  };
63
- // Read once per call: the state the engine holds does not change while the source lists.
78
+ // The state the engine holds does not change while the source lists, and parsing it costs as much as a request.
79
+ /** Folders listed again in this run after Notion stopped taking their saved position. */
80
+ const restarted = new Set();
81
+ let held;
64
82
  let known = new Map();
65
83
  // Containers resolved within one call; a page's parent is re-read on the next one, as it may have moved.
66
84
  let containers = new Map();
67
85
  let accessible = new Set();
68
86
  let newestSeen = Number.NEGATIVE_INFINITY;
69
87
  const fresh = () => {
70
- known = new Map([...(options.known?.() ?? [])].map((file) => [file.id, file]));
88
+ held ??= new Map([...(options.known?.() ?? [])].map((file) => [file.id, file]));
89
+ known = held;
71
90
  containers = new Map();
72
91
  accessible = new Set(known.keys());
73
92
  };
@@ -110,7 +129,7 @@ export const notionSource = (notion, options = {}) => {
110
129
  const row = page.parent.type === "data_source_id" || page.parent.type === "database_id";
111
130
  return {
112
131
  id: page.id,
113
- name: titleOf(page.properties),
132
+ name: titleOf(page.properties).trim() || UNTITLED,
114
133
  mime: "application/vnd.notion.page",
115
134
  parents: [await containerOf(page.parent)],
116
135
  version: versionOf(page.last_edited_time),
@@ -127,11 +146,38 @@ export const notionSource = (notion, options = {}) => {
127
146
  },
128
147
  };
129
148
  };
149
+ /**
150
+ * A page as its parent's listing gives it, with no read of its own. A page under a page has only its title for
151
+ * properties, and the block names it, its times and its authors (https://developers.notion.com/reference/block).
152
+ */
153
+ const childPageFile = (block, container) => {
154
+ accessible.add(block.id);
155
+ return {
156
+ id: block.id,
157
+ name: block.child_page?.title.trim() || UNTITLED,
158
+ mime: "application/vnd.notion.page",
159
+ parents: [container],
160
+ version: versionOf(block.last_edited_time),
161
+ modifiedAt: block.last_edited_time,
162
+ createdAt: block.created_time,
163
+ // The block has no link. Notion's own form is https://app.notion.com/p/{page-id}, and the page's link replaces
164
+ // it when its text is read (https://developers.notion.com/reference/versioning).
165
+ url: known.get(block.id)?.url || `https://app.notion.com/p/${block.id.replaceAll("-", "")}`,
166
+ trashed: block.in_trash ?? false,
167
+ canDownload: true,
168
+ providerMetadata: {
169
+ kind: "page",
170
+ parent: { type: block.parent.type, id: parentId(block.parent) },
171
+ ...(block.created_by ? { createdBy: block.created_by.id } : {}),
172
+ ...(block.last_edited_by ? { lastEditedBy: block.last_edited_by.id } : {}),
173
+ },
174
+ };
175
+ };
130
176
  const databaseFile = async (database) => {
131
177
  accessible.add(database.id);
132
178
  return {
133
179
  id: database.id,
134
- name: text(database.title),
180
+ name: text(database.title).trim() || UNTITLED,
135
181
  mime: "application/vnd.notion.database",
136
182
  parents: [await containerOf(database.parent)],
137
183
  version: database.last_edited_time,
@@ -171,53 +217,109 @@ export const notionSource = (notion, options = {}) => {
171
217
  return databaseFile(await reads.retrieveDatabase(id));
172
218
  }
173
219
  };
174
- /** One `created_time` window of a data source; Notion stops a query at 10,000 rows and says so. */
175
- const rowWindow = async (database, source, after, since) => {
220
+ /** One page of a data source's rows, oldest first: created from `after` on, and edited since `since`. */
221
+ const rowPage = (source, after, since, start) => {
176
222
  const filters = [
177
223
  ...(since ? [{ timestamp: "last_edited_time", last_edited_time: { on_or_after: since } }] : []),
178
224
  ...(after ? [{ timestamp: "created_time", created_time: { on_or_after: after } }] : []),
179
225
  ];
180
226
  const filter = filters.length > 1 ? { and: filters } : filters[0];
181
- const rows = [];
182
- let incomplete = false;
183
- let start;
184
- do {
185
- const page = await reads.queryDataSource(source, {
186
- ...(filter ? { filter } : {}),
187
- sorts: [{ timestamp: "created_time", direction: "ascending" }],
188
- page_size: PAGE_SIZE,
189
- ...(start ? { start_cursor: start } : {}),
227
+ return reads.queryDataSource(source, {
228
+ ...(filter ? { filter } : {}),
229
+ sorts: [{ timestamp: "created_time", direction: "ascending" }],
230
+ page_size: PAGE_SIZE,
231
+ ...(start ? { start_cursor: start } : {}),
232
+ });
233
+ };
234
+ /**
235
+ * A page of rows and where the next starts: from its last row's minute on, as Notion rounds `created_time` to the
236
+ * minute, or by the query's own position while a whole page shares one minute. `missing`: the known rows created
237
+ * within the span the page covered that it did not return, to read directly before any counts as gone.
238
+ */
239
+ const rowsPage = async (database, source, at, since) => {
240
+ const page = await rowPage(source, at.after, since, at.start);
241
+ const last = page.results.at(-1)?.created_time;
242
+ const more = page.has_more && page.next_cursor && last ? { cursor: page.next_cursor, last } : undefined;
243
+ const dense = more && at.after !== undefined && Date.parse(more.last) <= Date.parse(at.after);
244
+ const seen = [...(at.seen ?? []), ...page.results.map((row) => row.id)];
245
+ if (dense && isCut(page))
246
+ throw new CliError("validation_error", `database ${database} has more than 10000 rows created in one minute`, {
247
+ reason: "notion.window-too-dense",
248
+ database,
190
249
  });
191
- for (const result of page.results)
192
- rows.push(result);
193
- if (page.request_status?.type === "incomplete")
194
- incomplete = true;
195
- start = page.has_more && page.next_cursor ? page.next_cursor : undefined;
196
- } while (start);
197
- let next;
198
- if (incomplete) {
199
- next = rows.at(-1)?.created_time;
200
- if (!next || next === after)
201
- throw new CliError("validation_error", `database ${database} has more than 10000 rows created in one minute`, {
202
- reason: "notion.window-too-dense",
203
- database,
204
- });
250
+ const from = at.after ? Date.parse(at.after) : Number.NEGATIVE_INFINITY;
251
+ const to = more ? Date.parse(more.last) : Number.POSITIVE_INFINITY;
252
+ const shown = new Set(seen);
253
+ const missing = [...known.values()].filter((file) => {
254
+ const created = Date.parse(file.createdAt ?? "");
255
+ return (file.providerMetadata.kind === "row" &&
256
+ file.providerMetadata.parent?.id === source &&
257
+ !shown.has(file.id) &&
258
+ created >= from &&
259
+ created < to);
260
+ });
261
+ const next = dense
262
+ ? { ...(at.after ? { after: at.after } : {}), start: more.cursor, seen }
263
+ : more
264
+ ? { after: more.last }
265
+ : undefined;
266
+ return { rows: page.results, missing, next };
267
+ };
268
+ /**
269
+ * One page of a page's blocks: the child pages and databases it names, and the blocks still to list, the page first,
270
+ * then the blocks inside it that hold more (a child page can sit in a column or a toggle).
271
+ */
272
+ const blocksPage = async (at) => {
273
+ const blocks = [...at.blocks];
274
+ const seen = [...at.seen];
275
+ const pages = [];
276
+ const databases = [];
277
+ const head = blocks[0];
278
+ try {
279
+ const page = await reads.blockChildren(head.id, head.start);
280
+ for (const block of page.results) {
281
+ if (block.in_trash)
282
+ continue;
283
+ if (block.type === "child_page" || block.type === "child_database")
284
+ seen.push(block.id);
285
+ if (block.type === "child_page")
286
+ pages.push(block);
287
+ else if (block.type === "child_database")
288
+ databases.push(block.id);
289
+ else if (block.has_children)
290
+ blocks.push({ id: block.id });
291
+ }
292
+ if (page.has_more && page.next_cursor)
293
+ blocks[0] = { id: head.id, start: page.next_cursor };
294
+ else
295
+ blocks.shift();
296
+ }
297
+ catch (error) {
298
+ if (!isItemError(error))
299
+ throw error;
300
+ // The known children it hides are read one by one before any counts as gone.
301
+ warn({
302
+ id: head.id,
303
+ code: error.code,
304
+ reason: "notion.left-out",
305
+ message: "the blocks inside were left out of this sync: Notion would not list them",
306
+ });
307
+ blocks.shift();
205
308
  }
206
- return { rows, next };
309
+ return { pages, databases, blocks, seen };
207
310
  };
208
- const allRows = async (database) => {
209
- const files = new Map();
210
- for (const source of database.data_sources) {
211
- let after;
212
- do {
213
- const window = await rowWindow(database.id, source.id, after, null);
214
- for (const row of window.rows)
215
- if (!row.in_trash)
216
- files.set(row.id, await pageFile(row));
217
- after = window.next;
218
- } while (after);
311
+ /** A database a page's listing names; a linked view of one elsewhere answers 404, and is left out with a warning. */
312
+ const childDatabase = async (id) => {
313
+ try {
314
+ return await databaseFile(await reads.retrieveDatabase(id));
315
+ }
316
+ catch (error) {
317
+ if (!isItemError(error))
318
+ throw error;
319
+ const code = error.code;
320
+ warn({ id, code, reason: "notion.child-unreadable", message: "a child Notion would not give was left out" });
321
+ return undefined;
219
322
  }
220
- return [...files.values()];
221
323
  };
222
324
  const searchPage = (kind, start) => reads.search({
223
325
  filter: { property: "object", value: kind },
@@ -241,12 +343,16 @@ export const notionSource = (notion, options = {}) => {
241
343
  if (isCut(page))
242
344
  warn({
243
345
  code: "provider_error",
346
+ reason: "notion.search-capped",
244
347
  message: `Notion's search gave only the ${results.length} most recently edited ${kind}s; a top-level one it left out is found once it is edited`,
245
348
  });
246
349
  } while (start);
247
350
  return results;
248
351
  };
249
- /** A database search named, or undefined when Notion will not give it: search entries can be stale. */
352
+ /**
353
+ * A database, or why Notion will not give it: `gone` on a 404 (search entries can be stale, a linked view always
354
+ * answers so), `unreadable` on a 403, which says nothing about whether it is still there.
355
+ */
250
356
  const readDatabase = async (id) => {
251
357
  try {
252
358
  return await reads.retrieveDatabase(id);
@@ -254,28 +360,21 @@ export const notionSource = (notion, options = {}) => {
254
360
  catch (error) {
255
361
  if (!isItemError(error))
256
362
  throw error;
257
- warn({ id, code: error.code, message: "a database search listed could not be read" });
258
- return undefined;
259
- }
260
- };
261
- const childPages = async (blockId, found) => {
262
- let start;
263
- do {
264
- const page = await reads.blockChildren(blockId, start);
265
- for (const block of page.results) {
266
- if (block.in_trash)
267
- continue;
268
- if (block.type === "child_page")
269
- found.pages.push(block.id);
270
- else if (block.type === "child_database")
271
- found.databases.push(block.id);
272
- else if (block.has_children)
273
- await childPages(block.id, found);
363
+ if (isNotFound(error)) {
364
+ warn({ id, code: "not_found", reason: "notion.database-unreadable", message: "a database could not be read" });
365
+ return "gone";
274
366
  }
275
- start = page.has_more && page.next_cursor ? page.next_cursor : undefined;
276
- } while (start);
277
- return found;
367
+ warn({
368
+ id,
369
+ code: error.code,
370
+ reason: "notion.kept-unconfirmed",
371
+ message: "kept as it was: Notion would not show the database",
372
+ });
373
+ return "unreadable";
374
+ }
278
375
  };
376
+ const isGone = (database) => database === "gone" || (database !== "unreadable" && database.in_trash);
377
+ /** The top of the workspace, from search: Notion lists no children of a workspace. */
279
378
  const listed = async (id) => {
280
379
  if (id === WORKSPACE_ROOT) {
281
380
  const pages = (await searchAll("page"));
@@ -289,7 +388,7 @@ export const notionSource = (notion, options = {}) => {
289
388
  if (databases.has(id) || source.in_trash)
290
389
  continue;
291
390
  const database = await readDatabase(id);
292
- if (database)
391
+ if (typeof database === "object")
293
392
  databases.set(id, database);
294
393
  }
295
394
  const files = [];
@@ -301,30 +400,7 @@ export const notionSource = (notion, options = {}) => {
301
400
  files.push(await databaseFile(database));
302
401
  return files.filter((file) => file.parents[0] === WORKSPACE_ROOT);
303
402
  }
304
- const kind = known.get(id)?.providerMetadata.kind ?? (await retrieve(id)).providerMetadata.kind;
305
- if (kind === "database")
306
- return allRows(await reads.retrieveDatabase(id));
307
- if (kind === "row")
308
- return [];
309
- const found = await childPages(id, { pages: [], databases: [] });
310
- const files = [];
311
- const child = async (id, read) => {
312
- try {
313
- const file = await read();
314
- if (!file.trashed)
315
- files.push(file);
316
- }
317
- catch (error) {
318
- if (!isItemError(error))
319
- throw error;
320
- warn({ id, code: error.code, message: "a child Notion would not give was left out" });
321
- }
322
- };
323
- for (const page of found.pages)
324
- await child(page, async () => pageFile(await reads.retrievePage(page)));
325
- for (const database of found.databases)
326
- await child(database, async () => databaseFile(await reads.retrieveDatabase(database)));
327
- return files;
403
+ return [];
328
404
  };
329
405
  /** Known items missing from a listing, each read directly: gone only on 404 or the trash, kept on any doubt. */
330
406
  const confirm = async (missing, container, listing) => {
@@ -343,13 +419,113 @@ export const notionSource = (notion, options = {}) => {
343
419
  listing.gone.push(file.id);
344
420
  else if (isItemError(error)) {
345
421
  listing.files.push(file);
346
- warn({ id: file.id, code: error.code, message: "kept as it was: Notion would not say" });
422
+ warn({
423
+ id: file.id,
424
+ code: error.code,
425
+ reason: "notion.kept-unconfirmed",
426
+ message: "kept as it was: Notion would not say",
427
+ });
347
428
  }
348
429
  else
349
430
  throw error;
350
431
  }
351
432
  }
352
433
  };
434
+ /**
435
+ * One page of a folder's children for the engine's walk, with the position of the next in `cursor`. A database goes a
436
+ * page of rows at a time, a page a page of blocks at a time. Known children a page did not show are read directly
437
+ * before any counts as gone: for rows, those created within the span the page covers; for a page's children, those
438
+ * missing once its last block is listed. The workspace is one listing, as search has no order to resume a span by.
439
+ */
440
+ const childrenPage = async (id, token) => {
441
+ if (id === WORKSPACE_ROOT)
442
+ return { files: (await listChildren(id)).files };
443
+ let at;
444
+ if (token === undefined) {
445
+ const kind = known.get(id)?.providerMetadata.kind ?? (await retrieve(id)).providerMetadata.kind;
446
+ if (kind === "row")
447
+ return { files: [] };
448
+ if (kind === "database") {
449
+ const database = await readDatabase(id);
450
+ if (typeof database !== "object" || !database.data_sources.length)
451
+ return { files: [] };
452
+ at = { k: "rows", sources: database.data_sources.map((source) => source.id) };
453
+ }
454
+ else
455
+ at = { k: "blocks", blocks: [{ id }], seen: [] };
456
+ }
457
+ else
458
+ at = decodeListPosition(token);
459
+ const files = [];
460
+ const listing = { files: [], gone: [], moved: [] };
461
+ // Notion answers 400 validation_error to a start_cursor it no longer takes. On a later page that is the saved
462
+ // position going stale: as not_found the engine lists the folder again from its first page and drops nothing.
463
+ // Only the request sent with the saved start_cursor: a 400 on any other (a block Notion cannot list) is the
464
+ // answer. A folder already listed again in this run that goes stale again fails, so it cannot loop.
465
+ const stale = (error, start) => {
466
+ if (token === undefined || start === undefined || !isRefused(error) || restarted.has(id))
467
+ return error;
468
+ restarted.add(id);
469
+ return new CliError("not_found", `Notion no longer takes the saved position in ${id}; it is listed again`, {
470
+ reason: "notion.listing-stale",
471
+ });
472
+ };
473
+ if (at.k === "rows") {
474
+ const source = at.sources[0];
475
+ let page;
476
+ try {
477
+ page = await rowsPage(id, source, at, null);
478
+ }
479
+ catch (error) {
480
+ if (!isItemError(error))
481
+ throw stale(error, at.start);
482
+ warn({
483
+ id: source,
484
+ code: error.code,
485
+ reason: "notion.left-out",
486
+ message: `a data source of database ${id} was left out: Notion would not query it`,
487
+ });
488
+ // Its rows stay as the sync holds them: a refusal says nothing of them, and the walk drops what it does not list.
489
+ for (const file of known.values())
490
+ if (file.providerMetadata.kind === "row" && file.providerMetadata.parent?.id === source)
491
+ files.push(file);
492
+ const rest = at.sources.slice(1);
493
+ return rest.length ? { files, cursor: encodeListPosition({ k: "rows", sources: rest }) } : { files };
494
+ }
495
+ for (const row of page.rows)
496
+ if (!row.in_trash)
497
+ files.push(await pageFile(row));
498
+ await confirm(page.missing, id, listing);
499
+ for (const file of listing.files)
500
+ files.push(file);
501
+ const next = page.next
502
+ ? { k: "rows", sources: at.sources, ...page.next }
503
+ : at.sources.length > 1
504
+ ? { k: "rows", sources: at.sources.slice(1) }
505
+ : undefined;
506
+ return next ? { files, cursor: encodeListPosition(next) } : { files };
507
+ }
508
+ let page;
509
+ try {
510
+ page = await blocksPage(at);
511
+ }
512
+ catch (error) {
513
+ throw stale(error, at.blocks[0]?.start);
514
+ }
515
+ for (const block of page.pages)
516
+ files.push(childPageFile(block, id));
517
+ for (const database of page.databases) {
518
+ const file = await childDatabase(database);
519
+ if (file && !file.trashed)
520
+ files.push(file);
521
+ }
522
+ const { blocks, seen } = page;
523
+ if (blocks.length)
524
+ return { files, cursor: encodeListPosition({ k: "blocks", blocks, seen }) };
525
+ const shown = new Set(seen);
526
+ await confirm([...known.values()].filter((file) => file.parents[0] === id && !shown.has(file.id)), id, listing);
527
+ return { files: [...files, ...listing.files] };
528
+ };
353
529
  /** A container's children, with every known child that did not come back checked directly before it counts as gone. */
354
530
  const listChildren = async (id) => {
355
531
  const listing = { files: await listed(id), gone: [], moved: [] };
@@ -366,6 +542,17 @@ export const notionSource = (notion, options = {}) => {
366
542
  };
367
543
  const startPass = (cursor) => {
368
544
  const walk = now() - cursor.walkedAt >= walkEveryMs;
545
+ if (walk && roots.includes(WORKSPACE_ROOT)) {
546
+ // The workspace is listed by search a page at a time, so that a walk too long for one run goes on in the next.
547
+ const top = [...known.values()].filter((file) => file.parents[0] === WORKSPACE_ROOT).map((file) => file.id);
548
+ const tasks = [
549
+ { t: "search", kind: "page", full: true },
550
+ { t: "search", kind: "data_source", full: true },
551
+ ...roots.filter((id) => id !== WORKSPACE_ROOT).map((id) => ({ t: "walk", id })),
552
+ { t: "confirm", container: WORKSPACE_ROOT, ids: top },
553
+ ];
554
+ return { next: cursor.mark, startedAt: now(), walk, tasks };
555
+ }
369
556
  const tasks = [
370
557
  { t: "search", kind: "page" },
371
558
  { t: "search", kind: "data_source" },
@@ -380,6 +567,8 @@ export const notionSource = (notion, options = {}) => {
380
567
  fresh();
381
568
  requests = 0;
382
569
  const pass = cursor.pass ?? startPass(cursor);
570
+ containers = new Map(Object.entries(pass.parents ?? {}));
571
+ const resolved = containers.size;
383
572
  const since = cursor.mark ? minus(cursor.mark, overlapMs) : null;
384
573
  const items = new Map();
385
574
  const emit = (file) => items.set(file.id, { id: file.id, removed: false, file });
@@ -389,163 +578,313 @@ export const notionSource = (notion, options = {}) => {
389
578
  const before = known.get(file.id);
390
579
  return !before || before.name !== file.name || before.parents[0] !== file.parents[0];
391
580
  };
581
+ /** Work this run keeps even when the deadline cuts its step: a direct read or a resolved kind. */
582
+ let kept = 0;
583
+ // A saved position Notion no longer takes (it answers 400) starts that listing again, so it cannot fail every run.
584
+ const restart = (task, what) => {
585
+ warn({
586
+ code: "validation_error",
587
+ reason: "notion.listing-restarted",
588
+ message: `${what} started again from its top`,
589
+ });
590
+ pass.tasks.splice(1, 0, task);
591
+ };
592
+ // A confirm task stays last: it reads directly only what the rest of the pass did not show.
593
+ const queue = (task) => {
594
+ const last = pass.tasks.at(-1);
595
+ if (last?.t === "confirm")
596
+ pass.tasks.splice(-1, 0, task);
597
+ else
598
+ pass.tasks.push(task);
599
+ };
600
+ const shown = (id) => {
601
+ for (const task of pass.tasks)
602
+ if (task.t === "confirm")
603
+ task.ids = task.ids.filter((item) => item !== id);
604
+ };
392
605
  const addSource = (database, source) => {
393
606
  if (!cursor.sources.some((item) => item.source === source))
394
607
  cursor.sources.push({ database, source });
395
608
  };
396
- const search = async (kind) => {
397
- let start;
398
- do {
399
- const page = await searchPage(kind, start);
400
- start = page.has_more && page.next_cursor ? page.next_cursor : undefined;
401
- let reachedMark = false;
402
- for (const result of page.results) {
403
- if (since && Date.parse(result.last_edited_time) < Date.parse(since)) {
404
- start = undefined;
405
- reachedMark = true;
406
- break;
407
- }
408
- // Only what this pass saw before it began counts towards the next mark; later edits must stay inside it.
409
- if (kind === "page")
410
- pass.next = later(pass.next, result.last_edited_time);
411
- if (result.object === "page") {
412
- emit(await pageFile(result));
413
- continue;
414
- }
609
+ // One page of the answer per task, so that a pass cut short by the deadline goes on from the page it reached.
610
+ const search = async (task) => {
611
+ const { kind } = task;
612
+ let page;
613
+ try {
614
+ page = await searchPage(kind, task.start);
615
+ }
616
+ catch (error) {
617
+ if (!task.start || !isRefused(error))
618
+ throw error;
619
+ return restart({ ...task, start: undefined }, `the search for ${kind}s`);
620
+ }
621
+ let start = page.has_more && page.next_cursor ? page.next_cursor : undefined;
622
+ if (task.full) {
623
+ await searchTop(page);
624
+ if (isCut(page))
625
+ warn({
626
+ code: "provider_error",
627
+ reason: "notion.search-capped",
628
+ message: `Notion's search gave only the most recently edited ${kind}s; a top-level one it left out is found once it is edited`,
629
+ });
630
+ if (start)
631
+ pass.tasks.splice(1, 0, { ...task, start });
632
+ return;
633
+ }
634
+ let reachedMark = false;
635
+ for (const result of page.results) {
636
+ if (since && Date.parse(result.last_edited_time) < Date.parse(since)) {
637
+ start = undefined;
638
+ reachedMark = true;
639
+ break;
640
+ }
641
+ // Only what this pass saw before it began counts towards the next mark; later edits must stay inside it.
642
+ if (kind === "page")
643
+ pass.next = later(pass.next, result.last_edited_time);
644
+ if (result.object === "page") {
645
+ emit(await pageFile(result));
646
+ continue;
647
+ }
648
+ const id = result.parent.database_id;
649
+ // A database outside the chosen folders is not read; one inside them is held already, or comes by a walk.
650
+ if (!roots.includes(WORKSPACE_ROOT) && !known.has(id))
651
+ continue;
652
+ if (!pass.tasks.some((item) => item.t === "database" && item.id === id))
653
+ queue({ t: "database", id });
654
+ }
655
+ // Search has no time filter to split a cut answer by, so edits past the cut fail the sync instead of passing.
656
+ if (isCut(page) && !reachedMark)
657
+ throw new CliError("provider_error", `Notion cut the search for edited ${kind}s short`, {
658
+ reason: "notion.search-incomplete",
659
+ ...(page.request_status?.incomplete_reason
660
+ ? { incomplete_reason: page.request_status.incomplete_reason }
661
+ : {}),
662
+ });
663
+ if (start)
664
+ pass.tasks.splice(1, 0, { t: "search", kind, start });
665
+ };
666
+ const searchTop = async (page) => {
667
+ for (const result of page.results) {
668
+ if (result.in_trash)
669
+ continue;
670
+ if (result.object === "data_source") {
415
671
  const id = result.parent.database_id;
416
- // A database outside the chosen folders is not read; one inside them is held already, or comes by a walk.
417
- if (!roots.includes(WORKSPACE_ROOT) && !known.has(id))
418
- continue;
419
- const database = await readDatabase(id);
420
- if (!database)
421
- continue;
422
- const file = await databaseFile(database);
423
- if (file.trashed)
672
+ const queued = pass.tasks.find((item) => item.t === "database" && item.id === id);
673
+ if (queued?.t === "database")
674
+ queued.walk = true;
675
+ else
676
+ queue({ t: "database", id, walk: true });
677
+ continue;
678
+ }
679
+ pass.next = later(pass.next, result.last_edited_time);
680
+ if (result.parent.type !== "workspace")
681
+ continue;
682
+ const file = await pageFile(result);
683
+ shown(file.id);
684
+ if (changedPage(file))
685
+ emit(file);
686
+ queue({ t: "walk", id: file.id });
687
+ }
688
+ };
689
+ const database = async (task) => {
690
+ const found = await readDatabase(task.id);
691
+ if (typeof found !== "object")
692
+ return;
693
+ const file = await databaseFile(found);
694
+ if (file.trashed)
695
+ gone(task.id);
696
+ else if (unheld(file))
697
+ emit(file);
698
+ if (task.walk && !file.trashed && file.parents[0] === WORKSPACE_ROOT) {
699
+ shown(file.id);
700
+ queue({ t: "walk", id: file.id });
701
+ }
702
+ };
703
+ const confirmEach = async (task) => {
704
+ while (task.ids.length) {
705
+ const file = known.get(task.ids[0]);
706
+ if (file) {
707
+ const listing = { files: [], gone: [], moved: [] };
708
+ await confirm([file], task.container, listing);
709
+ for (const found of [...listing.files, ...listing.moved])
710
+ if (changedPage(found))
711
+ emit(found);
712
+ for (const id of listing.gone)
424
713
  gone(id);
425
- else if (unheld(file))
426
- emit(file);
427
714
  }
428
- // Search has no time filter to split a cut answer by, so edits past the cut fail the sync instead of passing.
429
- if (isCut(page) && !reachedMark)
430
- throw new CliError("provider_error", `Notion cut the search for edited ${kind}s short`, {
431
- reason: "notion.search-incomplete",
432
- ...(page.request_status?.incomplete_reason
433
- ? { incomplete_reason: page.request_status.incomplete_reason }
434
- : {}),
435
- });
436
- } while (start);
715
+ task.ids.shift();
716
+ kept++;
717
+ }
437
718
  };
719
+ // One page of rows per step. The next step reads from the last row's minute on, as Notion rounds created_time
720
+ // to the minute; only when a whole page shares one minute does it go on by the query's own position instead.
438
721
  const rows = async (task) => {
439
- let window;
722
+ let page;
440
723
  try {
441
- window = await rowWindow(task.database, task.source, task.after, task.full ? null : since);
724
+ page = await rowsPage(task.database, task.source, task, task.full ? null : since);
442
725
  }
443
726
  catch (error) {
727
+ if (task.start && isRefused(error))
728
+ return restart({ ...task, start: undefined, seen: undefined }, `the rows of database ${task.database}`);
444
729
  if (!isNotFound(error))
445
730
  throw error;
446
731
  cursor.sources = cursor.sources.filter((item) => item.source !== task.source);
447
- const database = await readDatabase(task.database);
448
- if (!database || database.in_trash)
732
+ if (isGone(await readDatabase(task.database)))
449
733
  gone(task.database);
450
734
  return;
451
735
  }
452
- const seen = new Set();
453
- for (const row of window.rows) {
454
- seen.add(row.id);
736
+ for (const row of page.rows)
455
737
  emit(await pageFile(row));
456
- }
457
- if (task.full) {
458
- // A window covers the rows created from its start up to the next window's start; a known row of that span
459
- // the window did not return is read directly before it counts as gone.
460
- const from = task.after ? Date.parse(task.after) : Number.NEGATIVE_INFINITY;
461
- const to = window.next ? Date.parse(window.next) : Number.POSITIVE_INFINITY;
462
- const missing = [...known.values()].filter((file) => {
463
- const created = Date.parse(file.createdAt ?? "");
464
- return (file.providerMetadata.kind === "row" &&
465
- file.providerMetadata.parent?.id === task.source &&
466
- !seen.has(file.id) &&
467
- created >= from &&
468
- created < to);
469
- });
470
- const listing = { files: [], gone: [], moved: [] };
471
- await confirm(missing, task.database, listing);
472
- for (const file of [...listing.files, ...listing.moved])
473
- emit(file);
474
- for (const id of listing.gone)
475
- gone(id);
476
- }
477
- if (window.next)
478
- pass.tasks.push({ ...task, after: window.next });
738
+ const next = [];
739
+ if (task.full && page.missing.length)
740
+ next.push({ t: "confirm", container: task.database, ids: page.missing.map((file) => file.id) });
741
+ if (page.next)
742
+ next.push({ ...task, after: page.next.after, start: page.next.start, seen: page.next.seen });
743
+ pass.tasks.splice(1, 0, ...next);
744
+ };
745
+ const child = async (task) => {
746
+ const file = await childDatabase(task.id);
747
+ if (!file || file.trashed)
748
+ return;
749
+ if (unheld(file))
750
+ emit(file);
751
+ queue({ t: "walk", id: file.id, kind: "database" });
479
752
  };
480
753
  const walkDatabase = async (id) => {
481
754
  const database = await readDatabase(id);
482
- if (!database || database.in_trash) {
755
+ if (database === "unreadable")
756
+ return;
757
+ if (database === "gone" || database.in_trash) {
483
758
  if (!roots.includes(id))
484
759
  gone(id);
485
760
  return;
486
761
  }
487
762
  for (const source of database.data_sources) {
488
763
  addSource(id, source.id);
489
- pass.tasks.push({ t: "rows", database: id, source: source.id, full: true });
764
+ queue({ t: "rows", database: id, source: source.id, full: true });
490
765
  }
491
766
  };
492
- const walk = async (id) => {
493
- const kind = id === WORKSPACE_ROOT ? "workspace" : (known.get(id)?.providerMetadata.kind ?? "database");
494
- // Pages under pages wait for cli-core's page-with-children (C2); listing them now would cost requests for nothing.
495
- if (kind === "database")
496
- return walkDatabase(id);
497
- if (kind !== "workspace")
498
- return;
499
- const listing = await listChildren(id);
767
+ // The engine walks again every folder it is sent, so a held page is sent only when Notion changed it.
768
+ const changedPage = (file) => unheld(file) || known.get(file.id)?.version !== file.version;
769
+ // A page's children a page of blocks per step, from where the last step stopped.
770
+ const walkPage = async (task) => {
771
+ let page;
772
+ try {
773
+ page = await blocksPage({ blocks: task.blocks ?? [{ id: task.id }], seen: task.seen ?? [] });
774
+ }
775
+ catch (error) {
776
+ if (task.blocks?.[0]?.start && isRefused(error))
777
+ return restart({ t: "walk", id: task.id, kind: "page" }, `the listing of page ${task.id}`);
778
+ throw error;
779
+ }
780
+ const { blocks, seen } = page;
781
+ for (const block of page.pages) {
782
+ const file = childPageFile(block, task.id);
783
+ if (changedPage(file))
784
+ emit(file);
785
+ const holds = [...known.values()].some((item) => item.parents[0] === block.id);
786
+ if (block.has_children || holds)
787
+ queue({ t: "walk", id: block.id, kind: "page" });
788
+ }
789
+ for (const id of page.databases)
790
+ queue({ t: "child", id, container: task.id });
791
+ if (blocks.length)
792
+ return void pass.tasks.splice(1, 0, { ...task, blocks, seen });
793
+ const listed = new Set(seen);
794
+ const missing = [...known.values()].filter((file) => file.parents[0] === task.id && !listed.has(file.id));
795
+ if (missing.length)
796
+ pass.tasks.splice(1, 0, { t: "confirm", container: task.id, ids: missing.map((file) => file.id) });
797
+ };
798
+ const walk = async (task) => {
799
+ if (task.id === WORKSPACE_ROOT)
800
+ return walkWorkspace();
801
+ if (!task.kind) {
802
+ task.kind = known.get(task.id)?.providerMetadata.kind ?? (await retrieve(task.id)).providerMetadata.kind;
803
+ kept++;
804
+ }
805
+ if (task.kind === "database")
806
+ return walkDatabase(task.id);
807
+ if (task.kind === "page")
808
+ return walkPage(task);
809
+ };
810
+ // Only a pass a 0.1.0 sync saved still holds the workspace as one step.
811
+ const walkWorkspace = async () => {
812
+ const listing = await listChildren(WORKSPACE_ROOT);
500
813
  for (const file of listing.moved)
501
814
  emit(file);
502
815
  for (const file of listing.files) {
503
- if (!isNotionFolder(file) || unheld(file))
816
+ const page = file.providerMetadata.kind === "page";
817
+ if (page ? changedPage(file) : unheld(file))
504
818
  emit(file);
505
- if (file.providerMetadata.kind === "database")
506
- pass.tasks.push({ t: "walk", id: file.id });
819
+ if (page || file.providerMetadata.kind === "database")
820
+ queue({ t: "walk", id: file.id });
507
821
  }
508
822
  for (const gid of listing.gone)
509
823
  gone(gid);
510
824
  };
511
825
  let done = 0;
512
- while (pass.tasks.length && requests < maxRequests) {
513
- const task = pass.tasks[0];
514
- try {
515
- if (task.t === "search")
516
- await search(task.kind);
517
- else if (task.t === "rows")
518
- await rows(task);
519
- else
520
- await walk(task.id);
521
- }
522
- catch (error) {
523
- const failure = isCliError(error) ? error : new CliError("provider_error", String(error));
524
- const id = task.t === "rows" ? task.database : task.t === "walk" ? task.id : undefined;
525
- if (isItemError(failure)) {
526
- warn({ ...(id ? { id } : {}), code: failure.code, message: `left out of this sync: ${failure.message}` });
527
- pass.tasks.shift();
528
- done++;
529
- continue;
826
+ timed = true;
827
+ try {
828
+ while (pass.tasks.length && requests < maxRequests) {
829
+ const task = pass.tasks[0];
830
+ try {
831
+ if (task.t === "search")
832
+ await search(task);
833
+ else if (task.t === "database")
834
+ await database(task);
835
+ else if (task.t === "confirm")
836
+ await confirmEach(task);
837
+ else if (task.t === "rows")
838
+ await rows(task);
839
+ else if (task.t === "child")
840
+ await child(task);
841
+ else
842
+ await walk(task);
530
843
  }
531
- // With nothing done yet the error is the answer; otherwise the work so far is kept and the next sync goes on.
532
- if (!done)
533
- throw failure;
534
- warn({
535
- ...(id ? { id } : {}),
536
- code: failure.code,
537
- message: `the sync stopped here and goes on next time: ${failure.message}`,
538
- ...(typeof failure.details.retry_after_ms === "number"
539
- ? { retry_after_ms: failure.details.retry_after_ms }
540
- : {}),
541
- });
542
- break;
844
+ catch (error) {
845
+ // The task is done again from its start next time: what it emitted is sent twice, which the engine allows.
846
+ if (error === OUT_OF_TIME) {
847
+ // cli-core ends the command at the deadline, so a run that saves nothing would only be asked again.
848
+ if (!done && !kept && containers.size === resolved)
849
+ throw new CliError("timeout", "the time left was too short for one step of the Notion sync; run it again with a longer --timeout", { reason: "notion.timeout-too-short" });
850
+ break;
851
+ }
852
+ const failure = isCliError(error) ? error : new CliError("provider_error", String(error));
853
+ const id = task.t === "rows" ? task.database : task.t === "search" || task.t === "confirm" ? undefined : task.id;
854
+ if (isItemError(failure)) {
855
+ warn({
856
+ ...(id ? { id } : {}),
857
+ code: failure.code,
858
+ reason: "notion.left-out",
859
+ message: `left out of this sync: ${failure.message}`,
860
+ });
861
+ pass.tasks.shift();
862
+ done++;
863
+ continue;
864
+ }
865
+ // With nothing done yet the error is the answer; otherwise the work so far is kept and the next sync goes on.
866
+ if (!done)
867
+ throw failure;
868
+ warn({
869
+ ...(id ? { id } : {}),
870
+ code: failure.code,
871
+ reason: "notion.stopped-early",
872
+ message: `the sync stopped here and goes on next time: ${failure.message}`,
873
+ ...(typeof failure.details.retry_after_ms === "number"
874
+ ? { retry_after_ms: failure.details.retry_after_ms }
875
+ : {}),
876
+ });
877
+ break;
878
+ }
879
+ pass.tasks.shift();
880
+ done++;
543
881
  }
544
- pass.tasks.shift();
545
- done++;
882
+ }
883
+ finally {
884
+ timed = false;
546
885
  }
547
886
  if (pass.tasks.length)
548
- cursor.pass = pass;
887
+ cursor.pass = { ...pass, parents: Object.fromEntries(containers) };
549
888
  else {
550
889
  cursor.mark = later(cursor.mark, pass.next);
551
890
  if (pass.walk)
@@ -568,14 +907,53 @@ export const notionSource = (notion, options = {}) => {
568
907
  add(user, `property:${name}`);
569
908
  return [...found.values()];
570
909
  };
571
- return {
572
- async identity() {
573
- const self = await reads.self();
574
- if (!self.bot?.workspace_id)
575
- throw new CliError("invalid_response", "Notion did not name the token's workspace", {
576
- reason: "notion.no-workspace",
910
+ const content = async (id, maxChars) => {
911
+ containers = new Map();
912
+ const page = await reads.retrievePage(id);
913
+ if (page.in_trash)
914
+ throw new CliError("not_found", "the page is in Notion's trash");
915
+ const file = await pageFile(page);
916
+ const body = await pageText(reads, id, (block, code) => {
917
+ if (code === "permission_error")
918
+ warn({
919
+ id: block,
920
+ code,
921
+ reason: "notion.left-out",
922
+ message: `a block of page ${id} was left out of its text: the token may not read it`,
577
923
  });
578
- return `${self.bot.workspace_id}:${self.id}`;
924
+ });
925
+ const fields = frontMatter(page.properties);
926
+ const metadata = {
927
+ ...file,
928
+ providerMetadata: {
929
+ ...file.providerMetadata,
930
+ frontMatter: fields,
931
+ people: people(page),
932
+ ...(body.missing ? { missingBlocks: body.missing } : {}),
933
+ },
934
+ };
935
+ const searchable = [file.name, ...frontMatterLines(fields), body.markdown].filter(Boolean).join("\n\n");
936
+ if (maxChars !== undefined && searchable.length > maxChars)
937
+ throw new CliError("validation_error", "the page is longer than the text limit", {
938
+ reason: "source.text-limit",
939
+ text_limit: maxChars,
940
+ });
941
+ return { metadata, markdown: body.markdown, text: withoutSignedLinks(searchable).text, tabs: [] };
942
+ };
943
+ let account;
944
+ const identity = async () => {
945
+ const self = await reads.self();
946
+ if (!self.bot?.workspace_id)
947
+ throw new CliError("invalid_response", "Notion did not name the token's workspace", {
948
+ reason: "notion.no-workspace",
949
+ });
950
+ return `${self.bot.workspace_id}:${self.id}`;
951
+ };
952
+ return {
953
+ // One sync run asks once: the CLI checks the account before it takes the lock, and the engine asks again.
954
+ identity() {
955
+ account ??= identity();
956
+ return account;
579
957
  },
580
958
  async metadata(id) {
581
959
  fresh();
@@ -583,7 +961,21 @@ export const notionSource = (notion, options = {}) => {
583
961
  },
584
962
  async children(id) {
585
963
  fresh();
586
- return (await listChildren(id)).files;
964
+ if (id === WORKSPACE_ROOT)
965
+ return (await listChildren(id)).files;
966
+ const files = [];
967
+ let cursor;
968
+ do {
969
+ const page = await childrenPage(id, cursor);
970
+ for (const file of page.files)
971
+ files.push(file);
972
+ cursor = page.cursor;
973
+ } while (cursor);
974
+ return files;
975
+ },
976
+ async childrenPage(id, cursor) {
977
+ fresh();
978
+ return childrenPage(id, cursor);
587
979
  },
588
980
  async startToken() {
589
981
  const top = await reads.search({
@@ -595,40 +987,9 @@ export const notionSource = (notion, options = {}) => {
595
987
  return encodeCursor(cursor);
596
988
  },
597
989
  changes,
598
- async content(id, maxChars) {
599
- containers = new Map();
600
- const page = await reads.retrievePage(id);
601
- if (page.in_trash)
602
- throw new CliError("not_found", "the page is in Notion's trash");
603
- const file = await pageFile(page);
604
- const body = await pageText(reads, id);
605
- const fields = frontMatter(page.properties);
606
- const metadata = {
607
- ...file,
608
- providerMetadata: {
609
- ...file.providerMetadata,
610
- frontMatter: fields,
611
- people: people(page),
612
- ...(body.missing ? { missingBlocks: body.missing } : {}),
613
- },
614
- };
615
- const searchable = [file.name, ...frontMatterLines(fields), body.markdown].filter(Boolean).join("\n\n");
616
- if (maxChars !== undefined && searchable.length > maxChars)
617
- throw new CliError("validation_error", "the page is longer than the text limit", {
618
- reason: "source.text-limit",
619
- text_limit: maxChars,
620
- });
621
- const content = {
622
- metadata,
623
- markdown: body.markdown,
624
- text: withoutSignedLinks(searchable).text,
625
- tabs: [],
626
- };
627
- return content;
628
- },
629
- async bytes() {
630
- throw new CliError("validation_error", "a Notion page has no file to download");
631
- },
990
+ content,
991
+ // A page has no file of its own; its Markdown is the nearest thing to one.
992
+ bytes: async (id) => new TextEncoder().encode((await content(id)).markdown),
632
993
  };
633
994
  };
634
995
  //# sourceMappingURL=source.js.map