@kamilio/wire 0.1.13 → 0.1.15

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 (35) hide show
  1. package/README.md +13 -0
  2. package/dist/adapters/root.d.ts +2 -2
  3. package/dist/adapters/root.d.ts.map +1 -1
  4. package/dist/adapters/root.js +25 -6
  5. package/dist/adapters/root.js.map +1 -1
  6. package/dist/cli.d.ts.map +1 -1
  7. package/dist/cli.js +9 -5
  8. package/dist/cli.js.map +1 -1
  9. package/dist/executable.d.ts.map +1 -1
  10. package/dist/executable.js +3 -2
  11. package/dist/executable.js.map +1 -1
  12. package/node_modules/provider-notion/dist/index.d.ts +1 -0
  13. package/node_modules/provider-notion/dist/index.d.ts.map +1 -1
  14. package/node_modules/provider-notion/dist/index.js +1 -0
  15. package/node_modules/provider-notion/dist/index.js.map +1 -1
  16. package/node_modules/provider-notion/dist/notion-sync.d.ts +3 -1
  17. package/node_modules/provider-notion/dist/notion-sync.d.ts.map +1 -1
  18. package/node_modules/provider-notion/dist/notion-sync.js +153 -22
  19. package/node_modules/provider-notion/dist/notion-sync.js.map +1 -1
  20. package/node_modules/provider-notion/src/index.ts +2 -0
  21. package/node_modules/provider-notion/src/notion-sync.ts +139 -23
  22. package/node_modules/provider-slack/dist/index.d.ts +1 -1
  23. package/node_modules/provider-slack/dist/index.d.ts.map +1 -1
  24. package/node_modules/provider-slack/dist/index.js +1 -1
  25. package/node_modules/provider-slack/dist/index.js.map +1 -1
  26. package/node_modules/provider-slack/dist/slack.d.ts +3 -0
  27. package/node_modules/provider-slack/dist/slack.d.ts.map +1 -1
  28. package/node_modules/provider-slack/dist/slack.js +111 -20
  29. package/node_modules/provider-slack/dist/slack.js.map +1 -1
  30. package/node_modules/provider-slack/src/index.ts +1 -1
  31. package/node_modules/provider-slack/src/slack.ts +101 -19
  32. package/package.json +1 -1
  33. package/src/adapters/root.ts +26 -7
  34. package/src/cli.ts +5 -3
  35. package/src/executable.ts +4 -2
