@kamilio/wire 0.1.16 → 0.1.18
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.
- package/README.md +2 -0
- package/node_modules/provider-asana/dist/asana-http.d.ts +3 -0
- package/node_modules/provider-asana/dist/asana-http.d.ts.map +1 -0
- package/node_modules/provider-asana/dist/asana-http.js +13 -0
- package/node_modules/provider-asana/dist/asana-http.js.map +1 -0
- package/node_modules/provider-asana/dist/asana-project.d.ts.map +1 -1
- package/node_modules/provider-asana/dist/asana-project.js +2 -1
- package/node_modules/provider-asana/dist/asana-project.js.map +1 -1
- package/node_modules/provider-asana/dist/asana-task.d.ts.map +1 -1
- package/node_modules/provider-asana/dist/asana-task.js +2 -1
- package/node_modules/provider-asana/dist/asana-task.js.map +1 -1
- package/node_modules/provider-asana/src/asana-http.ts +12 -0
- package/node_modules/provider-asana/src/asana-project.ts +2 -1
- package/node_modules/provider-asana/src/asana-task.ts +2 -1
- package/node_modules/provider-notion/dist/notion-sync.d.ts +3 -2
- package/node_modules/provider-notion/dist/notion-sync.d.ts.map +1 -1
- package/node_modules/provider-notion/dist/notion-sync.js +127 -24
- package/node_modules/provider-notion/dist/notion-sync.js.map +1 -1
- package/node_modules/provider-notion/dist/notion.d.ts.map +1 -1
- package/node_modules/provider-notion/dist/notion.js +2 -1
- package/node_modules/provider-notion/dist/notion.js.map +1 -1
- package/node_modules/provider-notion/src/notion-sync.ts +123 -25
- package/node_modules/provider-notion/src/notion.ts +2 -1
- package/package.json +1 -1
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { posix } from "node:path";
|
|
2
3
|
|
|
3
|
-
import type { FetchedDocument, JsonObject, JsonValue, Source, UploadedDocument } from "wire-core";
|
|
4
|
-
import { stableJsonCompact, stableJsonPretty } from "wire-core";
|
|
4
|
+
import type { DownloadedDocument, DownloadWriter, FetchedDocument, JsonObject, JsonValue, Source, UploadedDocument } from "wire-core";
|
|
5
|
+
import { markdownFilename, stableJsonCompact, stableJsonPretty } from "wire-core";
|
|
5
6
|
import type { RuntimeCapabilities } from "wire-core";
|
|
6
7
|
|
|
7
8
|
export type NotionRichText = JsonValue[][];
|
|
@@ -776,31 +777,32 @@ export function diffNotionBlockTrees(remoteTree: NotionTree, localBlocks: readon
|
|
|
776
777
|
return { operations, summary };
|
|
777
778
|
}
|
|
778
779
|
|
|
779
|
-
function renderNode(tree: NotionTree, indent: number, parentType = ""): string[] {
|
|
780
|
+
function renderNode(tree: NotionTree, indent: number, parentType = "", download = false): string[] {
|
|
780
781
|
const prefix = " ".repeat(indent);
|
|
781
782
|
const type = tree.block["type"] === "text" && object(tree.block["format"] ?? {})["toggleable"] === true ? "toggle" : tree.block["type"] as string;
|
|
783
|
+
const children = () => tree.children.flatMap((child) => renderNode(child, indent + 1, type, download));
|
|
782
784
|
const properties = object(tree.block["properties"] ?? {});
|
|
783
785
|
const title = properties["title"] === undefined ? "" : renderRichText(properties["title"]!);
|
|
784
786
|
const format = object(tree.block["format"] ?? {});
|
|
785
787
|
if (["header", "sub_header", "sub_sub_header"].includes(type)) {
|
|
786
788
|
const marker = type === "header" ? "#" : type === "sub_header" ? "##" : "###";
|
|
787
|
-
return [`${prefix}${marker} ${title}${format["toggleable"] === true ? " {toggle}" : ""}`, ...
|
|
789
|
+
return [`${prefix}${marker} ${title}${format["toggleable"] === true ? " {toggle}" : ""}`, ...children()];
|
|
788
790
|
}
|
|
789
791
|
if (type === "bulleted_list") {
|
|
790
792
|
const lines = title.split("\n");
|
|
791
|
-
return [`${prefix}- ${lines[0]}`, ...lines.slice(1).map((line) => `${prefix} ${escapeBlockMarkdownLine(line)}`), ...
|
|
793
|
+
return [`${prefix}- ${lines[0]}`, ...lines.slice(1).map((line) => `${prefix} ${escapeBlockMarkdownLine(line)}`), ...children()];
|
|
792
794
|
}
|
|
793
795
|
if (type === "numbered_list") {
|
|
794
796
|
const lines = title.split("\n");
|
|
795
|
-
return [`${prefix}1. ${lines[0]}`, ...lines.slice(1).map((line) => `${prefix} ${escapeBlockMarkdownLine(line)}`), ...
|
|
797
|
+
return [`${prefix}1. ${lines[0]}`, ...lines.slice(1).map((line) => `${prefix} ${escapeBlockMarkdownLine(line)}`), ...children()];
|
|
796
798
|
}
|
|
797
799
|
if (type === "to_do") {
|
|
798
800
|
const checked = richTextText(properties["checked"] ?? [["No"]]) === "Yes";
|
|
799
|
-
if (title === "") return [`${prefix}:::to-do`, `${prefix}:::checked ${JSON.stringify(checked)}`, prefix, ...
|
|
801
|
+
if (title === "") return [`${prefix}:::to-do`, `${prefix}:::checked ${JSON.stringify(checked)}`, prefix, ...children(), `${prefix}:::`];
|
|
800
802
|
const lines = title.split("\n");
|
|
801
|
-
return [`${prefix}- [${checked ? "x" : " "}] ${lines[0]}`, ...lines.slice(1).map((line) => `${prefix} ${escapeBlockMarkdownLine(line)}`), ...
|
|
803
|
+
return [`${prefix}- [${checked ? "x" : " "}] ${lines[0]}`, ...lines.slice(1).map((line) => `${prefix} ${escapeBlockMarkdownLine(line)}`), ...children()];
|
|
802
804
|
}
|
|
803
|
-
if (type === "quote") return [...title.split("\n").map((line) => `${prefix}> ${escapeBlockMarkdownLine(line)}`), ...
|
|
805
|
+
if (type === "quote") return [...title.split("\n").map((line) => `${prefix}> ${escapeBlockMarkdownLine(line)}`), ...children()];
|
|
804
806
|
if (type === "divider") return [`${prefix}---`];
|
|
805
807
|
if (type === "code") {
|
|
806
808
|
const code = richTextText(properties["title"]!);
|
|
@@ -809,16 +811,16 @@ function renderNode(tree: NotionTree, indent: number, parentType = ""): string[]
|
|
|
809
811
|
const language = richTextText(properties["language"]!).replace("Plain Text", "");
|
|
810
812
|
return [`${prefix}${fence}${language}`, ...code.split("\n").map((line) => `${prefix}${line}`), `${prefix}${fence}`];
|
|
811
813
|
}
|
|
812
|
-
if (type === "image") return [`${prefix}![${escapeInlineMarkdown(richTextText(properties["alt_text"]
|
|
814
|
+
if (type === "image") return [`${prefix}![${escapeInlineMarkdown(richTextText(properties["alt_text"] ?? []))}](${encodeURI(richTextText(properties["source"]!))})`];
|
|
813
815
|
if (type === "equation") return [`${prefix}:::equation`, ...title.split("\n").map((line) => `${prefix}${line}`), `${prefix}:::`];
|
|
814
|
-
if (type === "page") return [`${prefix}:::page`, `${prefix}${title}`, ...
|
|
815
|
-
if (type === "column_list") return [`${prefix}:::columns`, ...
|
|
816
|
-
if (type === "column") return [`${prefix}:::column`, ...(format["column_ratio"] === undefined ? [] : [`${prefix}${format["column_ratio"] as number}`]), ...
|
|
817
|
-
if (type === "transclusion_container") return [`${prefix}:::synced`, ...
|
|
818
|
-
if (type === "callout" || type === "toggle") return [`${prefix}:::${type}`, `${prefix}${title}`, ...
|
|
816
|
+
if (type === "page") return [`${prefix}:::page`, `${prefix}${title}`, ...children(), `${prefix}:::`];
|
|
817
|
+
if (type === "column_list") return [`${prefix}:::columns`, ...children(), `${prefix}:::`];
|
|
818
|
+
if (type === "column") return [`${prefix}:::column`, ...(format["column_ratio"] === undefined ? [] : [`${prefix}${format["column_ratio"] as number}`]), ...children(), `${prefix}:::`];
|
|
819
|
+
if (type === "transclusion_container") return [`${prefix}:::synced`, ...children(), `${prefix}:::`];
|
|
820
|
+
if (type === "callout" || type === "toggle") return [`${prefix}:::${type}`, `${prefix}${title}`, ...children(), `${prefix}:::`];
|
|
819
821
|
if (type === "table") {
|
|
820
822
|
const columns = object(tree.block["format"]!)["table_block_column_order"] as string[];
|
|
821
|
-
const rows = tree.children.map((child) => columns.map((column) => renderRichText(object(child.block["properties"]
|
|
823
|
+
const rows = tree.children.map((child) => columns.map((column) => renderRichText(object(child.block["properties"] ?? {})[column] ?? []).replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/<br>/g, "\\<br>").replace(/\n/g, "<br>")));
|
|
822
824
|
return rows.flatMap((row, index) => index === 0 ? [`${prefix}| ${row.join(" | ")} |`, `${prefix}| ${columns.map(() => "---").join(" | ")} |`] : [`${prefix}| ${row.join(" | ")} |`]);
|
|
823
825
|
}
|
|
824
826
|
if (type !== "text") {
|
|
@@ -826,17 +828,18 @@ function renderNode(tree: NotionTree, indent: number, parentType = ""): string[]
|
|
|
826
828
|
if (tree.block["format"] !== undefined) return [`${prefix}:::notion-format`, `${prefix}:::format ${compact(tree.block["format"]!)}`, ...opaque, `${prefix}:::`];
|
|
827
829
|
return opaque;
|
|
828
830
|
}
|
|
829
|
-
|
|
830
|
-
if (
|
|
831
|
-
return title.split("\n").map((line) => `${prefix}${
|
|
831
|
+
const nested = download ? children() : [];
|
|
832
|
+
if (title === "") return [`${prefix}:::text`, `${prefix}:::`, ...nested];
|
|
833
|
+
if (["bulleted_list", "numbered_list", "to_do"].includes(parentType)) return [`${prefix}:::text`, ...title.split("\n").map((line) => `${prefix}${line}`), `${prefix}:::`, ...nested];
|
|
834
|
+
return [...title.split("\n").map((line) => `${prefix}${escapeBlockMarkdownLine(line)}`), ...nested];
|
|
832
835
|
}
|
|
833
836
|
|
|
834
|
-
export function renderNotionTreeToMarkdown(tree: NotionTree, mentions?: UserMentions, emailMentions: EmailMentions = {}): string {
|
|
837
|
+
export function renderNotionTreeToMarkdown(tree: NotionTree, mentions?: UserMentions, emailMentions: EmailMentions = {}, download = false): string {
|
|
835
838
|
const title = renderRichText(object(tree.block["properties"]!)["title"]!);
|
|
836
839
|
const compactTypes = new Set(["bulleted_list", "numbered_list", "to_do"]);
|
|
837
840
|
const body = tree.children.flatMap((child, index) => [
|
|
838
841
|
...(index === 0 || (tree.children[index - 1]!.block["type"] === child.block["type"] && compactTypes.has(child.block["type"] as string)) ? [] : [""]),
|
|
839
|
-
...renderNode(child, 0),
|
|
842
|
+
...renderNode(child, 0, "", download),
|
|
840
843
|
]);
|
|
841
844
|
let markdown = [`# ${title}`, ...body.length === 0 ? [] : ["", ...body]].join("\n").trim();
|
|
842
845
|
for (const [id, link] of Object.entries(emailMentions)) markdown = markdown.replace(new RegExp(`<span data-notion-mention="u" data-notion-id="${escapeRegExp(escapeHtml(id))}">.*?</span>`, "g"), () => link);
|
|
@@ -937,15 +940,19 @@ async function fetchComments(runtime: RuntimeCapabilities, tree: NotionTree, spa
|
|
|
937
940
|
const data = await notionPost(runtime, "getRecordValues", cookie, { requests: missing.map((id) => ({ table, id })) }, headers);
|
|
938
941
|
for (const [index, result] of (data["results"] as JsonObject[]).entries()) records[table]!.set(missing[index]!, object(result["value"]!));
|
|
939
942
|
}
|
|
943
|
+
return renderComments(tree.id, discussions, records["comment"]!, records["notion_user"]!);
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
function renderComments(pageId: string, discussions: readonly JsonObject[], commentsById: ReadonlyMap<string, JsonObject>, users: ReadonlyMap<string, JsonObject>): string {
|
|
940
947
|
const threads = discussions.map((discussion) => {
|
|
941
|
-
const comments = (discussion["comments"] as string[]).map((id) =>
|
|
948
|
+
const comments = (discussion["comments"] as string[]).map((id) => commentsById.get(id)!).filter((comment) => comment["alive"] === true);
|
|
942
949
|
if (comments.length === 0) return "";
|
|
943
950
|
const context = discussion["context"] === undefined ? "" : renderRichText(discussion["context"]!);
|
|
944
|
-
const link = `https://www.notion.so/${
|
|
951
|
+
const link = `https://www.notion.so/${pageId.replaceAll("-", "")}#${(discussion["parent_id"] as string).replaceAll("-", "")}`;
|
|
945
952
|
return [
|
|
946
|
-
`### [${discussion["parent_id"] ===
|
|
953
|
+
`### [${discussion["parent_id"] === pageId ? "Page comment" : "Inline comment"}](${link})${discussion["resolved"] === true ? " (resolved)" : ""}`,
|
|
947
954
|
...(context === "" ? [] : [context.split("\n").map((line) => `> ${line}`).join("\n")]),
|
|
948
|
-
...comments.map((comment) => `**${escapeInlineMarkdown(
|
|
955
|
+
...comments.map((comment) => `**${escapeInlineMarkdown(users.get(comment["created_by_id"] as string)!["name"] as string)}** — ${new Date(comment["created_time"] as number).toISOString()}\n\n${renderRichText(comment["text"]!)}`),
|
|
949
956
|
].join("\n\n");
|
|
950
957
|
}).filter((thread) => thread !== "");
|
|
951
958
|
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,6 +1023,97 @@ export async function fetchNotionDocument(runtime: RuntimeCapabilities, url: str
|
|
|
1016
1023
|
return notionDocument(source.identifier, tree, undefined, {}, comments);
|
|
1017
1024
|
}
|
|
1018
1025
|
|
|
1026
|
+
export async function downloadNotionDirectory(runtime: RuntimeCapabilities, url: string, source: Source, write: DownloadWriter): Promise<DownloadedDocument | null> {
|
|
1027
|
+
const cookies = await runtime.cookies.loadSaved("notion");
|
|
1028
|
+
if (cookies === null) throw notionAuthError();
|
|
1029
|
+
const cookie = cookies.map(({ name, value }) => `${name}=${value}`).join("; ");
|
|
1030
|
+
const headers = { "x-notion-active-user-header": cookies.find(({ name }) => name === "notion_user_id")!.value, referer: url };
|
|
1031
|
+
const rootId = formatBlockId(source.identifier);
|
|
1032
|
+
const blocks = new Map<string, JsonObject>();
|
|
1033
|
+
const read = async (table: string, ids: readonly string[], records: Map<string, JsonObject>) => {
|
|
1034
|
+
for (let start = 0; start < ids.length; start += 100) {
|
|
1035
|
+
const spaceId = blocks.get(rootId)?.["space_id"];
|
|
1036
|
+
const requests = ids.slice(start, start + 100).map((id) => ({ pointer: { table, id, ...(spaceId === undefined ? {} : { spaceId }) }, version: -1 }));
|
|
1037
|
+
const data = await notionPost(runtime, "syncRecordValues", cookie, { requests }, headers);
|
|
1038
|
+
const returned = object(object(data["recordMap"]!)[table] ?? {});
|
|
1039
|
+
for (const { pointer: { id } } of requests) {
|
|
1040
|
+
if (returned[id] === undefined) continue;
|
|
1041
|
+
const value = object(object(returned[id])["value"]!)["value"];
|
|
1042
|
+
if (value !== undefined) records.set(id, object(value));
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
};
|
|
1046
|
+
const seen = new Set<string>([rootId]);
|
|
1047
|
+
let pending = [rootId];
|
|
1048
|
+
while (pending.length > 0) {
|
|
1049
|
+
await read("block", pending, blocks);
|
|
1050
|
+
const next: string[] = [];
|
|
1051
|
+
for (const id of pending) {
|
|
1052
|
+
const block = blocks.get(id);
|
|
1053
|
+
if (block === undefined || block["alive"] === false) continue;
|
|
1054
|
+
for (const child of block["content"] as readonly string[] | undefined ?? []) {
|
|
1055
|
+
if (seen.has(child)) continue;
|
|
1056
|
+
seen.add(child);
|
|
1057
|
+
next.push(child);
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
pending = next;
|
|
1061
|
+
}
|
|
1062
|
+
const root = blocks.get(rootId);
|
|
1063
|
+
if (root === undefined || root["alive"] === false) throw new Error(`Notion page is unavailable: ${url}`);
|
|
1064
|
+
if (![...blocks.values()].some((block) => block !== root && block["alive"] !== false && block["type"] === "page")) return null;
|
|
1065
|
+
|
|
1066
|
+
const discussions = new Map<string, JsonObject>(), comments = new Map<string, JsonObject>(), users = new Map<string, JsonObject>();
|
|
1067
|
+
const live = [...blocks.values()].filter((block) => block["alive"] !== false);
|
|
1068
|
+
await read("discussion", [...new Set(live.flatMap((block) => block["discussions"] as string[] | undefined ?? []))], discussions);
|
|
1069
|
+
await read("comment", [...new Set([...discussions.values()].flatMap((discussion) => discussion["comments"] as string[]))], comments);
|
|
1070
|
+
for (const table of ["notion_user", "bot"]) {
|
|
1071
|
+
const authors = [...comments.values()].filter((comment) => comment["alive"] === true && comment["created_by_table"] === table);
|
|
1072
|
+
await read(table, [...new Set(authors.map((comment) => text(comment["created_by_id"]!)))], users);
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
const paths = new Map<string, string>();
|
|
1076
|
+
const directoryName = (page: JsonObject) => {
|
|
1077
|
+
const slug = markdownFilename(richTextText(object(page["properties"] ?? {})["title"] ?? [])).slice(0, -3);
|
|
1078
|
+
return `${[...slug].slice(0, 48).join("")}-${text(page["id"]!).replaceAll("-", "")}`;
|
|
1079
|
+
};
|
|
1080
|
+
const exportPage = async (page: JsonObject, directory: string): Promise<DownloadedDocument> => {
|
|
1081
|
+
const id = text(page["id"]!);
|
|
1082
|
+
const path = posix.join(directory, "index.md");
|
|
1083
|
+
paths.set(id, path);
|
|
1084
|
+
const threads: JsonObject[] = [];
|
|
1085
|
+
const build = async (blockId: string, pageRoot: boolean): Promise<NotionTree> => {
|
|
1086
|
+
const block = blocks.get(blockId);
|
|
1087
|
+
if (block === undefined || (!pageRoot && block["type"] === "page")) {
|
|
1088
|
+
let label = "Unavailable Notion block";
|
|
1089
|
+
let href = `https://www.notion.so/${blockId.replaceAll("-", "")}`;
|
|
1090
|
+
if (block !== undefined) {
|
|
1091
|
+
label = richTextText(object(block["properties"] ?? {})["title"] ?? []) || "Untitled";
|
|
1092
|
+
if (!paths.has(blockId)) {
|
|
1093
|
+
const child = await exportPage(block, posix.join(directory, directoryName(block)));
|
|
1094
|
+
await write(child.path, child.markdown);
|
|
1095
|
+
}
|
|
1096
|
+
href = posix.relative(directory, paths.get(blockId)!);
|
|
1097
|
+
}
|
|
1098
|
+
return { id: blockId, block: { type: "text", properties: { title: [[label, [["a", href]]]] } }, children: [] };
|
|
1099
|
+
}
|
|
1100
|
+
for (const threadId of block["discussions"] as string[] | undefined ?? []) {
|
|
1101
|
+
const thread = discussions.get(threadId);
|
|
1102
|
+
if (thread !== undefined && thread["alive"] !== false) threads.push(thread);
|
|
1103
|
+
}
|
|
1104
|
+
const children: NotionTree[] = [];
|
|
1105
|
+
for (const child of block["content"] as string[] | undefined ?? []) {
|
|
1106
|
+
if (blocks.get(child)?.["alive"] !== false) children.push(await build(child, false));
|
|
1107
|
+
}
|
|
1108
|
+
return { id: blockId, block, children };
|
|
1109
|
+
};
|
|
1110
|
+
const tree = await build(id, true);
|
|
1111
|
+
const markdown = renderNotionTreeToMarkdown(tree, undefined, {}, true) + renderComments(id, threads, comments, users);
|
|
1112
|
+
return { path, title: richTextText(object(page["properties"]!)["title"]!), markdown, data: { page_id: id } };
|
|
1113
|
+
};
|
|
1114
|
+
return exportPage(root, directoryName(root));
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1019
1117
|
export async function uploadNotionDocument(runtime: RuntimeCapabilities, markdown: string, _markdownPath: string): Promise<UploadedDocument> {
|
|
1020
1118
|
const split = splitTitle(withoutComments(markdown));
|
|
1021
1119
|
if (split.title === "") throw new Error("Markdown document requires a first heading");
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { defineService } from "wire-core";
|
|
2
2
|
import type { RuntimeCapabilities } from "wire-core";
|
|
3
|
-
import { fetchNotionDocument, synchronizeNotionDocument, uploadNotionDocument } from "./notion-sync.js";
|
|
3
|
+
import { downloadNotionDirectory, fetchNotionDocument, synchronizeNotionDocument, uploadNotionDocument } from "./notion-sync.js";
|
|
4
4
|
|
|
5
5
|
const notionPageId = /[a-f0-9]{32}|[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i;
|
|
6
6
|
|
|
@@ -9,6 +9,7 @@ export const notionService = defineService<RuntimeCapabilities>({
|
|
|
9
9
|
matches: (url) => (url.hostname === "www.notion.so" || url.hostname === "notion.so" || url.hostname === "app.notion.com" || url.hostname.endsWith(".notion.site")) && notionPageId.test(url.href),
|
|
10
10
|
parse: (url) => Object.freeze({ service: "notion", identifier: notionPageId.exec(url.href)![0]!.replaceAll("-", "").toLowerCase(), type: "document" }),
|
|
11
11
|
fetch: fetchNotionDocument,
|
|
12
|
+
download: downloadNotionDirectory,
|
|
12
13
|
synchronize: (runtime, url, source, base, markdown, markdownPath) => synchronizeNotionDocument(runtime, url, source, base, markdown, markdownPath),
|
|
13
14
|
upload: uploadNotionDocument,
|
|
14
15
|
});
|