Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat: support pasted memo images

tianma328c3e15b0f7
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 93d9a4a0..41a60b60 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -14,6 +14,7 @@ import {
type MemoDetail,
type MemoSummary,
type Notebook,
+ type Resource,
type TiptapDoc,
} from "@edgeever/shared";
import { zValidator } from "@hono/zod-validator";
@@ -28,6 +29,7 @@ type Bindings = {
EDGE_EVER_AUTH_USERNAME?: string;
EDGE_EVER_AUTH_PASSWORD_HASH?: string;
EDGE_EVER_SESSION_TTL_DAYS?: string;
+ EDGE_EVER_R2_BUCKET_NAME?: string;
};
type AuthContext = {
@@ -98,6 +100,23 @@ type ApiTokenRow = {
expires_at: string | null;
};
+type ResourceRow = {
+ id: string;
+ memo_id: string;
+ original_memo_id: string | null;
+ bucket_name: string;
+ object_key: string;
+ kind: "image" | "attachment";
+ mime_type: string | null;
+ filename: string | null;
+ byte_size: number;
+ sha256: string | null;
+ width: number | null;
+ height: number | null;
+ created_at: string;
+ updated_at: string;
+};
+
type AppContext = Context<{ Bindings: Bindings; Variables: { auth: AuthContext } }>;
const SESSION_COOKIE = "edgeever_session";
@@ -107,6 +126,15 @@ const PASSWORD_HASH_BYTES = 32;
const PASSWORD_SALT_BYTES = 16;
const SESSION_TOKEN_BYTES = 32;
const DEFAULT_SESSION_TTL_DAYS = 30;
+const DEFAULT_R2_BUCKET_NAME = "edgeever-resources";
+const MAX_IMAGE_UPLOAD_BYTES = 10 * 1024 * 1024;
+const SUPPORTED_IMAGE_MIME_TYPES = new Set([
+ "image/png",
+ "image/jpeg",
+ "image/gif",
+ "image/webp",
+ "image/avif",
+]);
const app = new Hono<{ Bindings: Bindings; Variables: { auth: AuthContext } }>();
@@ -398,6 +426,132 @@ app.get("/api/v1/memos/:id", async (c) => {
return c.json({ memo });
});
+app.post("/api/v1/memos/:id/resources", async (c) => {
+ const memoId = c.req.param("id");
+ const memo = await getMemoDetail(c.env.DB, memoId);
+
+ if (!memo) {
+ return notFound(c, "Memo not found");
+ }
+
+ const form = await c.req.raw.formData();
+ const file = form.get("file");
+
+ if (!(file instanceof File)) {
+ return badRequest(c, "Expected multipart form field named file.");
+ }
+
+ const mimeType = file.type || "application/octet-stream";
+
+ if (!SUPPORTED_IMAGE_MIME_TYPES.has(mimeType)) {
+ return c.json(
+ {
+ error: {
+ code: "unsupported_media_type",
+ message: "Only PNG, JPEG, GIF, WebP and AVIF images are supported.",
+ },
+ },
+ 415
+ );
+ }
+
+ if (file.size <= 0 || file.size > MAX_IMAGE_UPLOAD_BYTES) {
+ return c.json(
+ {
+ error: {
+ code: "upload_too_large",
+ message: "Image must be between 1 byte and 10 MB.",
+ },
+ },
+ 413
+ );
+ }
+
+ const actor = getAuditActor(c);
+ const resourceId = createId("res");
+ const now = isoNow();
+ const bytes = new Uint8Array(await file.arrayBuffer());
+ const objectKey = `memos/${memoId}/${resourceId}${inferImageExtension(file.name, mimeType)}`;
+ const bucketName = c.env.EDGE_EVER_R2_BUCKET_NAME?.trim() || DEFAULT_R2_BUCKET_NAME;
+ const filename = normalizeFilename(file.name) || `${resourceId}${inferImageExtension(file.name, mimeType)}`;
+ const checksum = await sha256Bytes(bytes);
+
+ await c.env.RESOURCES.put(objectKey, bytes, {
+ httpMetadata: {
+ contentType: mimeType,
+ cacheControl: "private, max-age=3600",
+ },
+ customMetadata: {
+ memoId,
+ resourceId,
+ filename,
+ },
+ });
+
+ try {
+ await c.env.DB.batch([
+ c.env.DB.prepare(
+ `INSERT INTO resources (
+ id, memo_id, bucket_name, object_key, kind, mime_type, filename,
+ byte_size, sha256, metadata_json, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, 'image', ?, ?, ?, ?, ?, ?, ?)`
+ ).bind(
+ resourceId,
+ memoId,
+ bucketName,
+ objectKey,
+ mimeType,
+ filename,
+ file.size,
+ checksum,
+ JSON.stringify({ source: "paste" }),
+ now,
+ now
+ ),
+ auditStatement(c.env.DB, actor.actorType, actor.actorId, "resource.create", "resource", resourceId, {
+ memoId,
+ mimeType,
+ byteSize: file.size,
+ }),
+ ]);
+ } catch (error) {
+ await c.env.RESOURCES.delete(objectKey);
+ throw error;
+ }
+
+ const resource = await getResourceRow(c.env.DB, resourceId);
+
+ if (!resource) {
+ return notFound(c, "Resource not found");
+ }
+
+ return c.json({ resource: mapResource(resource) }, 201);
+});
+
+app.get("/api/v1/resources/:id/blob", async (c) => {
+ const resource = await getResourceRow(c.env.DB, c.req.param("id"));
+
+ if (!resource) {
+ return notFound(c, "Resource not found");
+ }
+
+ const object = await c.env.RESOURCES.get(resource.object_key);
+
+ if (!object) {
+ return notFound(c, "Resource object not found");
+ }
+
+ const headers = new Headers();
+ object.writeHttpMetadata(headers);
+ headers.set("Content-Type", resource.mime_type ?? headers.get("Content-Type") ?? "application/octet-stream");
+ headers.set("Cache-Control", headers.get("Cache-Control") ?? "private, max-age=3600");
+ headers.set("Content-Length", String(object.size));
+ headers.set("Content-Disposition", contentDispositionInline(resource.filename));
+ headers.set("X-Content-Type-Options", "nosniff");
+
+ return new Response(object.body, { headers });
+});
+
app.patch("/api/v1/memos/:id", zValidator("json", MemoUpdateSchema), async (c) => {
const id = c.req.param("id");
const input = c.req.valid("json");
@@ -955,6 +1109,22 @@ const mapMemoDetail = (row: MemoDetailRow): MemoDetail => ({
mergedIntoMemoId: row.merged_into_memo_id,
});
+const mapResource = (row: ResourceRow): Resource => ({
+ id: row.id,
+ memoId: row.memo_id,
+ originalMemoId: row.original_memo_id,
+ kind: row.kind,
+ mimeType: row.mime_type,
+ filename: row.filename,
+ byteSize: row.byte_size,
+ sha256: row.sha256,
+ width: row.width,
+ height: row.height,
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ url: `/api/v1/resources/${row.id}/blob`,
+});
+
const getNotebook = async (db: D1Database, id: string): Promise<Notebook | null> => {
const row = await db
.prepare(
@@ -987,6 +1157,17 @@ const getMemoDetail = async (db: D1Database, id: string): Promise<MemoDetail | n
return row ? mapMemoDetail(row) : null;
};
+const getResourceRow = async (db: D1Database, id: string): Promise<ResourceRow | null> =>
+ db
+ .prepare(
+ `SELECT id, memo_id, original_memo_id, bucket_name, object_key, kind, mime_type,
+ filename, byte_size, sha256, width, height, created_at, updated_at
+ FROM resources
+ WHERE id = ? AND is_deleted = 0`
+ )
+ .bind(id)
+ .first<ResourceRow>();
+
const parseJsonArray = (json: string): string[] => {
try {
const value = JSON.parse(json);
@@ -1065,10 +1246,54 @@ const toFtsQuery = (value: string) => {
const sha256 = async (value: string) => {
const bytes = new TextEncoder().encode(value);
- const digest = await crypto.subtle.digest("SHA-256", bytes);
+ return sha256Bytes(bytes);
+};
+
+const sha256Bytes = async (bytes: Uint8Array) => {
+ const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
+ const digest = await crypto.subtle.digest("SHA-256", buffer);
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
};
+const inferImageExtension = (filename: string, mimeType: string) => {
+ const extension = /\.(png|jpe?g|gif|webp|avif)$/i.exec(filename)?.[0]?.toLowerCase();
+
+ if (extension) {
+ return extension === ".jpeg" ? ".jpg" : extension;
+ }
+
+ switch (mimeType) {
+ case "image/png":
+ return ".png";
+ case "image/jpeg":
+ return ".jpg";
+ case "image/gif":
+ return ".gif";
+ case "image/webp":
+ return ".webp";
+ case "image/avif":
+ return ".avif";
+ default:
+ return "";
+ }
+};
+
+const normalizeFilename = (filename: string) =>
+ filename
+ .trim()
+ .replace(/[\\/]/g, "-")
+ .replace(/[\u0000-\u001f\u007f]/g, "")
+ .slice(0, 160);
+
+const contentDispositionInline = (filename: string | null) => {
+ if (!filename) {
+ return "inline";
+ }
+
+ const fallback = normalizeFilename(filename).replace(/"/g, "'");
+ return `inline; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(filename)}`;
+};
+
const notFound = (c: Context, message: string) =>
c.json(
{
@@ -1080,6 +1305,17 @@ const notFound = (c: Context, message: string) =>
404
);
+const badRequest = (c: Context, message: string) =>
+ c.json(
+ {
+ error: {
+ code: "bad_request",
+ message,
+ },
+ },
+ 400
+ );
+
const unauthorized = (c: Context, message: string) =>
c.json(
{
diff --git a/apps/web/src/app/App.tsx b/apps/web/src/app/App.tsx
index 0f28d451..6a4ddc8a 100644
--- a/apps/web/src/app/App.tsx
+++ b/apps/web/src/app/App.tsx
@@ -1,6 +1,7 @@
import type { AuthSession, AuthUser, MemoDetail, MemoSummary, Notebook, TiptapDoc } from "@edgeever/shared";
+import Image from "@tiptap/extension-image";
import Placeholder from "@tiptap/extension-placeholder";
-import { EditorContent, useEditor } from "@tiptap/react";
+import { EditorContent, useEditor, type Editor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
@@ -24,7 +25,7 @@ import {
Tags,
Trash2,
} from "lucide-react";
-import { useEffect, useMemo, useRef, useState, type FormEvent, type MouseEvent } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState, type FormEvent, type MouseEvent } from "react";
import { api } from "@/lib/api";
import { localDb } from "@/lib/local-db";
import { buildNotebookTree, cn, formatDateTime, parseTagsText, type NotebookNode } from "@/lib/utils";
@@ -803,6 +804,22 @@ const MemoCard = ({
);
};
+const SUPPORTED_PASTE_IMAGE_TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"]);
+
+const getImageFilesFromDataTransfer = (dataTransfer: DataTransfer | null) => {
+ if (!dataTransfer) {
+ return [];
+ }
+
+ const fileItems = Array.from(dataTransfer.items ?? [])
+ .filter((item) => item.kind === "file")
+ .map((item) => item.getAsFile())
+ .filter((file): file is File => Boolean(file));
+ const files = fileItems.length > 0 ? fileItems : Array.from(dataTransfer.files ?? []);
+
+ return files.filter((file) => SUPPORTED_PASTE_IMAGE_TYPES.has(file.type));
+};
+
const EditorPane = ({
memo,
notebooks,
@@ -821,9 +838,56 @@ const EditorPane = ({
const [title, setTitle] = useState("");
const [tagsText, setTagsText] = useState("");
const [saveState, setSaveState] = useState<"idle" | "saving" | "saved">("idle");
+ const [imageUploadState, setImageUploadState] = useState<"idle" | "uploading" | "error">("idle");
+ const memoRef = useRef<MemoDetail | null>(memo);
+ const editorRef = useRef<Editor | null>(null);
+ const insertImageFiles = useCallback((files: File[]) => {
+ const currentMemo = memoRef.current;
+ const currentEditor = editorRef.current;
+
+ if (!currentMemo || !currentEditor || files.length === 0) {
+ return;
+ }
+
+ const targetMemoId = currentMemo.id;
+
+ void (async () => {
+ setImageUploadState("uploading");
+
+ try {
+ for (const file of files) {
+ const { resource } = await api.uploadMemoResource(targetMemoId, file);
+
+ if (memoRef.current?.id !== targetMemoId || !editorRef.current) {
+ setImageUploadState("idle");
+ return;
+ }
+
+ editorRef.current
+ .chain()
+ .focus()
+ .setImage({
+ src: resource.url,
+ alt: resource.filename ?? file.name,
+ title: resource.filename ?? file.name,
+ })
+ .run();
+ }
+
+ setImageUploadState("idle");
+ } catch {
+ setImageUploadState("error");
+ window.setTimeout(() => setImageUploadState("idle"), 2200);
+ }
+ })();
+ }, []);
const editor = useEditor({
extensions: [
StarterKit,
+ Image.configure({
+ allowBase64: false,
+ inline: false,
+ }),
Placeholder.configure({
placeholder: "Start writing...",
}),
@@ -833,9 +897,45 @@ const EditorPane = ({
attributes: {
class: "prose prose-slate max-w-none",
},
+ handlePaste: (_view, event) => {
+ const files = getImageFilesFromDataTransfer(event.clipboardData);
+
+ if (files.length === 0) {
+ return false;
+ }
+
+ event.preventDefault();
+ insertImageFiles(files);
+ return true;
+ },
+ handleDrop: (_view, event) => {
+ const files = getImageFilesFromDataTransfer(event.dataTransfer);
+
+ if (files.length === 0) {
+ return false;
+ }
+
+ event.preventDefault();
+ insertImageFiles(files);
+ return true;
+ },
},
});
+ useEffect(() => {
+ memoRef.current = memo;
+ }, [memo]);
+
+ useEffect(() => {
+ editorRef.current = editor;
+
+ return () => {
+ if (editorRef.current === editor) {
+ editorRef.current = null;
+ }
+ };
+ }, [editor]);
+
useEffect(() => {
if (!memo) {
setTitle("");
@@ -940,6 +1040,18 @@ const EditorPane = ({
</div>
<div className="flex items-center gap-2">
+ {imageUploadState !== "idle" ? (
+ <span
+ className={cn(
+ "hidden rounded-md px-2 py-1 text-xs font-medium sm:inline-flex",
+ imageUploadState === "error"
+ ? "bg-rose-50 text-rose-700"
+ : "bg-emerald-50 text-emerald-700"
+ )}
+ >
+ {imageUploadState === "error" ? "图片上传失败" : "图片上传中"}
+ </span>
+ ) : null}
<Button size="sm" variant="ghost" title="删除笔记" onClick={() => void onDeleted(memo.id)}>
<Trash2 className="h-4 w-4" />
</Button>
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index a9aa0e8a..9fdbbcea 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -1,4 +1,4 @@
-import type { AuthSession, MemoDetail, MemoSummary, Notebook, TiptapDoc } from "@edgeever/shared";
+import type { AuthSession, MemoDetail, MemoSummary, Notebook, Resource, TiptapDoc } from "@edgeever/shared";
type ListNotebooksResponse = {
notebooks: Notebook[];
@@ -16,6 +16,10 @@ type NotebookResponse = {
notebook: Notebook;
};
+type ResourceResponse = {
+ resource: Resource;
+};
+
export class ApiRequestError extends Error {
status: number;
code?: string;
@@ -29,13 +33,16 @@ export class ApiRequestError extends Error {
}
const request = async <T>(path: string, init?: RequestInit): Promise<T> => {
+ const headers = new Headers(init?.headers);
+
+ if (!(init?.body instanceof FormData) && !headers.has("Content-Type")) {
+ headers.set("Content-Type", "application/json");
+ }
+
const response = await fetch(path, {
credentials: "include",
...init,
- headers: {
- "Content-Type": "application/json",
- ...init?.headers,
- },
+ headers,
});
if (!response.ok) {
@@ -101,6 +108,16 @@ export const api = {
getMemo: (memoId: string) => request<MemoResponse>(`/api/v1/memos/${memoId}`),
+ uploadMemoResource: (memoId: string, file: File) => {
+ const form = new FormData();
+ form.append("file", file);
+
+ return request<ResourceResponse>(`/api/v1/memos/${memoId}/resources`, {
+ method: "POST",
+ body: form,
+ });
+ },
+
updateMemo: (
memoId: string,
payload: {
diff --git a/apps/web/src/styles/globals.css b/apps/web/src/styles/globals.css
index 568e9fb9..ff6b7ff8 100644
--- a/apps/web/src/styles/globals.css
+++ b/apps/web/src/styles/globals.css
@@ -79,6 +79,20 @@ textarea {
margin: 0.25rem 0;
}
+.ProseMirror img {
+ display: block;
+ max-width: 100%;
+ height: auto;
+ margin: 1rem 0;
+ border: 1px solid #d1fae5;
+ border-radius: 8px;
+}
+
+.ProseMirror img.ProseMirror-selectednode {
+ outline: 2px solid #34d399;
+ outline-offset: 3px;
+}
+
.ProseMirror p.is-editor-empty:first-child::before {
color: #94a3b8;
content: attr(data-placeholder);
diff --git a/bun.lock b/bun.lock
index 1395d3e0..1824cc29 100644
--- a/bun.lock
+++ b/bun.lock
@@ -8,6 +8,7 @@
"@edgeever/shared": "workspace:*",
"@hono/zod-validator": "latest",
"@tanstack/react-query": "latest",
+ "@tiptap/extension-image": "^3.27.1",
"@tiptap/extension-placeholder": "latest",
"@tiptap/react": "latest",
"@tiptap/starter-kit": "latest",
@@ -284,6 +285,8 @@
"@tiptap/extension-horizontal-rule": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.27.1", "@tiptap/pm": "3.27.1" } }, "sha512-QlKE7qn5qMnIGVGhXQlvYedvLtNJ9z0dmit5w8vPb8tKzW4Spk6M7N2kruprrDA8GBwHfeR5wmF+njfUm34qxg=="],
+ "@tiptap/extension-image": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.27.1" } }, "sha512-+JTahgQT+NxiGjduaB3qJVyhU/wh4m3pVkht1Earioku2bm/apj5Lb8rSowa/NJYP3B+oQgV/V4YLw5dtDgBoA=="],
+
"@tiptap/extension-italic": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.27.1" } }, "sha512-jGGeyn9uRUnNjSTHpbqhiGsp6KaYTSbV09jDXPJI9cDwfV9hpugLvpaCZd0BMBbhU1B1W6kOfX0BE15qX/HQfA=="],
"@tiptap/extension-link": ["@tiptap/[email protected]", "", { "dependencies": { "linkifyjs": "^4.3.3" }, "peerDependencies": { "@tiptap/core": "3.27.1", "@tiptap/pm": "3.27.1" } }, "sha512-/2jBfsxBZUDGJmpZifqRQPz7f1E5qpS1BckTZ39TADzUJX+feKy7RJ3DtQ02+8y6SSMzvP9loGVjrk6zEMTk4g=="],
diff --git a/package.json b/package.json
index 3993899c..52045183 100644
--- a/package.json
+++ b/package.json
@@ -37,6 +37,7 @@
"@edgeever/shared": "workspace:*",
"@hono/zod-validator": "latest",
"@tanstack/react-query": "latest",
+ "@tiptap/extension-image": "^3.27.1",
"@tiptap/extension-placeholder": "latest",
"@tiptap/react": "latest",
"@tiptap/starter-kit": "latest",
diff --git a/packages/shared/src/content.ts b/packages/shared/src/content.ts
index 26055cf4..e2ecfdd5 100644
--- a/packages/shared/src/content.ts
+++ b/packages/shared/src/content.ts
@@ -34,6 +34,7 @@ export const markdownToDoc = (markdown: string): TiptapDoc => {
type: "doc",
content: blocks.map((block) => {
const heading = /^(#{1,3})\s+(.+)$/.exec(block);
+ const image = /^!\[([^\]]*)\]\((\S+?)(?:\s+"([^"]+)")?\)$/.exec(block);
if (heading) {
return {
@@ -43,6 +44,23 @@ export const markdownToDoc = (markdown: string): TiptapDoc => {
};
}
+ if (image) {
+ return {
+ type: "image",
+ attrs: {
+ src: image[2],
+ alt: image[1] || null,
+ title: image[3] || null,
+ },
+ };
+ }
+
+ if (/^-{3,}$/.test(block)) {
+ return {
+ type: "horizontalRule",
+ };
+ }
+
return {
type: "paragraph",
content: [{ type: "text", text: block }],
@@ -59,12 +77,23 @@ export const docToText = (doc: unknown): string => {
return;
}
- const current = node as { text?: unknown; content?: unknown };
+ const current = node as { type?: unknown; text?: unknown; attrs?: Record<string, unknown>; content?: unknown };
if (typeof current.text === "string") {
pieces.push(current.text);
}
+ if (current.type === "image") {
+ const label =
+ getStringAttr(current.attrs, "alt") ||
+ getStringAttr(current.attrs, "title") ||
+ getStringAttr(current.attrs, "filename");
+
+ if (label) {
+ pieces.push(label);
+ }
+ }
+
if (Array.isArray(current.content)) {
for (const child of current.content) {
walk(child);
@@ -89,6 +118,76 @@ export const docToMarkdown = (doc: unknown): string => {
}
return root.content
+ .map((node) => blockToMarkdown(node))
+ .filter(Boolean)
+ .join("\n\n");
+};
+
+const blockToMarkdown = (node: unknown): string => {
+ if (!node || typeof node !== "object") {
+ return "";
+ }
+
+ const current = node as {
+ type?: unknown;
+ attrs?: Record<string, unknown>;
+ content?: unknown;
+ text?: unknown;
+ };
+
+ if (current.type === "heading") {
+ const level = typeof current.attrs?.level === "number" ? current.attrs.level : 1;
+ const text = inlineToMarkdown(current.content);
+ return text ? `${"#".repeat(Math.min(Math.max(level, 1), 6))} ${text}` : "";
+ }
+
+ if (current.type === "image") {
+ return imageToMarkdown(current.attrs);
+ }
+
+ if (current.type === "horizontalRule") {
+ return "---";
+ }
+
+ if (current.type === "bulletList" && Array.isArray(current.content)) {
+ return current.content
+ .map((item) => inlineToMarkdown((item as { content?: unknown })?.content))
+ .filter(Boolean)
+ .map((item) => `- ${item.replace(/\n/g, "\n ")}`)
+ .join("\n");
+ }
+
+ if (current.type === "orderedList" && Array.isArray(current.content)) {
+ return current.content
+ .map((item, index) => {
+ const text = inlineToMarkdown((item as { content?: unknown })?.content);
+ return text ? `${index + 1}. ${text.replace(/\n/g, "\n ")}` : "";
+ })
+ .filter(Boolean)
+ .join("\n");
+ }
+
+ if (current.type === "blockquote") {
+ const text = inlineToMarkdown(current.content);
+ return text
+ .split("\n")
+ .map((line) => `> ${line}`)
+ .join("\n");
+ }
+
+ if (current.type === "codeBlock") {
+ return `\`\`\`\n${docToText({ content: current.content })}\n\`\`\``;
+ }
+
+ return inlineToMarkdown(current.content);
+};
+
+const inlineToMarkdown = (content: unknown): string => {
+ if (!Array.isArray(content)) {
+ return "";
+ }
+
+ return content
.map((node) => {
if (!node || typeof node !== "object") {
return "";
@@ -96,24 +195,45 @@ export const docToMarkdown = (doc: unknown): string => {
const current = node as {
type?: unknown;
- attrs?: { level?: unknown };
+ text?: unknown;
+ attrs?: Record<string, unknown>;
content?: unknown;
};
- const text = docToText({ content: current.content });
- if (!text) {
- return "";
+ if (typeof current.text === "string") {
+ return current.text;
}
- if (current.type === "heading") {
- const level = typeof current.attrs?.level === "number" ? current.attrs.level : 1;
- return `${"#".repeat(Math.min(Math.max(level, 1), 6))} ${text}`;
+ if (current.type === "hardBreak") {
+ return "\n";
}
- return text;
+ if (current.type === "image") {
+ return imageToMarkdown(current.attrs);
+ }
+
+ return inlineToMarkdown(current.content);
})
- .filter(Boolean)
- .join("\n\n");
+ .join("");
+};
+
+const imageToMarkdown = (attrs: Record<string, unknown> | undefined): string => {
+ const src = getStringAttr(attrs, "src");
+
+ if (!src) {
+ return "";
+ }
+
+ const alt = getStringAttr(attrs, "alt");
+ const title = getStringAttr(attrs, "title");
+ const titleSuffix = title ? ` "${title.replace(/"/g, '\\"')}"` : "";
+
+ return `![${alt.replace(/\]/g, "\\]")}](${src}${titleSuffix})`;
+};
+
+const getStringAttr = (attrs: Record<string, unknown> | undefined, key: string) => {
+ const value = attrs?.[key];
+ return typeof value === "string" ? value.trim() : "";
};
export const createExcerpt = (text: string, maxLength = 30): string => {
diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts
index fbbb84c2..696035a6 100644
--- a/packages/shared/src/types.ts
+++ b/packages/shared/src/types.ts
@@ -34,6 +34,24 @@ export type MemoDetail = MemoSummary & {
mergedIntoMemoId: string | null;
};
+export type ResourceKind = "image" | "attachment";
+
+export type Resource = {
+ id: string;
+ memoId: string;
+ originalMemoId: string | null;
+ kind: ResourceKind;
+ mimeType: string | null;
+ filename: string | null;
+ byteSize: number;
+ sha256: string | null;
+ width: number | null;
+ height: number | null;
+ createdAt: string;
+ updatedAt: string;
+ url: string;
+};
+
export type AuthUser = {
id: string;
username: string;
diff --git a/scripts/run-wrangler.mjs b/scripts/run-wrangler.mjs
index 65089fa5..c7da85bc 100644
--- a/scripts/run-wrangler.mjs
+++ b/scripts/run-wrangler.mjs
@@ -117,6 +117,7 @@ config = replaceTomlValue(
const runtimeVars = {
EDGE_EVER_AUTH_USERNAME: envValue("AUTH_USERNAME"),
EDGE_EVER_SESSION_TTL_DAYS: envValue("SESSION_TTL_DAYS"),
+ EDGE_EVER_R2_BUCKET_NAME: envValue("R2_BUCKET_NAME"),
};
const runtimeVarLines = Object.entries(runtimeVars)
.filter(([, value]) => Boolean(value))