CI / go (Server) (push) Failing after 4m38s
CI / go (Web-App) (push) Successful in 12m18s
Docs / build (push) Canceled after 0s
Docs / deploy (push) Canceled after 0s
CI / frontend (push) Failing after 7m49s
CI / desktop (ubuntu-latest) (push) Successful in 1h25m30s
CI / mobile (push) Failing after 5m14s
CI / docker (push) Successful in 39m26s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
Databases (ADR-13 follow-ups):
- Relation properties link records to another database, on the same page
or on any page the reader can open (read live and read-only, like synced
pages). Cells list the linked titles; clicking one opens the record.
- Rollup properties work out counts, sums, averages, medians, min/max,
ranges, earliest/latest dates and checked counts over related records.
Neither is stored: views compute them before drawing (linked.ts), so they
follow both databases live, and rollups sort and filter as numbers.
- Exports (Markdown, HTML, PDF, Word) resolve them for same-page databases.
- A record opens as a full page at /p/<page>/r/<database>/<record>, with
"Open as full page" on the side panel and "Back to the page".
Edgeless mode (ADR-14 follow-ups):
- History previews show a version's canvas and count canvas changes.
- Comments can be anchored to canvas elements (anchor {element}); elements
with open threads show a badge that opens the thread.
- Workspaces choose how new pages open (workspaces.default_page_mode); the
per-device choice now defaults to following the workspace.
- Phones edit the canvas once a page is opened for editing; the page note
shows the page title.
Languages:
- The admin panel speaks English, Polish, German, French and Spanish, with
a picker sharing the web app's setting and a key parity test.
- The phone app speaks the same five, follows the phone's language (and
Android's per-app language setting), and has its own parity test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
623 lines
33 KiB
TypeScript
623 lines
33 KiB
TypeScript
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
import type { components } from "./schema";
|
|
|
|
type Schemas = components["schemas"];
|
|
export type Version = Schemas["Version"];
|
|
export type Status = Schemas["Status"];
|
|
export type User = Schemas["User"];
|
|
export type Session = Schemas["Session"];
|
|
export type UserList = Schemas["UserList"];
|
|
export type AuthMethods = Schemas["AuthMethods"];
|
|
export type SignupRequest = Schemas["SignupRequest"];
|
|
export type ErrorBody = Schemas["Error"];
|
|
export type Role = Schemas["Role"];
|
|
export type WorkspaceRole = Schemas["WorkspaceRole"];
|
|
export type Organization = Schemas["Organization"];
|
|
export type Workspace = Schemas["Workspace"];
|
|
export type WorkspaceMember = Schemas["WorkspaceMember"];
|
|
export type CreateUserRequest = Schemas["CreateUserRequest"];
|
|
export type UpdateUserRequest = Schemas["UpdateUserRequest"];
|
|
export type SpaceRole = Schemas["SpaceRole"];
|
|
export type SpaceDefaultRole = Schemas["SpaceDefaultRole"];
|
|
export type SpaceVisibility = Schemas["SpaceVisibility"];
|
|
export type Space = Schemas["Space"];
|
|
export type SpaceMember = Schemas["SpaceMember"];
|
|
export type PageNode = Schemas["PageNode"];
|
|
export type PageRef = Schemas["PageRef"];
|
|
export type Page = Schemas["Page"];
|
|
export type TrashedPage = Schemas["TrashedPage"];
|
|
export type ArchivedPage = Schemas["ArchivedPage"];
|
|
export type PinnedPage = Schemas["PinnedPage"];
|
|
export type PageFont = Schemas["PageFont"];
|
|
export type PageMode = Schemas["PageMode"];
|
|
export type LinkPreview = Schemas["LinkPreview"];
|
|
export type PageContent = Schemas["PageContent"];
|
|
export type PageVersion = Schemas["PageVersion"];
|
|
export type PublicSettings = Schemas["PublicSettings"];
|
|
export type InstanceSettings = Schemas["InstanceSettings"];
|
|
export type InstanceSettingsUpdate = Schemas["InstanceSettingsUpdate"];
|
|
export type Invite = Schemas["Invite"];
|
|
export type Group = Schemas["Group"];
|
|
export type PageItem = Schemas["PageItem"];
|
|
export type Attachment = Schemas["Attachment"];
|
|
export type SearchHit = Schemas["SearchHit"];
|
|
export type ShareLink = Schemas["ShareLink"];
|
|
export type Comment = Schemas["Comment"];
|
|
export type AdminStats = Schemas["AdminStats"];
|
|
export type AdminHealth = Schemas["AdminHealth"];
|
|
export type Job = Schemas["Job"];
|
|
export type Backup = Schemas["Backup"];
|
|
export type SharedPage = Schemas["SharedPage"];
|
|
export type PageGrantRole = Schemas["PageGrantRole"];
|
|
export type Reaction = Schemas["Reaction"];
|
|
export type Template = Schemas["Template"];
|
|
export type OAuthStart = Schemas["OAuthStart"];
|
|
export type TotpStatus = Schemas["TotpStatus"];
|
|
export type TotpSetup = Schemas["TotpSetup"];
|
|
export type ApiToken = Schemas["ApiToken"];
|
|
export type NewApiToken = Schemas["NewApiToken"];
|
|
export type AuditEntry = Schemas["AuditEntry"];
|
|
export type AuditPage = Schemas["AuditPage"];
|
|
export type Webhook = Schemas["Webhook"];
|
|
export type WebhookInput = Schemas["WebhookInput"];
|
|
export type WebhookEvent = Schemas["WebhookEvent"];
|
|
export type WebhookDelivery = Schemas["WebhookDelivery"];
|
|
export type OAuthProviderSettings = Schemas["OAuthProviderSettings"];
|
|
export type WatchState = Schemas["WatchState"];
|
|
export type NotificationType = Schemas["NotificationType"];
|
|
export type Notification = Schemas["Notification"];
|
|
export type NotificationList = Schemas["NotificationList"];
|
|
export type NotificationSettings = Schemas["NotificationSettings"];
|
|
export type PageGrant = Schemas["PageGrant"];
|
|
export type PageInvite = Schemas["PageInvite"];
|
|
export type PageAccess = Schemas["PageAccess"];
|
|
export type SharePageResult = Schemas["SharePageResult"];
|
|
export type SearchResult = Schemas["SearchResult"];
|
|
export type GroupRequest = Schemas["GroupRequest"];
|
|
export type SpaceGroup = Schemas["SpaceGroup"];
|
|
export type MemberUser = Schemas["MemberUser"];
|
|
export type InviteInfo = Schemas["InviteInfo"];
|
|
export type CreateInviteRequest = Schemas["CreateInviteRequest"];
|
|
export type PageUser = Schemas["PageUser"];
|
|
export type PropertyType = Schemas["PropertyType"];
|
|
export type LabelColor = Schemas["LabelColor"];
|
|
export type PropertyOption = Schemas["PropertyOption"];
|
|
export type PropertyVisibility = Schemas["PropertyVisibility"];
|
|
export type Property = Schemas["Property"];
|
|
export type PropertyInput = Schemas["PropertyInput"];
|
|
export type Tag = Schemas["Tag"];
|
|
export type TagInput = Schemas["TagInput"];
|
|
export type DocRule = Schemas["DocRule"];
|
|
export type DocFilter = Schemas["DocFilter"];
|
|
export type DocItem = Schemas["DocItem"];
|
|
export type DocList = Schemas["DocList"];
|
|
export type Collection = Schemas["Collection"];
|
|
export type CollectionInput = Schemas["CollectionInput"];
|
|
export type JournalDay = Schemas["JournalDay"];
|
|
export type JournalInfo = Schemas["JournalInfo"];
|
|
export type CreateSpaceRequest = { name: string; description?: string; icon?: string; visibility?: SpaceVisibility };
|
|
export type UpdateSpaceRequest = Partial<Pick<Space, "name" | "description" | "icon" | "visibility" | "defaultRole">>;
|
|
|
|
/** Admins manage their own organization; superadmins manage everything. */
|
|
export function isManager(user: Pick<User, "role"> | null | undefined): boolean {
|
|
return user?.role === "admin" || user?.role === "superadmin";
|
|
}
|
|
|
|
export class ApiError extends Error {
|
|
/** Machine-readable code from the server, e.g. "invalid_credentials". */
|
|
readonly code: string;
|
|
/** Human-readable explanation from the server, when it sent one. */
|
|
readonly serverMessage: string;
|
|
readonly fields: Record<string, string>;
|
|
readonly mfaId?: string;
|
|
/** With "totp_required": send it to auth.verifyTotp with a code. */
|
|
readonly challenge?: string;
|
|
|
|
constructor(
|
|
public readonly status: number,
|
|
public readonly body: unknown,
|
|
) {
|
|
const err = (typeof body === "object" && body !== null ? body : {}) as Partial<ErrorBody>;
|
|
super(`Docwell API error ${status}${err.error ? `: ${err.error}` : ""}`);
|
|
this.code = err.error ?? "unknown";
|
|
this.serverMessage = err.message ?? "";
|
|
this.fields = err.fields ?? {};
|
|
this.mfaId = err.mfaId;
|
|
this.challenge = err.challenge;
|
|
}
|
|
}
|
|
|
|
export interface ClientOptions {
|
|
/** Base URL of docwell-server, or "" for same-origin. */
|
|
baseUrl: string;
|
|
/** Returns the current session token, if any. */
|
|
token?: () => string | null | undefined;
|
|
/** Called when the server rejects the token (401 on an authenticated call). */
|
|
onUnauthorized?: () => void;
|
|
fetch?: typeof fetch;
|
|
}
|
|
|
|
export function createClient(opts: ClientOptions) {
|
|
const base = opts.baseUrl.replace(/\/+$/, "");
|
|
const doFetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
|
|
|
|
async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
|
|
const headers: Record<string, string> = { Accept: "application/json" };
|
|
const token = opts.token?.();
|
|
if (token) headers.Authorization = `Bearer ${token}`;
|
|
if (body !== undefined) headers["Content-Type"] = "application/json";
|
|
|
|
const res = await doFetch(base + path, {
|
|
method,
|
|
headers,
|
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
});
|
|
const data = res.headers.get("content-type")?.includes("application/json") ? await res.json() : await res.text();
|
|
if (!res.ok) {
|
|
const err = new ApiError(res.status, data);
|
|
if (res.status === 401 && token && err.code === "unauthorized") opts.onUnauthorized?.();
|
|
throw err;
|
|
}
|
|
return data as T;
|
|
}
|
|
|
|
const post = <T = void>(path: string, body?: unknown) => request<T>("POST", path, body ?? {});
|
|
|
|
/** Fetches a file with the session token; the name comes from Content-Disposition. */
|
|
async function download(path: string): Promise<{ blob: Blob; filename: string }> {
|
|
const headers: Record<string, string> = {};
|
|
const token = opts.token?.();
|
|
if (token) headers.Authorization = `Bearer ${token}`;
|
|
const res = await doFetch(base + path, { headers });
|
|
if (!res.ok) {
|
|
const data = res.headers.get("content-type")?.includes("application/json") ? await res.json() : await res.text();
|
|
throw new ApiError(res.status, data);
|
|
}
|
|
const cd = res.headers.get("content-disposition") ?? "";
|
|
const m = /filename\*=UTF-8''([^;]+)/i.exec(cd) ?? /filename="?([^";]+)"?/i.exec(cd);
|
|
return { blob: await res.blob(), filename: m ? decodeURIComponent(m[1]!) : "download" };
|
|
}
|
|
|
|
/** Sends a multipart form; the browser sets the boundary header itself. */
|
|
async function upload<T>(path: string, form: FormData): Promise<T> {
|
|
const headers: Record<string, string> = { Accept: "application/json" };
|
|
const token = opts.token?.();
|
|
if (token) headers.Authorization = `Bearer ${token}`;
|
|
const res = await doFetch(base + path, { method: "POST", headers, body: form });
|
|
const data = res.headers.get("content-type")?.includes("application/json") ? await res.json() : await res.text();
|
|
if (!res.ok) {
|
|
const err = new ApiError(res.status, data);
|
|
if (res.status === 401 && token && err.code === "unauthorized") opts.onUnauthorized?.();
|
|
throw err;
|
|
}
|
|
return data as T;
|
|
}
|
|
|
|
return {
|
|
request,
|
|
version: () => request<Version>("GET", "/api/v1/version"),
|
|
readiness: () => request<Status>("GET", "/readyz"),
|
|
|
|
auth: {
|
|
methods: () => request<AuthMethods>("GET", "/api/v1/auth/methods"),
|
|
signup: (input: SignupRequest) => post<Session>("/api/v1/auth/signup", input),
|
|
login: (email: string, password: string, mfaId?: string) =>
|
|
post<Session>("/api/v1/auth/login", { email, password, mfaId }),
|
|
requestOtp: (email: string) => post<{ otpId: string }>("/api/v1/auth/otp/request", { email }),
|
|
loginWithOtp: (otpId: string, code: string, mfaId?: string) =>
|
|
post<Session>("/api/v1/auth/otp/login", { otpId, code, mfaId }),
|
|
refresh: () => request<Session>("POST", "/api/v1/auth/refresh"),
|
|
me: () => request<User>("GET", "/api/v1/auth/me"),
|
|
requestPasswordReset: (email: string) => post("/api/v1/auth/password-reset/request", { email }),
|
|
confirmPasswordReset: (token: string, password: string) =>
|
|
post("/api/v1/auth/password-reset/confirm", { token, password }),
|
|
requestVerification: (email: string) => post("/api/v1/auth/verification/request", { email }),
|
|
confirmVerification: (token: string) => post("/api/v1/auth/verification/confirm", { token }),
|
|
inviteInfo: (token: string) => request<InviteInfo>("GET", `/api/v1/auth/invites/${encodeURIComponent(token)}`),
|
|
/** Signed out: name and password create the account. Signed in: attaches the current account. */
|
|
acceptInvite: (token: string, name?: string, password?: string) =>
|
|
post<Session>("/api/v1/auth/invites/accept", { token, name, password }),
|
|
/** Second step of sign-in, after an ApiError with code "totp_required". */
|
|
verifyTotp: (challenge: string, code: string) => post<Session>("/api/v1/auth/totp/verify", { challenge, code }),
|
|
startOAuth: (provider: string, redirect: string) =>
|
|
post<OAuthStart>("/api/v1/auth/oauth2/start", { provider, redirect }),
|
|
finishOAuth: (state: string, code: string) => post<Session>("/api/v1/auth/oauth2/finish", { state, code }),
|
|
},
|
|
|
|
/** The signed-in account's own security settings (not usable with API tokens). */
|
|
me: {
|
|
totp: () => request<TotpStatus>("GET", "/api/v1/me/totp"),
|
|
setupTotp: () => post<TotpSetup>("/api/v1/me/totp/setup"),
|
|
enableTotp: (code: string) => post<{ recoveryCodes: string[] }>("/api/v1/me/totp/enable", { code }),
|
|
disableTotp: (code: string) => post<void>("/api/v1/me/totp/disable", { code }),
|
|
tokens: () => request<ApiToken[]>("GET", "/api/v1/me/tokens"),
|
|
createToken: (input: { name: string; scope: "read" | "write"; expiresDays?: number }) =>
|
|
post<NewApiToken>("/api/v1/me/tokens", input),
|
|
revokeToken: (id: string) => request<void>("DELETE", `/api/v1/me/tokens/${encodeURIComponent(id)}`),
|
|
},
|
|
|
|
webhooks: {
|
|
list: (workspace: string) =>
|
|
request<Webhook[]>("GET", `/api/v1/workspaces/${encodeURIComponent(workspace)}/webhooks`),
|
|
create: (workspace: string, input: WebhookInput) =>
|
|
post<Webhook>(`/api/v1/workspaces/${encodeURIComponent(workspace)}/webhooks`, input),
|
|
update: (id: string, input: WebhookInput) =>
|
|
request<Webhook>("PATCH", `/api/v1/webhooks/${encodeURIComponent(id)}`, input),
|
|
remove: (id: string) => request<void>("DELETE", `/api/v1/webhooks/${encodeURIComponent(id)}`),
|
|
deliveries: (id: string) =>
|
|
request<WebhookDelivery[]>("GET", `/api/v1/webhooks/${encodeURIComponent(id)}/deliveries`),
|
|
test: (id: string) => post<WebhookDelivery>(`/api/v1/webhooks/${encodeURIComponent(id)}/test`),
|
|
},
|
|
|
|
comments: {
|
|
update: (id: string, body: string) =>
|
|
request<Comment>("PATCH", `/api/v1/comments/${encodeURIComponent(id)}`, { body }),
|
|
remove: (id: string) => request<void>("DELETE", `/api/v1/comments/${encodeURIComponent(id)}`),
|
|
resolve: (id: string, resolved: boolean) =>
|
|
post<Comment>(`/api/v1/comments/${encodeURIComponent(id)}/resolve`, { resolved }),
|
|
react: (id: string, emoji: string, on: boolean) =>
|
|
post<Comment>(`/api/v1/comments/${encodeURIComponent(id)}/reactions`, { emoji, on }),
|
|
},
|
|
|
|
notifications: {
|
|
list: (opts: { unread?: boolean; limit?: number } = {}) =>
|
|
request<NotificationList>(
|
|
"GET",
|
|
`/api/v1/notifications${query({ unread: opts.unread ? "true" : undefined, limit: opts.limit?.toString() })}`,
|
|
),
|
|
/** Marks the listed notifications read, or all of them; resolves to the unread count. */
|
|
markRead: (input: { ids?: string[]; all?: boolean }) =>
|
|
post<{ unread: number }>("/api/v1/notifications/read", input),
|
|
settings: () => request<NotificationSettings>("GET", "/api/v1/notifications/settings"),
|
|
setSettings: (input: NotificationSettings) =>
|
|
request<NotificationSettings>("PUT", "/api/v1/notifications/settings", input),
|
|
},
|
|
|
|
files: {
|
|
/** A short-lived token for ?token= on file URLs (img tags cannot send headers). */
|
|
token: () => post<{ token: string; expires: string }>("/api/v1/files/token"),
|
|
removeAttachment: (id: string) => request<void>("DELETE", `/api/v1/attachments/${encodeURIComponent(id)}`),
|
|
},
|
|
|
|
/** Reading pages through a public link (no session needed). */
|
|
share: {
|
|
get: (token: string, page?: string) =>
|
|
request<SharedPage>(
|
|
"GET",
|
|
`/api/v1/share/${encodeURIComponent(token)}${page ? `/pages/${encodeURIComponent(page)}` : ""}`,
|
|
),
|
|
},
|
|
|
|
invites: {
|
|
list: (params: { workspace?: string; organization?: string } = {}) =>
|
|
request<Invite[]>("GET", `/api/v1/invites${query(params)}`),
|
|
create: (input: CreateInviteRequest) => post<Invite>("/api/v1/invites", input),
|
|
revoke: (id: string) => request<void>("DELETE", `/api/v1/invites/${encodeURIComponent(id)}`),
|
|
resend: (id: string) => post<Invite>(`/api/v1/invites/${encodeURIComponent(id)}/resend`),
|
|
},
|
|
|
|
settings: {
|
|
public: () => request<PublicSettings>("GET", "/api/v1/settings/public"),
|
|
get: () => request<InstanceSettings>("GET", "/api/v1/admin/settings"),
|
|
update: (patch: InstanceSettingsUpdate) => request<InstanceSettings>("PATCH", "/api/v1/admin/settings", patch),
|
|
testEmail: (to: string) => post("/api/v1/admin/settings/test-email", { to }),
|
|
testStorage: () => post("/api/v1/admin/settings/test-storage"),
|
|
},
|
|
|
|
/** Instance administration (the admin panel). */
|
|
admin: {
|
|
stats: () => request<AdminStats>("GET", "/api/v1/admin/stats"),
|
|
health: () => request<AdminHealth>("GET", "/api/v1/admin/health"),
|
|
jobs: () => request<Job[]>("GET", "/api/v1/admin/jobs"),
|
|
runJob: (name: string) => post(`/api/v1/admin/jobs/${encodeURIComponent(name)}/run`),
|
|
backups: () => request<Backup[]>("GET", "/api/v1/admin/backups"),
|
|
createBackup: () => post("/api/v1/admin/backups"),
|
|
deleteBackup: (key: string) => request<void>("DELETE", `/api/v1/admin/backups/${encodeURIComponent(key)}`),
|
|
downloadBackup: (key: string) => download(`/api/v1/admin/backups/${encodeURIComponent(key)}`),
|
|
audit: (params: { q?: string; since?: string; until?: string; page?: number; perPage?: number } = {}) =>
|
|
request<AuditPage>("GET", `/api/v1/admin/audit${query(params)}`),
|
|
exportAudit: (params: { q?: string; since?: string; until?: string } = {}) =>
|
|
download(`/api/v1/admin/audit/export${query(params)}`),
|
|
tokens: () => request<ApiToken[]>("GET", "/api/v1/admin/tokens"),
|
|
revokeToken: (id: string) => request<void>("DELETE", `/api/v1/admin/tokens/${encodeURIComponent(id)}`),
|
|
},
|
|
|
|
users: {
|
|
list: (params: { page?: number; perPage?: number; q?: string; organization?: string } = {}) =>
|
|
request<UserList>("GET", `/api/v1/users${query(params)}`),
|
|
create: (input: CreateUserRequest) => post<User>("/api/v1/users", input),
|
|
/** Turns off someone's two-step sign-in (their manager). */
|
|
resetTotp: (id: string) => request<void>("DELETE", `/api/v1/users/${encodeURIComponent(id)}/totp`),
|
|
update: (id: string, patch: UpdateUserRequest) =>
|
|
request<User>("PATCH", `/api/v1/users/${encodeURIComponent(id)}`, patch),
|
|
remove: (id: string) => request<void>("DELETE", `/api/v1/users/${encodeURIComponent(id)}`),
|
|
sendPasswordReset: (id: string) => post(`/api/v1/users/${encodeURIComponent(id)}/password-reset`),
|
|
},
|
|
|
|
orgs: {
|
|
list: () => request<Organization[]>("GET", "/api/v1/orgs"),
|
|
create: (name: string) => post<Organization>("/api/v1/orgs", { name }),
|
|
rename: (id: string, name: string) =>
|
|
request<Organization>("PATCH", `/api/v1/orgs/${encodeURIComponent(id)}`, { name }),
|
|
remove: (id: string) => request<void>("DELETE", `/api/v1/orgs/${encodeURIComponent(id)}`),
|
|
},
|
|
|
|
workspaces: {
|
|
list: () => request<Workspace[]>("GET", "/api/v1/workspaces"),
|
|
create: (name: string, organization?: string) => post<Workspace>("/api/v1/workspaces", { name, organization }),
|
|
rename: (id: string, name: string) =>
|
|
request<Workspace>("PATCH", `/api/v1/workspaces/${encodeURIComponent(id)}`, { name }),
|
|
/** Changes how the workspace's new pages open: as text or as a canvas. */
|
|
setDefaultPageMode: (id: string, defaultPageMode: PageMode) =>
|
|
request<Workspace>("PATCH", `/api/v1/workspaces/${encodeURIComponent(id)}`, { defaultPageMode }),
|
|
remove: (id: string) => request<void>("DELETE", `/api/v1/workspaces/${encodeURIComponent(id)}`),
|
|
members: (id: string) =>
|
|
request<WorkspaceMember[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/members`),
|
|
setMember: (id: string, email: string, role: WorkspaceRole) =>
|
|
request<WorkspaceMember>("PUT", `/api/v1/workspaces/${encodeURIComponent(id)}/members`, { email, role }),
|
|
removeMember: (id: string, userId: string) =>
|
|
request<void>("DELETE", `/api/v1/workspaces/${encodeURIComponent(id)}/members/${encodeURIComponent(userId)}`),
|
|
spaces: (id: string) => request<Space[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/spaces`),
|
|
createSpace: (id: string, input: CreateSpaceRequest) =>
|
|
post<Space>(`/api/v1/workspaces/${encodeURIComponent(id)}/spaces`, input),
|
|
groups: (id: string) => request<Group[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/groups`),
|
|
people: (id: string, q: string, limit?: number) =>
|
|
request<MemberUser[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/people${query({ q, limit })}`),
|
|
search: (id: string, q: string, limit?: number, filter: SearchFilter = {}) =>
|
|
request<SearchResult>(
|
|
"GET",
|
|
`/api/v1/workspaces/${encodeURIComponent(id)}/search${query({ q, limit, ...filter })}`,
|
|
),
|
|
favorites: (id: string) => request<PageItem[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/favorites`),
|
|
templates: (id: string) => request<Template[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/templates`),
|
|
recent: (id: string, limit?: number) =>
|
|
request<PageItem[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/recent${query({ limit })}`),
|
|
createGroup: (id: string, input: GroupRequest) =>
|
|
post<Group>(`/api/v1/workspaces/${encodeURIComponent(id)}/groups`, input),
|
|
properties: (id: string) => request<Property[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/properties`),
|
|
createProperty: (id: string, input: PropertyInput) =>
|
|
post<Property>(`/api/v1/workspaces/${encodeURIComponent(id)}/properties`, input),
|
|
tags: (id: string) => request<Tag[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/tags`),
|
|
createTag: (id: string, input: TagInput) => post<Tag>(`/api/v1/workspaces/${encodeURIComponent(id)}/tags`, input),
|
|
/** All docs: the pages the caller can open, narrowed by the query. */
|
|
docs: (id: string, q: { space?: string; tag?: string; collection?: string; filter?: DocFilter } = {}) =>
|
|
request<DocList>(
|
|
"GET",
|
|
`/api/v1/workspaces/${encodeURIComponent(id)}/docs${query({
|
|
space: q.space,
|
|
tag: q.tag,
|
|
collection: q.collection,
|
|
filter: q.filter?.rules.length ? JSON.stringify(q.filter) : undefined,
|
|
})}`,
|
|
),
|
|
collections: (id: string) =>
|
|
request<Collection[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/collections`),
|
|
createCollection: (id: string, input: CollectionInput) =>
|
|
post<Collection>(`/api/v1/workspaces/${encodeURIComponent(id)}/collections`, input),
|
|
/** The caller's journal days from from to to (YYYY-MM-DD). */
|
|
journal: (id: string, from: string, to: string) =>
|
|
request<JournalInfo>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/journals${query({ from, to })}`),
|
|
setJournalTemplate: (id: string, template: string) =>
|
|
request<JournalInfo>("PATCH", `/api/v1/workspaces/${encodeURIComponent(id)}/journals`, { template }),
|
|
/** The caller's journal page for a day, made if there is none yet. */
|
|
openJournal: (id: string, date: string, title?: string) =>
|
|
request<Page>(
|
|
"PUT",
|
|
`/api/v1/workspaces/${encodeURIComponent(id)}/journals/${encodeURIComponent(date)}`,
|
|
title ? { title } : {},
|
|
),
|
|
},
|
|
|
|
properties: {
|
|
update: (id: string, patch: PropertyInput) =>
|
|
request<Property>("PATCH", `/api/v1/properties/${encodeURIComponent(id)}`, patch),
|
|
remove: (id: string) => request<void>("DELETE", `/api/v1/properties/${encodeURIComponent(id)}`),
|
|
},
|
|
|
|
tags: {
|
|
update: (id: string, patch: TagInput) => request<Tag>("PATCH", `/api/v1/tags/${encodeURIComponent(id)}`, patch),
|
|
remove: (id: string) => request<void>("DELETE", `/api/v1/tags/${encodeURIComponent(id)}`),
|
|
/** Moves every page of tag id to into, then deletes id. */
|
|
merge: (id: string, into: string) => post<Tag>(`/api/v1/tags/${encodeURIComponent(id)}/merge`, { into }),
|
|
},
|
|
|
|
collections: {
|
|
update: (id: string, patch: CollectionInput) =>
|
|
request<Collection>("PATCH", `/api/v1/collections/${encodeURIComponent(id)}`, patch),
|
|
remove: (id: string) => request<void>("DELETE", `/api/v1/collections/${encodeURIComponent(id)}`),
|
|
setPage: (id: string, page: string, on: boolean) =>
|
|
request<Collection>(
|
|
on ? "PUT" : "DELETE",
|
|
`/api/v1/collections/${encodeURIComponent(id)}/pages/${encodeURIComponent(page)}`,
|
|
),
|
|
},
|
|
|
|
groups: {
|
|
update: (id: string, patch: GroupRequest) =>
|
|
request<Group>("PATCH", `/api/v1/groups/${encodeURIComponent(id)}`, patch),
|
|
remove: (id: string) => request<void>("DELETE", `/api/v1/groups/${encodeURIComponent(id)}`),
|
|
members: (id: string) => request<MemberUser[]>("GET", `/api/v1/groups/${encodeURIComponent(id)}/members`),
|
|
addMember: (id: string, email: string) =>
|
|
request<MemberUser>("PUT", `/api/v1/groups/${encodeURIComponent(id)}/members`, { email }),
|
|
removeMember: (id: string, userId: string) =>
|
|
request<void>("DELETE", `/api/v1/groups/${encodeURIComponent(id)}/members/${encodeURIComponent(userId)}`),
|
|
},
|
|
|
|
spaces: {
|
|
get: (id: string) => request<Space>("GET", `/api/v1/spaces/${encodeURIComponent(id)}`),
|
|
update: (id: string, patch: UpdateSpaceRequest) =>
|
|
request<Space>("PATCH", `/api/v1/spaces/${encodeURIComponent(id)}`, patch),
|
|
remove: (id: string) => request<void>("DELETE", `/api/v1/spaces/${encodeURIComponent(id)}`),
|
|
members: (id: string) => request<SpaceMember[]>("GET", `/api/v1/spaces/${encodeURIComponent(id)}/members`),
|
|
setMember: (id: string, email: string, role: SpaceRole) =>
|
|
request<SpaceMember>("PUT", `/api/v1/spaces/${encodeURIComponent(id)}/members`, { email, role }),
|
|
removeMember: (id: string, userId: string) =>
|
|
request<void>("DELETE", `/api/v1/spaces/${encodeURIComponent(id)}/members/${encodeURIComponent(userId)}`),
|
|
groups: (id: string) => request<SpaceGroup[]>("GET", `/api/v1/spaces/${encodeURIComponent(id)}/groups`),
|
|
setGroup: (id: string, group: string, role: SpaceRole) =>
|
|
request<SpaceGroup>("PUT", `/api/v1/spaces/${encodeURIComponent(id)}/groups`, { group, role }),
|
|
removeGroup: (id: string, groupId: string) =>
|
|
request<void>("DELETE", `/api/v1/spaces/${encodeURIComponent(id)}/groups/${encodeURIComponent(groupId)}`),
|
|
pages: (id: string) => request<PageNode[]>("GET", `/api/v1/spaces/${encodeURIComponent(id)}/pages`),
|
|
createPage: (id: string, input: { parent?: string; title?: string; index?: number } = {}) =>
|
|
post<Page>(`/api/v1/spaces/${encodeURIComponent(id)}/pages`, input),
|
|
trash: (id: string) => request<TrashedPage[]>("GET", `/api/v1/spaces/${encodeURIComponent(id)}/trash`),
|
|
archive: (id: string) => request<ArchivedPage[]>("GET", `/api/v1/spaces/${encodeURIComponent(id)}/archive`),
|
|
pinned: (id: string) => request<PinnedPage[]>("GET", `/api/v1/spaces/${encodeURIComponent(id)}/pinned`),
|
|
/** The whole space as a zip of Markdown or HTML files. */
|
|
export: (id: string, format: "markdown" | "html") =>
|
|
download(`/api/v1/spaces/${encodeURIComponent(id)}/export${query({ format })}`),
|
|
/** Creates a page per Markdown or HTML file, under parent ("" = top level). */
|
|
import: (id: string, files: File[], parent = "") => {
|
|
const form = new FormData();
|
|
for (const f of files) form.append("file", f, f.name);
|
|
if (parent) form.append("parent", parent);
|
|
return upload<Page[]>(`/api/v1/spaces/${encodeURIComponent(id)}/import`, form);
|
|
},
|
|
},
|
|
|
|
pages: {
|
|
get: (id: string) => request<Page>("GET", `/api/v1/pages/${encodeURIComponent(id)}`),
|
|
update: (
|
|
id: string,
|
|
patch: {
|
|
title?: string;
|
|
icon?: string;
|
|
isTemplate?: boolean;
|
|
fullWidth?: boolean;
|
|
font?: PageFont;
|
|
defaultMode?: PageMode;
|
|
tags?: string[];
|
|
/** Property values by property id; null clears one. */
|
|
properties?: Record<string, unknown>;
|
|
},
|
|
) => request<Page>("PATCH", `/api/v1/pages/${encodeURIComponent(id)}`, patch),
|
|
/** Moves a page under parent ("" = top level) at index among its other children. */
|
|
content: (id: string) => request<PageContent>("GET", `/api/v1/pages/${encodeURIComponent(id)}/content`),
|
|
/** Replaces the page's document; content is Tiptap JSON with type "doc". */
|
|
saveContent: (id: string, content: Record<string, unknown>) =>
|
|
request<PageContent>("PUT", `/api/v1/pages/${encodeURIComponent(id)}/content`, { content }),
|
|
versions: (id: string) => request<PageVersion[]>("GET", `/api/v1/pages/${encodeURIComponent(id)}/versions`),
|
|
version: (id: string, versionId: string) =>
|
|
request<PageContent>(
|
|
"GET",
|
|
`/api/v1/pages/${encodeURIComponent(id)}/versions/${encodeURIComponent(versionId)}`,
|
|
),
|
|
restoreVersion: (id: string, versionId: string) =>
|
|
post<PageContent>(`/api/v1/pages/${encodeURIComponent(id)}/versions/${encodeURIComponent(versionId)}/restore`),
|
|
move: (id: string, parent: string, index: number) =>
|
|
post<Page>(`/api/v1/pages/${encodeURIComponent(id)}/move`, { parent, index }),
|
|
trash: (id: string) => request<void>("DELETE", `/api/v1/pages/${encodeURIComponent(id)}`),
|
|
restore: (id: string) => post<Page>(`/api/v1/pages/${encodeURIComponent(id)}/restore`),
|
|
archive: (id: string) => post<Page>(`/api/v1/pages/${encodeURIComponent(id)}/archive`),
|
|
unarchive: (id: string) => post<Page>(`/api/v1/pages/${encodeURIComponent(id)}/unarchive`),
|
|
pin: (id: string) => request<Page>("PUT", `/api/v1/pages/${encodeURIComponent(id)}/pin`),
|
|
unpin: (id: string) => request<Page>("DELETE", `/api/v1/pages/${encodeURIComponent(id)}/pin`),
|
|
/** A web page's title, description and picture, read by docwell-server. */
|
|
preview: (url: string) => request<LinkPreview>("GET", `/api/v1/link-preview${query({ url })}`),
|
|
setFavorite: (id: string, on: boolean) =>
|
|
request<void>(on ? "PUT" : "DELETE", `/api/v1/pages/${encodeURIComponent(id)}/favorite`),
|
|
attachments: (id: string) => request<Attachment[]>("GET", `/api/v1/pages/${encodeURIComponent(id)}/attachments`),
|
|
upload: (id: string, file: Blob, name: string) => {
|
|
const form = new FormData();
|
|
form.append("file", file, name);
|
|
return upload<Attachment>(`/api/v1/pages/${encodeURIComponent(id)}/attachments`, form);
|
|
},
|
|
comments: (id: string) => request<Comment[]>("GET", `/api/v1/pages/${encodeURIComponent(id)}/comments`),
|
|
/** The pages the caller can open that link to this one. */
|
|
backlinks: (id: string) => request<PageItem[]>("GET", `/api/v1/pages/${encodeURIComponent(id)}/backlinks`),
|
|
/** Replaces the page's content with a template's. */
|
|
applyTemplate: (id: string, template: string) =>
|
|
post<Page>(`/api/v1/pages/${encodeURIComponent(id)}/apply-template`, { template }),
|
|
watch: (id: string) => request<WatchState>("GET", `/api/v1/pages/${encodeURIComponent(id)}/watch`),
|
|
setWatch: (id: string, watching: boolean) =>
|
|
request<WatchState>("PUT", `/api/v1/pages/${encodeURIComponent(id)}/watch`, { watching }),
|
|
addComment: (
|
|
id: string,
|
|
input: {
|
|
body: string;
|
|
quote?: string;
|
|
anchor?: Record<string, unknown> | null;
|
|
parent?: string;
|
|
mentions?: string[];
|
|
},
|
|
) => post<Comment>(`/api/v1/pages/${encodeURIComponent(id)}/comments`, input),
|
|
/** The public link; rejects with a 404 ApiError when sharing is off. */
|
|
shareLink: (id: string) => request<ShareLink>("GET", `/api/v1/pages/${encodeURIComponent(id)}/share`),
|
|
setShareLink: (id: string, includeSubpages: boolean) =>
|
|
request<ShareLink>("PUT", `/api/v1/pages/${encodeURIComponent(id)}/share`, { includeSubpages }),
|
|
deleteShareLink: (id: string) => request<void>("DELETE", `/api/v1/pages/${encodeURIComponent(id)}/share`),
|
|
/** Who has access beyond the space's members: grants and the restricted switch. */
|
|
access: (id: string) => request<PageAccess>("GET", `/api/v1/pages/${encodeURIComponent(id)}/access`),
|
|
setRestricted: (id: string, restricted: boolean) =>
|
|
request<PageAccess>("PATCH", `/api/v1/pages/${encodeURIComponent(id)}/access`, { restricted }),
|
|
/** Shares with someone by email; people outside the workspace are invited as guests. */
|
|
shareWithUser: (id: string, email: string, role: PageGrantRole) =>
|
|
request<SharePageResult>("PUT", `/api/v1/pages/${encodeURIComponent(id)}/access/users`, { email, role }),
|
|
unshareUser: (id: string, userId: string) =>
|
|
request<PageAccess>(
|
|
"DELETE",
|
|
`/api/v1/pages/${encodeURIComponent(id)}/access/users/${encodeURIComponent(userId)}`,
|
|
),
|
|
shareWithGroup: (id: string, groupId: string, role: PageGrantRole) =>
|
|
request<PageAccess>(
|
|
"PUT",
|
|
`/api/v1/pages/${encodeURIComponent(id)}/access/groups/${encodeURIComponent(groupId)}`,
|
|
{ role },
|
|
),
|
|
unshareGroup: (id: string, groupId: string) =>
|
|
request<PageAccess>(
|
|
"DELETE",
|
|
`/api/v1/pages/${encodeURIComponent(id)}/access/groups/${encodeURIComponent(groupId)}`,
|
|
),
|
|
export: (id: string, format: "markdown" | "html" | "pdf" | "docx") =>
|
|
download(`/api/v1/pages/${encodeURIComponent(id)}/export${query({ format })}`),
|
|
/** Records that the user opened the page, for their recent list. */
|
|
visit: (id: string) => post(`/api/v1/pages/${encodeURIComponent(id)}/visit`),
|
|
purge: (id: string) => request<void>("DELETE", `/api/v1/pages/${encodeURIComponent(id)}?permanent=true`),
|
|
},
|
|
};
|
|
}
|
|
|
|
/** Optional narrowing for workspaces.search; dates are RFC 3339 times or YYYY-MM-DD days. */
|
|
export type SearchFilter = {
|
|
space?: string;
|
|
tag?: string;
|
|
author?: string;
|
|
updatedAfter?: string;
|
|
updatedBefore?: string;
|
|
};
|
|
|
|
function query(params: Record<string, string | number | undefined>): string {
|
|
const qs = new URLSearchParams();
|
|
for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== "") qs.set(k, String(v));
|
|
const s = qs.toString();
|
|
return s ? `?${s}` : "";
|
|
}
|
|
|
|
export type DocwellClient = ReturnType<typeof createClient>;
|
|
|
|
/** Persists the session token; storage failures are ignored (private mode, webviews). */
|
|
export function createTokenStore(key = "docwell.token") {
|
|
let memory: string | null = null;
|
|
return {
|
|
get(): string | null {
|
|
try {
|
|
return localStorage.getItem(key) ?? memory;
|
|
} catch {
|
|
return memory;
|
|
}
|
|
},
|
|
set(token: string | null) {
|
|
memory = token;
|
|
try {
|
|
if (token) localStorage.setItem(key, token);
|
|
else localStorage.removeItem(key);
|
|
} catch {
|
|
// keep the in-memory copy only
|
|
}
|
|
},
|
|
};
|
|
}
|