@@ -257,8 +257,8 @@ function hydrateUserMentions(markdownText, mentions) {
257
257
  function baseUserMentions(base) {
258
258
  return base["user_mentions"];
259
259
  }
260
- function notionData(pageId, markdown, tree, mentions) {
261
- return mentions === undefined ? { page_id: pageId, markdown, blocks: sidecarBlocksFromNotionTree(tree) } : { page_id: pageId, markdown, blocks: sidecarBlocksFromNotionTree(tree), user_mentions: mentions };
260
+ function notionData(pageId, markdown, tree, mentions, emailMentions = {}) {
261
+ return { page_id: pageId, markdown, blocks: sidecarBlocksFromNotionTree(tree), ...(mentions === undefined ? {} : { user_mentions: mentions }), ...(Object.keys(emailMentions).length === 0 ? {} : { email_mentions: emailMentions }) };
262
262
  }
263
263
  function lineIndent(line) { return Math.floor(line.match(/^ */)[0].length / 2); }
264
264
  function stripIndent(line) { return line.replace(/^ +/, ""); }
@@ -877,14 +877,16 @@ function renderNode(tree, indent, parentType = "") {
877
877
  return [`${prefix}:::text`, ...title.split("\n").map((line) => `${prefix}${line}`), `${prefix}:::`];
878
878
  return title.split("\n").map((line) => `${prefix}${escapeBlockMarkdownLine(line)}`);
879
879
  }
880
- export function renderNotionTreeToMarkdown(tree, mentions) {
880
+ export function renderNotionTreeToMarkdown(tree, mentions, emailMentions = {}) {
881
881
  const title = renderRichText(object(tree.block["properties"])["title"]);
882
882
  const compactTypes = new Set(["bulleted_list", "numbered_list", "to_do"]);
883
883
  const body = tree.children.flatMap((child, index) => [
884
884
  ...(index === 0 || (tree.children[index - 1].block["type"] === child.block["type"] && compactTypes.has(child.block["type"])) ? [] : [""]),
885
885
  ...renderNode(child, 0),
886
886
  ]);
887
- const markdown = [`# ${title}`, ...body.length === 0 ? [] : ["", ...body]].join("\n").trim();
887
+ let markdown = [`# ${title}`, ...body.length === 0 ? [] : ["", ...body]].join("\n").trim();
888
+ for (const [id, link] of Object.entries(emailMentions))
889
+ markdown = markdown.replace(new RegExp(`<span data-notion-mention="u" data-notion-id="${escapeRegExp(escapeHtml(id))}">.*?</span>`, "g"), () => link);
888
890
  return mentions === undefined ? markdown : renderUserMentions(markdown, mentions);
889
891
  }
890
892
  async function notionPost(runtime, path, cookie, body, headers) {
@@ -893,6 +895,132 @@ async function notionPost(runtime, path, cookie, body, headers) {
893
895
  throw new Error(`POST ${path} failed: ${response.status} ${await response.text()}`);
894
896
  return await response.json();
895
897
  }
898
+ async function findNotionUsers(runtime, query, cookie, spaceId, headers) {
899
+ query = query.trim();
900
+ if (query === "")
901
+ throw new Error("Notion user lookup requires an email or name");
902
+ const response = await notionPost(runtime, "getVisibleUsers", cookie, { spaceId }, headers);
903
+ const users = response["users"];
904
+ if (/^[^@\s]+@[^@\s]+$/.test(query))
905
+ return users.filter((user) => user["aliases"]?.some((email) => email.toLowerCase() === query.toLowerCase()));
906
+ if (users.length === 0)
907
+ return [];
908
+ const records = await notionPost(runtime, "getRecordValues", cookie, { requests: users.map((user) => ({ table: "notion_user", id: user["userId"] })) }, headers);
909
+ const results = records["results"];
910
+ return users.flatMap((user, index) => {
911
+ const profile = results[index]?.["value"];
912
+ const name = profile?.["name"] ?? "";
913
+ const names = [name, ...(user["aliases"] ?? [])];
914
+ return query.toLowerCase().split(/\s+/).every((word) => names.some((value) => value.toLowerCase().includes(word))) ? [{ ...user, name }] : [];
915
+ });
916
+ }
917
+ export async function lookupNotionUsers(runtime, query) {
918
+ const cookies = await runtime.cookies.loadSaved("notion");
919
+ if (cookies === null)
920
+ throw notionAuthError();
921
+ const cookie = cookies.map((value) => `${value.name}=${value.value}`).join("; ");
922
+ const userId = cookies.find((value) => value.name === "notion_user_id").value;
923
+ const spaces = await notionPost(runtime, "getSpaces", cookie, {}, {});
924
+ const spaceView = object(object(spaces[userId])["space_view"]);
925
+ const ids = [...new Set(Object.values(spaceView).map((value) => object(value)["spaceId"]))];
926
+ const users = [];
927
+ for (const spaceId of ids)
928
+ users.push(...await findNotionUsers(runtime, query, cookie, spaceId, { "x-notion-active-user-header": userId, "x-notion-space-id": spaceId }));
929
+ return [...new Map(users.map((user) => [user["userId"], user])).values()];
930
+ }
931
+ async function resolveNotionEmailMentions(runtime, blocks, cookie, spaceId, headers, mentions) {
932
+ const segments = [];
933
+ const visit = (value) => {
934
+ if (Array.isArray(value)) {
935
+ if (typeof value[0] === "string" && value[0].startsWith("@") && Array.isArray(value[1]) && value[1].some((mark) => Array.isArray(mark) && mark[0] === "a" && typeof mark[1] === "string" && mark[1].startsWith("mailto:")))
936
+ segments.push(value);
937
+ else
938
+ for (const child of value)
939
+ visit(child);
940
+ }
941
+ else if (value !== null && typeof value === "object")
942
+ for (const child of Object.values(value))
943
+ visit(child);
944
+ };
945
+ for (const block of blocks) {
946
+ if (block.type === "code" || block.properties["notion_opaque"] !== undefined)
947
+ continue;
948
+ visit(block.rich_text);
949
+ visit(block.properties);
950
+ }
951
+ if (segments.length === 0)
952
+ return;
953
+ const response = await notionPost(runtime, "getVisibleUsers", cookie, { spaceId }, headers);
954
+ const users = response["users"];
955
+ for (const segment of segments) {
956
+ const marks = segment[1];
957
+ const link = marks.find((mark) => mark[0] === "a" && mark[1].startsWith("mailto:"));
958
+ const email = decodeURIComponent(link[1].slice(7));
959
+ if (!/^[^@\s?]+@[^@\s?]+$/.test(email))
960
+ throw new Error(`Invalid mention email: ${email}`);
961
+ const matches = users.filter((user) => user["aliases"]?.some((alias) => alias.toLowerCase() === email.toLowerCase()));
962
+ if (matches.length !== 1)
963
+ throw new Error(`Expected one Notion user for ${email}, found ${matches.length}`);
964
+ const id = matches[0]["userId"];
965
+ mentions[id] = `[${escapeInlineMarkdown(segment[0])}](mailto:${email})`;
966
+ segment[0] = "‣";
967
+ link[0] = "u";
968
+ link[1] = id;
969
+ }
970
+ }
971
+ async function fetchComments(runtime, tree, spaceId, cookie, headers) {
972
+ const records = { discussion: new Map(), comment: new Map(), notion_user: new Map() };
973
+ let startingAfterId;
974
+ while (true) {
975
+ const data = await notionPost(runtime, "getActivityLog", cookie, { spaceId, navigableBlock: { id: tree.id }, limit: 100, ...(startingAfterId === undefined ? {} : { startingAfterId }) }, headers);
976
+ const recordMap = object(data["recordMap"]);
977
+ for (const table of Object.keys(records)) {
978
+ if (recordMap[table] === undefined)
979
+ continue;
980
+ for (const [id, wrapper] of Object.entries(object(recordMap[table]))) {
981
+ const value = object(object(object(wrapper)["value"])["value"]);
982
+ const previous = records[table].get(id);
983
+ if (previous === undefined || value["version"] >= previous["version"])
984
+ records[table].set(id, value);
985
+ }
986
+ }
987
+ const activityIds = data["activityIds"];
988
+ if (activityIds.length < 100)
989
+ break;
990
+ startingAfterId = activityIds[activityIds.length - 1];
991
+ }
992
+ const blockIds = new Set(sidecarBlocksFromNotionTree(tree).map((block) => block.id));
993
+ const discussions = [...records["discussion"].values()].filter((discussion) => blockIds.has(discussion["parent_id"]) && discussion["alive"] !== false);
994
+ for (const table of ["comment", "notion_user"]) {
995
+ const ids = table === "comment" ? discussions.flatMap((discussion) => discussion["comments"]) : [...records["comment"].values()].filter((comment) => comment["alive"] === true).map((comment) => comment["created_by_id"]);
996
+ const missing = [...new Set(ids)].filter((id) => !records[table].has(id));
997
+ if (missing.length === 0)
998
+ continue;
999
+ const data = await notionPost(runtime, "getRecordValues", cookie, { requests: missing.map((id) => ({ table, id })) }, headers);
1000
+ for (const [index, result] of data["results"].entries())
1001
+ records[table].set(missing[index], object(result["value"]));
1002
+ }
1003
+ const threads = discussions.map((discussion) => {
1004
+ const comments = discussion["comments"].map((id) => records["comment"].get(id)).filter((comment) => comment["alive"] === true);
1005
+ if (comments.length === 0)
1006
+ return "";
1007
+ const context = discussion["context"] === undefined ? "" : renderRichText(discussion["context"]);
1008
+ const link = `https://www.notion.so/${tree.id.replaceAll("-", "")}#${discussion["parent_id"].replaceAll("-", "")}`;
1009
+ return [
1010
+ `### [${discussion["parent_id"] === tree.id ? "Page comment" : "Inline comment"}](${link})${discussion["resolved"] === true ? " (resolved)" : ""}`,
1011
+ ...(context === "" ? [] : [context.split("\n").map((line) => `> ${line}`).join("\n")]),
1012
+ ...comments.map((comment) => `**${escapeInlineMarkdown(records["notion_user"].get(comment["created_by_id"])["name"])}** — ${new Date(comment["created_time"]).toISOString()}\n\n${renderRichText(comment["text"])}`),
1013
+ ].join("\n\n");
1014
+ }).filter((thread) => thread !== "");
1015
+ return threads.length === 0 ? "" : `\n\n<!-- wire:notion-comments -->\n\n## Comments (read-only)\n\n${threads.join("\n\n")}\n\n<!-- /wire:notion-comments -->`;
1016
+ }
1017
+ function withoutComments(markdown) {
1018
+ return markdown.replace(/\n\n<!-- wire:notion-comments -->[\s\S]*?<!-- \/wire:notion-comments -->/g, "");
1019
+ }
1020
+ function notionDocument(pageId, tree, mentions, emailMentions, comments) {
1021
+ const markdown = renderNotionTreeToMarkdown(tree, mentions, emailMentions) + comments;
1022
+ return { title: markdown.split("\n")[0].replace(/^# */, ""), markdown, data: notionData(pageId, markdown, tree, mentions, emailMentions) };
1023
+ }
896
1024
  async function fetchTree(runtime, url, source) {
897
1025
  const cookies = await runtime.cookies.loadSaved("notion");
898
1026
  if (cookies === null)
@@ -945,15 +1073,16 @@ async function fetchTree(runtime, url, source) {
945
1073
  return { id: idValue, block, children: [] };
946
1074
  return { id: idValue, block, children: (block["content"] ?? []).filter((child) => blocks.get(child)?.["alive"] !== false).map(build) };
947
1075
  };
948
- return { tree: build(pageId), userId, spaceId, cookie, headers };
1076
+ const tree = build(pageId);
1077
+ const comments = await fetchComments(runtime, tree, spaceId, cookie, headers);
1078
+ return { tree, userId, spaceId, cookie, headers, comments };
949
1079
  }
950
1080
  export async function fetchNotionDocument(runtime, url, source) {
951
- const { tree } = await fetchTree(runtime, url, source);
952
- const markdown = renderNotionTreeToMarkdown(tree);
953
- return { title: markdown.split("\n")[0].replace(/^# */, ""), markdown, data: notionData(source.identifier, markdown, tree, undefined) };
1081
+ const { tree, comments } = await fetchTree(runtime, url, source);
1082
+ return notionDocument(source.identifier, tree, undefined, {}, comments);
954
1083
  }
955
1084
  export async function uploadNotionDocument(runtime, markdown, _markdownPath) {
956
- const split = splitTitle(markdown);
1085
+ const split = splitTitle(withoutComments(markdown));
957
1086
  if (split.title === "")
958
1087
  throw new Error("Markdown document requires a first heading");
959
1088
  const cookies = await runtime.cookies.loadSaved("notion");
@@ -993,6 +1122,8 @@ export async function uploadNotionDocument(runtime, markdown, _markdownPath) {
993
1122
  },
994
1123
  };
995
1124
  const localBlocks = parseNotionMarkdown(split.body);
1125
+ const emailMentions = {};
1126
+ await resolveNotionEmailMentions(runtime, localBlocks, cookie, spaceId, headers, emailMentions);
996
1127
  const operations = [pageOperation, ...buildNotionCreateOperations(localBlocks, pageId, spaceId, userId, currentTime).operations];
997
1128
  await notionPost(runtime, "saveTransactionsFanout", cookie, { requestId: randomUUID(), transactions: [{ id: randomUUID(), spaceId, operations }] }, headers);
998
1129
  const pageTree = {
@@ -1000,8 +1131,8 @@ export async function uploadNotionDocument(runtime, markdown, _markdownPath) {
1000
1131
  block: pageOperation.args,
1001
1132
  children: localTree(localBlocks).map((node) => outputNode(node, undefined, pageId, { spaceId, userId }, currentTime)),
1002
1133
  };
1003
- const output = renderNotionTreeToMarkdown(pageTree);
1004
- return { url: `https://www.notion.so/${compactPageId}`, title: split.title, markdown: output, data: notionData(compactPageId, output, pageTree, undefined) };
1134
+ const output = renderNotionTreeToMarkdown(pageTree, undefined, emailMentions);
1135
+ return { url: `https://www.notion.so/${compactPageId}`, title: split.title, markdown: output, data: notionData(compactPageId, output, pageTree, undefined, emailMentions) };
1005
1136
  }
1006
1137
  function splitTitle(markdown) {
1007
1138
  const lines = markdown.replace(/^\ufeff/, "").split("\n");
@@ -1016,9 +1147,10 @@ export async function synchronizeNotionDocument(runtime, url, source, base, mark
1016
1147
  const remote = await fetchTree(runtime, url, source);
1017
1148
  const baseObject = object(base);
1018
1149
  const mentions = baseUserMentions(baseObject);
1019
- const currentMarkdown = renderNotionTreeToMarkdown(remote.tree, mentions);
1020
- const baseMarkdown = baseObject["markdown"];
1021
- let split = splitTitle(markdown);
1150
+ const emailMentions = { ...baseObject["email_mentions"] };
1151
+ const currentMarkdown = renderNotionTreeToMarkdown(remote.tree, mentions, emailMentions);
1152
+ const baseMarkdown = baseObject["markdown"] === undefined ? undefined : withoutComments(baseObject["markdown"]);
1153
+ let split = splitTitle(withoutComments(markdown));
1022
1154
  const currentSplit = splitTitle(currentMarkdown);
1023
1155
  const baseSplit = baseMarkdown === undefined ? undefined : splitTitle(baseMarkdown);
1024
1156
  let fieldMerged = false;
@@ -1040,32 +1172,32 @@ export async function synchronizeNotionDocument(runtime, url, source, base, mark
1040
1172
  const localTitleChanged = baseSplit.title !== split.title;
1041
1173
  const remoteTitleChanged = baseSplit.title !== currentSplit.title;
1042
1174
  if (!localTitleChanged && remoteTitleChanged)
1043
- return { title: currentSplit.title, markdown: currentMarkdown, data: notionData(remote.tree.id, currentMarkdown, remote.tree, mentions) };
1175
+ return notionDocument(remote.tree.id, remote.tree, mentions, emailMentions, remote.comments);
1044
1176
  if (localTitleChanged && remoteTitleChanged && split.title !== currentSplit.title)
1045
1177
  throw new Error("Markdown and Notion changed since last sync");
1046
1178
  if (localTitleChanged && remoteTitleChanged)
1047
- return { title: currentSplit.title, markdown: currentMarkdown, data: notionData(remote.tree.id, currentMarkdown, remote.tree, mentions) };
1179
+ return notionDocument(remote.tree.id, remote.tree, mentions, emailMentions, remote.comments);
1048
1180
  }
1049
1181
  const titleRich = split.title === "" ? object(remote.tree.block["properties"])["title"] : titleRichText(split.title);
1050
1182
  const titleChanged = split.title !== "" && compact(object(remote.tree.block["properties"])["title"]) !== compact(titleRich);
1051
1183
  if (titleChanged)
1052
1184
  await notionPost(runtime, "saveTransactionsFanout", remote.cookie, { requestId: randomUUID(), transactions: [{ id: randomUUID(), spaceId: remote.spaceId, operations: [{ pointer: pointer(remote.tree.id, remote.spaceId), path: ["properties", "title"], command: "updateBlockPropertyValue", args: { primitiveOp: { command: "set", args: titleRich } } }, { pointer: pointer(remote.tree.id, remote.spaceId), path: ["last_edited_time"], command: "set", args: runtime.clock.now().getTime() }] }] }, remote.headers);
1053
1185
  const outputTree = { ...remote.tree, block: { ...remote.tree.block, properties: { ...object(remote.tree.block["properties"]), title: titleRich } } };
1054
- const output = renderNotionTreeToMarkdown(outputTree, mentions);
1055
- return { title: output.split("\n")[0].replace(/^# */, ""), markdown: output, data: notionData(remote.tree.id, output, outputTree, mentions) };
1186
+ return notionDocument(remote.tree.id, outputTree, mentions, emailMentions, remote.comments);
1056
1187
  }
1057
1188
  if (baseMarkdown !== undefined) {
1058
1189
  const localChanged = baseMarkdown !== targetMarkdown;
1059
1190
  const remoteChanged = baseMarkdown !== currentMarkdown;
1060
1191
  if (!localChanged && remoteChanged)
1061
- return { title: currentMarkdown.split("\n")[0].replace(/^# */, ""), markdown: currentMarkdown, data: notionData(remote.tree.id, currentMarkdown, remote.tree, mentions) };
1192
+ return notionDocument(remote.tree.id, remote.tree, mentions, emailMentions, remote.comments);
1062
1193
  if (localChanged && remoteChanged && targetMarkdown !== currentMarkdown && !fieldMerged)
1063
1194
  throw new Error("Markdown and Notion changed since last sync");
1064
1195
  if (localChanged && remoteChanged && targetMarkdown === currentMarkdown)
1065
- return { title: currentMarkdown.split("\n")[0].replace(/^# */, ""), markdown: currentMarkdown, data: notionData(remote.tree.id, currentMarkdown, remote.tree, mentions) };
1196
+ return notionDocument(remote.tree.id, remote.tree, mentions, emailMentions, remote.comments);
1066
1197
  }
1067
1198
  const localBody = mentions === undefined ? split.body : hydrateUserMentions(split.body, mentions);
1068
1199
  const localBlocks = parseNotionMarkdown(localBody);
1200
+ await resolveNotionEmailMentions(runtime, localBlocks, remote.cookie, remote.spaceId, remote.headers, emailMentions);
1069
1201
  const ambient = { spaceId: remote.spaceId, userId: remote.userId, currentTime: runtime.clock.now().getTime() };
1070
1202
  const diffResult = diffNotionBlockTrees(remote.tree, localBlocks, sidecarBlocksFromNotionTree(remote.tree), ambient);
1071
1203
  const operations = [...diffResult.operations];
@@ -1075,7 +1207,6 @@ export async function synchronizeNotionDocument(runtime, url, source, base, mark
1075
1207
  if (operations.length > 0)
1076
1208
  await notionPost(runtime, "saveTransactionsFanout", remote.cookie, { requestId: randomUUID(), transactions: [{ id: randomUUID(), spaceId: remote.spaceId, operations }] }, remote.headers);
1077
1209
  const outputTree = { id: remote.tree.id, block: { ...remote.tree.block, properties: { ...object(remote.tree.block["properties"]), title: titleRich } }, children: localTree(localBlocks).map((node, index) => outputNode(node, remote.tree.children[index], remote.tree.id, remote, ambient.currentTime)) };
1078
- const output = renderNotionTreeToMarkdown(outputTree, mentions);
1079
- return { title: output.split("\n")[0].replace(/^# */, ""), markdown: output, data: notionData(remote.tree.id, output, outputTree, mentions) };
1210
+ return notionDocument(remote.tree.id, outputTree, mentions, emailMentions, remote.comments);
1080
1211
  }
1081
1212
  //# sourceMappingURL=notion-sync.js.map