diff --git a/connectors/github/src/assets.ts b/connectors/github/src/assets.ts index 3b00d8f3..79258175 100644 --- a/connectors/github/src/assets.ts +++ b/connectors/github/src/assets.ts @@ -147,7 +147,7 @@ function media(prefix: Uint8Array, declared: string | null): string { ? mime : "application/octet-stream"; } -/** Signed storage requests carry no API credentials, even across redirects. */ +// Signed storage requests carry no API credentials, even across redirects. export async function openAsset( value: string, signal: AbortSignal, diff --git a/connectors/github/src/definition.ts b/connectors/github/src/definition.ts index bae893e9..b9787e04 100644 --- a/connectors/github/src/definition.ts +++ b/connectors/github/src/definition.ts @@ -122,11 +122,8 @@ function appOf(values: { type Settings = Readonly>>; -/** The connector for the settings a run reads, which the kit builds again at - * the start of each run. With none, it is in its widest shape. */ export function connector(settings: Settings = {}) { - // A process that reads no stars holds no star field, so it never writes or - // puts back the marks another process sets on the rows it syncs. + // A process that reads no stars holds no star field, so it never puts back the marks another process sets. const starFields = settings.github_stars === false ? [] : ["starred", "starred_at"]; return defineConnector({ @@ -159,10 +156,7 @@ export function connector(settings: Settings = {}) { ], readOnly: [...starFields, "synced"], derived: [...starFields, "synced"], - // Nothing turns a synced row into a star-only one: a star-only write, - // or one process putting back what it last wrote, leaves `synced` - // alone, and a row another process has marked synced since this one - // agreed on it is not this one's to archive. + // A row another process has marked synced is not this one's to archive. policy: (item, entry, archiving) => item?.properties["synced"] !== true ? {} @@ -461,8 +455,7 @@ export function connector(settings: Settings = {}) { from_type_constraints: [issueType], to_type_constraints: [issueType], }, - // Retired (see `retired`): cleared on every row written with them, so one synced before - // holds only `about` and `comments-on`. + // Retired: cleared on every row written with them, so one synced before holds only `about` and `comments-on`. { id: references, cardinality: "many-to-many", diff --git a/connectors/github/src/discussion-write.ts b/connectors/github/src/discussion-write.ts index 5da07ba1..2d1b9448 100644 --- a/connectors/github/src/discussion-write.ts +++ b/connectors/github/src/discussion-write.ts @@ -64,7 +64,6 @@ const reasons = { duplicate: "DUPLICATE", } as const; -/** The reason a row asks to close for: one GitHub offers, or resolved. */ function closing(item: Item): (typeof reasons)[keyof typeof reasons] { const asked = text(item, "state_reason")?.toLowerCase(); return asked !== undefined && asked in reasons @@ -86,9 +85,7 @@ function commentAnswer(context: Context, comment: DiscussionComment): Entry { ); } -/** Asked of each installation the sync uses, with the token that reads - * Discussions. A node none of them shows is gone; where one refused the - * App Discussions, the node may be there, so the change waits. */ +// Where one installation refused the App Discussions, the node may be there, so the change waits. async function seekIn( context: Context, app: App, @@ -171,8 +168,6 @@ async function commentAt( }; } -/** A refusal of a Discussions write, as a refused change rather than a - * failed run. */ async function refused( error: unknown, place: Place, @@ -188,7 +183,6 @@ async function discussionsMadeSince( signal: AbortSignal, attempted: string, ): Promise<{ node_id: string; body: string; discussion: Discussion }[]> { - // GitHub takes no idempotency key: find what the first try made. const since = new Date(Date.parse(attempted) - margin).toISOString(); const bot = await botOf(app, signal); const listed = await listDiscussions( @@ -222,9 +216,6 @@ async function commentsMadeSince( type Handled = { entry: Entry | undefined } | undefined; -/** Which kind of thread a comment is in: where the row was placed, or for a - * row with no placement, which kind its node is. An issue comment goes on to - * the issue path unasked. */ async function threadIsDiscussion( change: Change, context: Context, @@ -242,8 +233,6 @@ async function threadIsDiscussion( return (await commentAt(context, app, item, node)) !== undefined; } -/** Whether what a comment comments on belongs to a discussion: a discussion, - * or a comment that GitHub holds in one. An issue's comment does not. */ async function inDiscussion( thread: Item, context: Context, @@ -256,8 +245,6 @@ async function inDiscussion( return (await commentAt(context, app, thread, node)) !== undefined; } -/** Carries a change to a discussion or to a comment on one; nothing for any - * other row, which the issue path carries. */ export async function carryDiscussions( change: Change, context: Context, @@ -421,8 +408,6 @@ async function createRow( return place(change, context, where, posted, false); } -/** Brings a discussion a create made to what the row says: a retry finds one - * made before the row changed, and a row can be made closed. */ async function place( change: Change, context: Context, @@ -521,8 +506,7 @@ async function createComment( change.connections?.[commentsOn]?.added[0] ?? change.placement?.[commentsOn]?.[0]; const hostNode = thread === undefined ? undefined : text(thread, "github_id"); - // A reply comments on its parent comment, so the discussion is the one - // GitHub holds that comment in. + // A reply comments on its parent comment, so the discussion is the one GitHub holds that comment in. const discussionNode = thread?.type === commentType && hostNode !== undefined ? (await commentAt(context, app, thread, hostNode))?.comment.discussion @@ -619,9 +603,6 @@ async function createComment( return commentAnswer(context, comment); } -/** Posts a comment again that is gone from GitHub, under the App's name only - * where the App wrote it. `undefined` where the row is not a discussion - * comment placed in a discussion. */ export async function remakeDiscussions( change: Change, context: Context, diff --git a/connectors/github/src/discussions.ts b/connectors/github/src/discussions.ts index 7849bdc9..da314741 100644 --- a/connectors/github/src/discussions.ts +++ b/connectors/github/src/discussions.ts @@ -16,8 +16,7 @@ import { import { batches, query, reads, type Client } from "./github.js"; import { loginOf } from "./graph.js"; -/** A comment cursor asked a little early, so a discussion GitHub shows late - * under an earlier time is still read; what comes again is unchanged. */ +// Asked a little early, so a discussion GitHub shows late under an earlier time is still read. const overlap = 5 * 60 * 1000; const discussionFields = ` @@ -36,9 +35,7 @@ const commentFields = ` const whereFields = "discussion { id repository { id nameWithOwner } }"; -/** The first page of a discussion's comments, and of each comment's replies, - * asked with the discussion itself so a read is one request where they fit. - * Less than GitHub allows keeps the query's cost down; the rest is paged. */ +// Asked with the discussion so a read is one request where they fit; fewer than GitHub allows keeps the query's cost down. const commentsFirst = 20; const repliesFirst = 10; const inlineComments = `comments(first: ${String(commentsFirst)}) { @@ -151,9 +148,6 @@ function advance( return cursor; } -/** Why GitHub will not show the App or token a repository's Discussions: the - * installation does not hold the permission, or its answer names the - * repository as unreadable. Anything else is no refusal and is thrown on. */ export class DiscussionsRefused extends Error { override name = "DiscussionsRefused"; } @@ -176,7 +170,6 @@ export function discussionsRefusal(error: unknown): string | undefined { interface Read { found: Discussion[]; - /** The first page of each one's comments, where they were asked for. */ first: Map>; } @@ -240,10 +233,6 @@ export async function discussionCommentsByNode( return found; } -/** Every top-level comment and reply of a discussion, parents before their - * replies; none where GitHub no longer shows the discussion. Where the first - * page of comments came with the discussion, it is read from there and only - * what lies beyond it is asked for. */ export async function commentsOf( octokit: Client, discussion: { node: string; repository: Repository }, @@ -301,9 +290,6 @@ export async function commentsOf( } } -/** A repository's discussions, newest change first, down to `since` where - * one is given, each with the first page of its comments. A repository - * with Discussions turned off lists none. */ export async function listDiscussions( octokit: Client, owner: string, @@ -355,8 +341,7 @@ export async function listDiscussions( } } -/** Whether a repository has Discussions turned on, asked with the token that - * reads them. False where GitHub does not show the repository to it. */ +// False where GitHub does not show the repository to the token. async function discussionsOn( octokit: Client, fullName: string, @@ -445,7 +430,7 @@ const mutations = { type Closing = "RESOLVED" | "OUTDATED" | "DUPLICATE"; -/** A create is never retried blind: one that landed would be made twice. */ +// A create is never retried blind: one that landed would be made twice. const once = { request: { retries: 0 } }; export async function createDiscussion( @@ -525,9 +510,7 @@ export async function updateDiscussionComment( return answered(answer.updateDiscussionComment.comment); } -/** GraphQL answers NOT_FOUND alike for a comment gone and for one it will - * not let the App touch, so it counts as gone only where the comment no - * longer reads in a repository that still does. */ +// GraphQL answers NOT_FOUND alike for a gone comment and one the App may not touch: gone only where the comment no longer reads in a repository that still does. export async function deleteDiscussionComment( octokit: Client, id: string, @@ -553,7 +536,6 @@ type Reading = Pick< "upsert" | "linked" | "linkedEach" | "archive" | "log" | "hints" >; -/** The links of the comments and replies Marfa holds under a discussion. */ async function heldComments( context: Pick, discussion: string, @@ -579,9 +561,7 @@ async function heldComments( return held; } -/** The discussions Marfa holds in a repository, each with the links of the - * comments and replies it holds under it. Rows written by this run have no - * connection yet, so this is read before anything is written. */ +// Read before anything is written: rows written by this run have no connection yet. export async function heldIn( context: Pick, node: string, @@ -625,8 +605,6 @@ async function write( ); } -/** The comments held under discussions that were read in full, which that - * read did not return, each with its discussion. */ function absentFrom( held: ReadonlyMap, comments: ReadonlyMap, @@ -640,9 +618,7 @@ function absentFrom( return absent; } -/** Those of these comments that a lookup by their own node does not find - * either. A comment that was deleted but has replies is returned, blank, and - * is not among them. */ +// A comment deleted but with replies is returned, blank, so is not among them. async function confirmedGone( octokit: Client, absent: readonly string[], @@ -661,13 +637,7 @@ async function missingComments( return confirmedGone(octokit, [...absentFrom(held, comments).keys()]); } -/** Reads a repository's discussions with every comment and reply, and writes - * them. Down to the saved time it lists only what changed; a first read and - * the daily check list them all, which also archives what GitHub no longer - * returns, a discussion or a comment, once a lookup by its own node agrees. - * An edit to a comment does not move its discussion's time, so only that - * full read and a delivery find the edit on a discussion otherwise quiet. - * Returns the time the next read lists down to. */ +// An edit to a comment does not move its discussion's time, so only the full read and a delivery find it. export async function syncDiscussions( context: Reading, octokit: Client, @@ -743,20 +713,6 @@ async function archiveGone( } } -/** The discussions a delivery named, read in full where GitHub shows them in - * a synced repository. Each one read in full also has archived the comments - * the delivery named that Marfa holds and it no longer returns, if a lookup - * by the comment's own node agrees. A discussion GitHub shows nowhere, with - * nothing deferred and its repository still reading, is archived if Marfa - * holds no comment under it; one that does is left to the daily check. - * Nothing is archived while the repository has Discussions turned off, nor - * once any lookup was refused: the discussion may be there, and the - * scheduled read says the refusal for the repository. - * - * Returns the discussions not shown yet because a limit deferred the look, - * and the comments the delivery named that this read dealt with: read in - * full, confirmed gone, or left on purpose to the daily check. A caller - * must not judge those as issue comments. */ export async function readNamedDiscussions( context: Reading, ids: ReadonlySet, @@ -778,9 +734,7 @@ export async function readNamedDiscussions( for (const link of links) if (named.has(link)) handled.add(link); }; const switches = new Map(); - // A repository is judged by what its discussions leave out only while - // GitHub says it has Discussions on; a repository it does not show is not - // proven on. + // A repository is judged by what its discussions leave out only while GitHub says it has Discussions on. const switchedOn = async ( octokit: Client, fullName: string, @@ -889,10 +843,7 @@ export async function readNamedDiscussions( if (discussionsRefusal(error) === undefined) throw error; continue; } - // A run for deliveries archives only what a delivery named, and a - // discussion's own delivery names none of its comments. Archiving the - // discussion alone would leave them out of the daily check's sight, so a - // discussion with any waits for that check, which archives both. + // A delivery archives only what it named and names none of a discussion's comments: a discussion with any waits for the daily check. await context.archive( discussionType, gone.filter((link) => (held.get(link) ?? []).length === 0), diff --git a/connectors/github/src/entries.ts b/connectors/github/src/entries.ts index 83d5d479..d3120784 100644 --- a/connectors/github/src/entries.ts +++ b/connectors/github/src/entries.ts @@ -1,15 +1,13 @@ import { createHash } from "node:crypto"; import type { Entry, Item, Target } from "@withmarfa/connector"; -/** What the App writes at the end of what a row makes, unseen on GitHub's - * page, so a later try finds what an earlier one made whatever changed. */ +// The App ends what a row makes with a mark unseen on GitHub's page, so a later try finds what an earlier one made. export function markOf(rowId: string): string { const digest = createHash("sha256").update(rowId).digest("hex"); return ``; } -/** Whether a body ends with the row's mark, as the App writes it: one - * quoted anywhere else names nothing. */ +// A mark quoted anywhere else names nothing. export function markedFor(body: string, rowId: string): boolean { return body.trimEnd().endsWith(markOf(rowId)); } @@ -23,7 +21,6 @@ function issueBody(body: string | null): string | null { return text === "" ? null : text; } -/** The GitHub node id a row is linked by. */ export function linkOf(row: Item): string | undefined { const value = row.properties["github_id"]; return typeof value === "string" ? value : undefined; @@ -44,8 +41,6 @@ export const githubCloses = "github.closes"; export const githubClosedBy = "github.closed-by"; export const commentsOn = "comments-on"; export const about = "about"; -/** Retired: the connector clears these on the rows it wrote with them, so a - * row synced before holds only its current edges. */ export const inThread = "in-thread"; export const references = "references"; @@ -60,8 +55,6 @@ export interface RestRepository { has_issues?: boolean; updated_at: string; default_branch?: string; - /** From the person's stars, which only a scheduled run with a token lists: - * absent where the stars were never listed. */ starred?: boolean; starred_at?: string | null; } @@ -101,7 +94,6 @@ export interface Discussion { body: string; url: string; open: boolean; - /** GitHub's `stateReason`, lowercase: resolved, outdated, duplicate or reopened. */ reason: string | null; answered: boolean; locked: boolean; @@ -112,14 +104,12 @@ export interface Discussion { repository: { node: string; name: string }; } -/** A comment or reply on a discussion; a reply names the comment it answers. */ export interface DiscussionComment { node: string; body: string; url: string; createdAt: string; updatedAt: string; - /** Set where GitHub deleted a comment it keeps for its replies. */ deleted: boolean; author: string | null; discussion: string; @@ -133,8 +123,6 @@ export interface Related { repository: { id: string }; } -/** The newest transfer on an issue's timeline, and the repository the issue - * came from, or null where the token cannot see that repository. */ export interface Transfer { from: { id: string; name: string } | null; } @@ -154,13 +142,11 @@ export interface Issue { labels: string[]; assignees: string[]; repository: { node: string; name: string }; - /** The newest transfer on the timeline, or null where it shows none. */ transfer: Transfer | null; } export interface Relations { - /** GitHub shows an App no issue in a private repository it is not - * installed on, so such a relation is not here at all. */ + // GitHub shows an App no issue in a private repository it is not installed on, so such a relation is absent. parent: Related | null; blockedBy: Related[]; relatesTo: Related[]; @@ -210,17 +196,13 @@ export function issueOfRest( }; } -/** The status word of an issue: `open` while open, `duplicate` when closed as - * a duplicate, `canceled` when closed as not planned, else `completed`. */ export function statusOf(open: boolean, reason: string | null): string { if (open) return "open"; if (reason === "duplicate") return "duplicate"; return reason === "not_planned" ? "canceled" : "completed"; } -/** `synced` says whether the repository is read for its issues and the rest, - * or kept only for a star, which is what lets a run that reads stars tell a - * row another process syncs from one it may archive. */ +// `synced` false keeps a repository only for its star, which lets a run that reads stars tell a row another process syncs from one it may archive. export function repositoryEntry( repository: RestRepository, synced: boolean, @@ -242,16 +224,9 @@ export function repositoryEntry( }; } -/** Identifies the pull request that closed an issue. `node` is present when - * the PR's repository is synced so a connection can be made; absent when - * only its address is known. */ export type ClosedByPR = { node: string; url: string } | { node?: undefined; url: string } | null; -/** `hidden` is the repository's visibility: named by every read and by the - * answers to writes where the last read recorded it. `closedByPR`, when - * given, sets the github.closed-by connection (synced PR) or closed_by_url - * (PR outside the synced set). */ export function issueEntry( issue: Issue, relations: Relations, @@ -325,17 +300,12 @@ export function issueEntry( } export interface CheckCounts { - /** Rollup state from GitHub's StatusCheckRollup. */ state: string; - /** Non-zero counts by CheckRunState. */ check_runs: Record; - /** Non-zero counts by StatusState. */ statuses: Record; } -/** A check run or a commit status on a pull request's head commit. */ export interface CheckRun { - /** GitHub's node id for it: the same check read again is the same row. */ id: string; name: string; kind: "check_run" | "status"; @@ -359,12 +329,8 @@ export interface PullRequest { baseBranch: string; headBranch: string; author: string | null; - /** Null when the commit has no checks, and undefined when GitHub refused - * them to the token, so nothing is known. */ + // `undefined` where GitHub refused the checks to the token: nothing is known and the table is left as it was. checks: CheckCounts | null | undefined; - /** The checks themselves, as the `check_runs` table holds them: empty when - * the commit has none, and undefined when GitHub refused them to the token, - * so the table is left as it was. */ checkRuns: CheckRun[] | undefined; createdAt: string; updatedAt: string; @@ -372,8 +338,6 @@ export interface PullRequest { closingIssues: { id: string; url: string; repository: { id: string } }[]; } -/** The status word of a pull request: its own state, with `draft` for an open - * draft. */ export function prStatusOf( prState: "open" | "closed" | "merged", draft: boolean, @@ -382,8 +346,7 @@ export function prStatusOf( return prState; } -/** A pull request whose check summary is known, as `withStoredChecks` makes - * it, so a write never clears a summary GitHub refused this run. */ +// Known, so a write never clears a summary GitHub refused this run. export type CheckedPullRequest = PullRequest & { checks: CheckCounts | null }; export function pullRequestEntry( @@ -494,9 +457,7 @@ export function discussionCommentEntry( occurred_at: comment.createdAt, changed_at: comment.updatedAt, connections: { - // A reply comments on the comment it answers, a top-level comment on the - // discussion: the edge is many-to-one, so a reply has no second link to - // the discussion. + // A reply comments on the comment it answers, so it has no second link to the discussion. [commentsOn]: [ comment.replyTo === null ? { type: discussionType, id: comment.discussion } diff --git a/connectors/github/src/files.ts b/connectors/github/src/files.ts index 13977c4e..fb77c064 100644 --- a/connectors/github/src/files.ts +++ b/connectors/github/src/files.ts @@ -154,7 +154,7 @@ function fileEntry( }, }; } -/** Ordinary entries must carry the last attachment accounting, not clear it. */ +// Ordinary entries must carry the last attachment accounting, not clear it. export async function fileNotes( context: Pick, type: string, @@ -295,9 +295,7 @@ async function keep( await opened.bytes.cancel().catch(() => undefined); } } -/** Discussions are outside the attachment import, and the issues token that - * reads these bodies may not ask for their comments. A discussion comment's - * address is the one thing its row holds that says so. */ +// Discussions are outside the attachment import: a discussion comment's address says so. function inDiscussion(row: Item): boolean { const url = row.properties["url"]; return ( @@ -312,7 +310,7 @@ export interface Repository { name: string; private: boolean; } -/** Only stable parent identities and safe outcomes survive a signed URL's lifetime. */ +// Only stable parent identities and safe outcomes survive a signed URL's lifetime. export async function preserveFiles( context: Context, client: Client, diff --git a/connectors/github/src/github.ts b/connectors/github/src/github.ts index 88dcf8d5..720348c5 100644 --- a/connectors/github/src/github.ts +++ b/connectors/github/src/github.ts @@ -17,8 +17,6 @@ export const apiVersion = "2026-03-10"; const Client = Octokit.plugin(paginateRest, throttling, retry); export type Client = InstanceType; -/** Where a client sends its requests, and the least time it leaves between - * two writes; absent, the throttling library's own spacing applies. */ export interface Origin { readonly base: string; readonly spacingMs?: number | undefined; @@ -39,8 +37,7 @@ export class PermissionRequired extends Error { const longestSpacing = 60_000; -/** Reads `github_request_spacing_ms`, which is for a stub of the API: against - * GitHub's own address a spacing below GitHub's minimum would be accepted. */ +// For a stub of the API: against GitHub's own address a spacing below its minimum would be accepted. export function spacingOf(values: { readonly github_request_spacing_ms?: number | undefined; readonly github_api_url?: string | undefined; @@ -65,8 +62,7 @@ let spaced: | { ms: number; write: Bottleneck.Group; notifications: Bottleneck.Group } | undefined; -// The throttle plugin spaces writes, GraphQL requests and the writes that -// notify someone by whole seconds, through limiters it shares across clients. +// The throttle plugin spaces writes, GraphQL requests and writes that notify someone by whole seconds, through limiters shared across clients. // A setting replaces them with limiters of its own, shared the same way. function spacing(ms: number | undefined) { if (ms === undefined) return {}; @@ -215,12 +211,7 @@ function counted(octokit: Client, key: string, guard: boolean): Client { return octokit; } -/** What an installation token is minted for: `list` reads only which - * repositories the installation holds; `read` reaches issues and pull - * requests, and `write` carries only issues and their comments. The two - * Discussions accesses and `contents`, which reads repository files, are - * separate so an installation that has not yet accepted one of those - * permissions still mints every other token. */ +// Discussions and contents are separate so an installation that has not accepted one still mints every other token. export type Access = "list" | "read" | "write" | "discussions" | "discussions-write" | "contents"; @@ -239,22 +230,15 @@ const permissions = { contents: { contents: "read", metadata: "read" }, } as const; -/** GitHub's cap on the repositories one token can name. */ +// GitHub's cap on the repositories one token can name. export const namedAtMost = 500; export interface Reach { readonly access: Access; - /** Past GitHub's cap, or absent, the token reaches every repository of - * the installation. */ readonly repositoryIds?: readonly number[]; - /** For a read token that only finds where a node sits: where GitHub - * refuses to name a repository, as one taken from the installation since - * it was recorded, the installation's whole reach instead. */ readonly orWhole?: boolean; } -/** How far apart this machine's clock and GitHub's may be before the - * connector stops signing rather than trust its correction. */ export const skewAtMost = 10 * 60; export class ClockSkew extends Error { @@ -267,9 +251,7 @@ export class ClockSkew extends Error { } interface Signer { - /** Installation tokens, kept for their hour across runs. */ readonly cache: TokenCache; - /** Seconds GitHub's clock runs ahead of ours, as its answers showed. */ skew: number; } @@ -296,8 +278,6 @@ class TokenCache { const signers = new Map(); -/** One per App and process, so what it learns of GitHub's clock and the - * tokens it mints are kept between runs. */ function signerOf(app: App): Signer { const key = `${app.base} ${app.appId}`; let signer = signers.get(key); @@ -308,7 +288,6 @@ function signerOf(app: App): Signer { return signer; } -/** Mints under the run's own signal, from the App's shared cache. */ function minterOf(app: App, signal: AbortSignal) { const signer = signerOf(app); return createAppAuth({ @@ -324,8 +303,7 @@ function adopt(signer: Signer, skew: number): void { signer.skew = skew; } -/** Signs with what GitHub's clock is known to say; `timeDifference` is the - * library's own reading of it, where its hook retried a refused JWT. */ +// `timeDifference` is the library's own reading of GitHub's clock, where its hook retried a refused JWT. function jwtOf(app: App, signer: () => Signer) { return async (appId: string | number, timeDifference?: number) => { if (timeDifference !== undefined) adopt(signer(), timeDifference); @@ -338,8 +316,6 @@ function jwtOf(app: App, signer: () => Signer) { }; } -/** How far GitHub's clock runs ahead of ours, where it refused a JWT for - * its times. */ function skewOf(error: unknown): number | undefined { if (!(error instanceof RequestError) || error.status !== 401) return; if (!/'(?:Expiration time|Issued at)' claim/.test(error.message)) return; @@ -605,8 +581,7 @@ export async function unlessUnchanged( } } -/** GraphQL's answer where some nodes are gone: the rest, and nulls for - * those, rather than a failure. */ +// Where some nodes are gone, GraphQL answers the rest and nulls for those, not a failure. export async function query( octokit: Client, text: string, @@ -625,13 +600,8 @@ export async function query( } } -/** GraphQL's answer to a query of `nodes(ids:)`, in the order asked, with null - * for a node that is gone and for a node GitHub refuses the token with - * FORBIDDEN, as it does a private repository's Discussions node asked for by - * a token without the Discussions permission. A node refused, at any path - * under it, is named in `refused` and its data is nulled, so it is never - * taken for gone or read in part. A refusal that names no node, such as one - * for the whole query, still throws, as does any other error. */ +// FORBIDDEN for a node (a private repository's Discussions node, without the permission) is named in `refused` and nulled, never taken for gone. +// A refusal naming no node still throws. export async function queryNodes( octokit: Client, text: string, diff --git a/connectors/github/src/graph.ts b/connectors/github/src/graph.ts index de275256..628af66f 100644 --- a/connectors/github/src/graph.ts +++ b/connectors/github/src/graph.ts @@ -85,8 +85,7 @@ interface Author { __typename: string; } -/** A bot's login as REST writes it, with its suffix, which GraphQL leaves - * off, so a row reads the same whichever answered. */ +// REST writes a bot's login with its suffix, which GraphQL leaves off. export function loginOf(author: Author | null): string | null { if (author === null) return null; return author.__typename === "Bot" ? `${author.login}[bot]` : author.login; @@ -201,7 +200,6 @@ function known( ); } -/** GraphQL names its enums in capitals; REST, which the rest follows, not. */ export function reasonOf(value: string | null): string | null { return value === null ? null : value.toLowerCase(); } @@ -251,8 +249,6 @@ export async function issuesByNode( return found; } -/** What else the relations query reads of an issue: the issues it blocks and - * those under it, and its transfer. */ export interface Linked { blocking: string[]; children: string[]; @@ -289,12 +285,6 @@ export async function relationsOf( return found; } -/** The issue comments among the nodes, and the nodes that are not known to be - * gone: `refused`, which GitHub would not show the token (a discussion - * comment in a private repository, to a token without the Discussions - * permission), and `elsewhere`, which it showed as another kind of node (a - * discussion comment in a public repository, which any token reads). Both - * belong to a read of their discussion, not to this one. */ export async function commentsByNode( octokit: Client, ids: readonly string[], @@ -417,7 +407,6 @@ const mutations = { }`, }; -/** GraphQL's answers for what will not change by asking again. */ export const refusedTypes: ReadonlySet = new Set([ "NOT_FOUND", "FORBIDDEN", @@ -491,9 +480,7 @@ async function commentIsGone(octokit: Client, id: string): Promise { ); } -/** GraphQL answers NOT_FOUND alike for a comment gone and for one it will - * not let the App touch, so it counts as gone only where the comment no - * longer reads in a repository that still does. */ +// GraphQL answers NOT_FOUND alike for a gone comment and one the App may not touch: gone only where the comment no longer reads in a repository that still does. export async function deleteComment( octokit: Client, id: string, diff --git a/connectors/github/src/notifications.ts b/connectors/github/src/notifications.ts index a7eb39f9..0ec14be7 100644 --- a/connectors/github/src/notifications.ts +++ b/connectors/github/src/notifications.ts @@ -25,8 +25,6 @@ export const notificationType = "github.notification"; export const tokenName = "github_notifications_token"; -/** The conditions a read of notifications raises, each cleared by a scheduled - * run that asks GitHub and finds it gone. */ export const refused = "notifications-refused"; export const limited = "notifications-rate-limit"; export const failed = "notifications-failed"; @@ -34,22 +32,16 @@ export const conditionKeys = [refused, limited, failed]; const stateKey = "notifications"; -/** A day on, the listing is read whole whatever `Last-Modified` last said, - * which also connects a thread to an issue synced since it was read. */ +// A day on, the listing is read whole whatever `Last-Modified` last said. const checkEvery = 24 * 60 * 60 * 1000; /** GitHub's page size for this listing is at most 50. */ const perPage = 50; -/** No listing GitHub keeps is this long; a `Link` that never ends is. */ +// No listing GitHub keeps is this long; a `Link` that never ends is. const pagesAtMost = 2000; -/** What the next run needs of this one: the moment GitHub last said the - * listing changed, when it was last asked and how long GitHub asked to wait, - * when it was last read whole, whom and what it was read for, and the held - * threads that listing did not name. A listing sorted by its last change - * moves while it is paged and can skip a live thread, so a thread is - * archived only once the listing after that one lacks it too. */ +// A listing sorted by its last change moves while paged and can skip a live thread, so a thread is archived only once the next listing lacks it too. interface Progress { modified?: string; polled: string; @@ -76,10 +68,8 @@ export interface RestThread { type RootContext = RunContext; export interface Options extends Origin { - /** Absent, nothing is read and nothing is reported. */ readonly token: string | undefined; readonly scope: Scope | undefined; - /** `github_repositories` as set; a change to it forces a whole read. */ readonly scopeText: string | undefined; } @@ -113,9 +103,7 @@ function progressOf(value: unknown): Progress | undefined { }; } -/** The address of what a thread concerns, from the repository's own and the - * last two parts of the subject's API address. GitHub names no page for - * other subjects, such as a release or a check suite. */ +// GitHub names no page for other subjects, such as a release or a check suite. function addressOf(thread: RestThread): string | undefined { const html = thread.repository?.html_url; const tail = /\/(issues|pulls|discussions|commits)\/([^/?#]+)$/.exec( @@ -131,8 +119,6 @@ function addressOf(thread: RestThread): string | undefined { return page === undefined ? undefined : `${html}/${page}/${tail[2] ?? ""}`; } -/** The kinds of subject a thread can be connected to, by the type that holds - * them and the part of the subject's address that names its number. */ const concerned: Record = { Issue: { type: issueType, path: "issues" }, PullRequest: { type: pullRequestType, path: "pulls" }, @@ -216,9 +202,7 @@ type Listing = interval: number | undefined; }; -/** The first page asks with `If-Modified-Since`, and GitHub answers every - * page of an unchanged listing 304, so the rest are asked without it. A - * failure on any page leaves nothing of the listing. */ +// GitHub answers every page of an unchanged listing 304 to `If-Modified-Since`, so only the first page sends it. async function list( octokit: Client, since: string | undefined, @@ -277,7 +261,6 @@ function refusal(error: unknown): string | undefined { : `${tokenName} cannot read notifications (${String(code)}); GitHub reads them only for a classic token or an OAuth token with the notifications scope, never for an App or a fine-grained token${scopes === undefined ? "" : `, and this token's scopes are ${scopes === "" ? "none" : scopes}`}. The threads already read are kept`; } -/** Raises the condition a failed listing leaves: GitHub's, and only GitHub's. */ function raise(error: unknown, log: RootContext["log"]): void { if (rateLimited(error)) { log.condition( @@ -298,10 +281,6 @@ function raise(error: unknown, log: RootContext["log"]): void { ); } -/** Reads the person's notifications as `github.notification` rows, on a - * scheduled run. A failure of GitHub's listing is a condition and never - * fails the run, since every other kind is read apart from it; a failure of - * Marfa is the kit's, as anywhere else. */ export async function readNotifications( context: RootContext, options: Options, @@ -325,8 +304,7 @@ export async function readNotifications( reached(...conditionKeys); const key = `${createHash("sha256").update(token).digest("hex").slice(0, 16)} ${options.scopeText?.trim().toLowerCase() ?? ""}`; const checked = kept === undefined ? NaN : Date.parse(kept.checked); - // A thread missing from the last listing is confirmed or cleared by the - // next one, so while any is, the listing is read whole. + // A thread missing from the last listing is confirmed or cleared by the next one, so while any is, the listing is read whole. const since = kept?.modified !== undefined && kept.key === key && diff --git a/connectors/github/src/pulls.ts b/connectors/github/src/pulls.ts index 8c40a239..054c2b6c 100644 --- a/connectors/github/src/pulls.ts +++ b/connectors/github/src/pulls.ts @@ -37,20 +37,10 @@ function fields(rollup: boolean): string { `; } -/** The condition for a token that cannot read check results. */ export const checksUnreadable = "checks-unreadable"; -/** - * Whether a run's pull request reads may ask a token for check results. A - * fine-grained personal token has no Checks permission, and an installation - * can refuse it too. GitHub then answers every pull request but nulls each - * one's rollup, with a FORBIDDEN error at that path. Such an answer is used - * as it is, with those pull requests' `checks` unknown (`undefined`), never - * empty, and that token is not asked for the rollup again in the run, while - * other tokens still are. The condition is named once per run. Any other - * error, including a FORBIDDEN on a pull request or a repository itself, - * still fails the read. - */ +// A fine-grained personal token has no Checks permission and an installation can refuse it: GitHub then nulls each pull request's rollup with FORBIDDEN at that path. +// That answer is used with `checks` unknown, never empty. export class Rollup { private readonly refused = new WeakSet(); private anyRefused = false; @@ -60,8 +50,6 @@ export class Rollup { private readonly log: { condition(key: string, message: string): void }, ) {} - /** Whether a read asked for the rollup and no token was refused it, which - * clears the condition. */ get answered(): boolean { return this.asked && !this.anyRefused; } @@ -98,11 +86,7 @@ export class Rollup { } } -/** The paths of the rollups GitHub refused, when every error it gave is a - * pull request that is gone (NOT_FOUND) or a refusal (FORBIDDEN) whose path - * reaches into a pull request's `commits`, and it still sent data; otherwise - * undefined. A refusal of a pull request or a repository itself is never - * taken for a refusal of its checks. */ +// A refusal of a pull request or a repository itself is never taken for a refusal of its checks. function rollupRefusals(error: unknown): (string | number)[][] | undefined { if (!(error instanceof GraphqlResponseError)) return undefined; if (error.data === null || typeof error.data !== "object") return undefined; @@ -118,8 +102,6 @@ function rollupRefusals(error: unknown): (string | number)[][] | undefined { return refusals; } -/** Drops `commits` from the pull request at `path`, so its checks read as - * unknown rather than as a commit with no checks. */ function unknownChecks(data: unknown, path: (string | number)[]): void { let node: unknown = data; for (const step of path) { @@ -235,8 +217,6 @@ function checkOf(one: Context): CheckRun | undefined { } return undefined; } -/** Every check on the rollup: the first page came with the pull request, and - * the rest are read by the rollup's id. */ async function checkRunsOf( octokit: Client, rollup: { id: string; contexts: Page }, @@ -333,9 +313,7 @@ async function mapped(octokit: Client, node: GraphPR): Promise { closingIssues: [...closing.values()], }; } -/** The pull requests with the check summary their rows hold wherever GitHub - * refused it this run, since a write without the field would clear it and - * unknown is not none. A pull request with no row yet has none. */ +// Unknown is not none: a write without the field would clear it. export async function withStoredChecks( context: Pick, "inspect">, prs: readonly PullRequest[], @@ -357,9 +335,7 @@ export async function withStoredChecks( })); } -/** The checks of each pull request, written to the `check_runs` table of its - * item, which must be written first. A pull request whose checks GitHub - * refused this run is left as it was, since unknown is not none. */ +// The item must be written first. export async function syncChecks( context: Pick, "tables">, prs: readonly PullRequest[], diff --git a/connectors/github/src/read.ts b/connectors/github/src/read.ts index cb67c061..16062411 100644 --- a/connectors/github/src/read.ts +++ b/connectors/github/src/read.ts @@ -110,26 +110,17 @@ const checkEvery = 24 * 60 * 60 * 1000; export interface Kept { installation: number; name: string; - /** GitHub's repository id, which a token names; absent until a - * scheduled run records it. */ id?: number; open?: Page[]; closed?: { since: string; pages: Page[] }; - /** `full` where the listing's first page was full last time, whose - * ETag then cannot say nothing lies past it. */ + // `full` where the first page was full last time: its ETag cannot say nothing lies past it. comments?: { since: string; etag?: string; full?: boolean }; checked?: string; - /** The time Discussions were last read down to; absent until they are. */ discussions?: { since: string }; paused?: boolean; - /** Set once the repository left the installation while a row under it was - * still active: only `takeOut` revisits it, and the writes, which reach - * only repositories the App reads, leave it out. */ + // Set while a row under a repository that left the installation is active: only `takeOut` revisits it. leaving?: boolean; - /** The repository's visibility as its rows last said it. */ private?: boolean; - /** Issues Marfa has no row for that may be mid-transfer, each with when - * this read first held it back. */ waiting?: Record; } @@ -171,14 +162,12 @@ function numbersOf(pages: readonly Page[] | undefined): number[] { type Privacy = ReadonlyMap; -/** A repository the read did not list is taken as private, so a row never - * claims more openness than was seen. */ +// A repository the read did not list is taken as private, so a row never claims more openness than was seen. function privateIn(privacy: Privacy, node: string): boolean { return privacy.get(node) ?? true; } -/** A comment cursor asked a little early, so one GitHub shows late under - * an earlier time is still read; what comes again is unchanged. */ +// Asked a little early, so an issue GitHub shows late under an earlier time is still read. const overlap = 5 * 60 * 1000; function day(at: Date): string { @@ -229,10 +218,8 @@ class Coverage { } retain(context: Context): void { - // Saved progress can be absent even when a condition stands. Keep unknown - // identities conservatively; exempt only checks this read actually reached. - // Issue keys do not carry a repository and current edges cannot identify - // every old condition, so unobserved issue evidence stays conservative. + // Saved progress can be absent even when a condition stands: keep unknown identities. + // Issue keys carry no repository and current edges cannot identify every old condition, so unobserved issue evidence stays conservative. context.log.unreached({ keys: [...this.keys], prefixes: [...this.prefixes], @@ -241,8 +228,7 @@ class Coverage { } } -/** The personal token lists the stars; failing that the notifications token, - * a classic token without `repo`, which lists public stars only. */ +// The personal token lists the stars; failing that the notifications token, a classic token without `repo`, which lists public stars only. function starReader( app: App | Personal, personal: Client | undefined, @@ -352,14 +338,11 @@ async function readAll( ? [{ id: 0, account: { login: "the personal token" } }] : await asApp(app, signal).paginate("GET /app/installations"); coverage.reached("clock-skew"); - // A person who archived or trashed a row has settled a duplicate it was in. - // This reads every issue and comment row, so a delivery leaves it to the - // scheduled run. + // A person who archived or trashed a row has settled a duplicate it was in. This reads every issue and comment row, so a delivery leaves it to the scheduled run. if (context.hints === undefined) coverage.reached(...(await settledDuplicates(context))); const clients = new Map(); - // Discussions are read with their own token, so an installation that has - // not accepted their permission still reads everything else. + // Discussions are read with their own token, so an installation that has not accepted their permission still reads everything else. const discussionClients = new Map(); const listed = new Map< string, @@ -461,8 +444,7 @@ async function readAll( ); } } - // Only a scheduled run lists the stars, and not where github_stars turned - // them off; the rest keep each mark as it was. + // Only a scheduled run lists the stars, and not where github_stars turned them off; the rest keep each mark as it was. const scheduled = context.hints === undefined; const stars = await Stars.open( context, @@ -486,8 +468,7 @@ async function readAll( const paused = new Set( [...outside.keys()].filter((node) => kept[node] !== undefined), ); - // A paused repository is reached for reading, so relations to its - // issues, which its rows still hold, stay. + // A paused repository is reached for reading, so relations to its issues, which its rows still hold, stay. const reached = new Map(); for (const { repository, installation } of [ ...listed.values(), @@ -534,8 +515,6 @@ async function readAll( ); } } - // Visibility follows immutable repository identity, including restored files - // whose repository is no longer in saved progress. await markFilesPrivate( context, new Map( @@ -648,8 +627,7 @@ async function readAll( stars.starred(node), ); forgetFiles(state, node); - // Kept while a row under it is active, so the next run takes it out - // again and archives its row once nothing under it is. + // Kept while a row under it is active, so the next run takes it out again. await save( scoped, node, @@ -816,8 +794,7 @@ async function readAll( await save(scoped, node, next[node]); }; - // Files are read with their own token, so an installation that has not - // accepted the Contents permission still reads everything else. + // Files are read with their own token, so an installation that has not accepted the Contents permission still reads everything else. const filesClients = (): Map => { const named = new Set(files.map((entry) => entry.repository)); const chosen = [...listed.values()].filter(({ repository }) => @@ -912,12 +889,7 @@ async function readAll( } } -/** Takes a repository out of this process: archives the rows this process - * holds an agreement for under it. Its own row stays while any row under it - * is still active, whoever wrote it, since another process may still sync - * it, and while the repository is starred. Answers whether it stayed for a - * row, so the caller keeps the repository's progress and takes it out again - * once nothing under it is active. */ +// Its own row stays while any row under it is active, whoever wrote it, and while the repository is starred. async function takeOut( context: Context, node: string, @@ -956,8 +928,7 @@ async function takeOut( const rows = await linked(type, inRepository, under, { rows: "all" }); remaining += rows.filter((row) => row.state === "active").length; } - // A starred repository keeps its row and its `synced`, since another - // process may still sync it: a lost star then only unmarks it. + // A starred repository keeps its row and its `synced`, since another process may still sync it: a lost star then only unmarks it. if (!starred && remaining === 0) await archive(repositoryType, [node]); const bar = [ ...(remaining > 0 @@ -989,8 +960,6 @@ async function syncRepository( rollup: Rollup; privacy: Privacy; check: boolean; - /** Marks conditions the check ran in full for, so any it did not raise - * again are cleared. */ reached: (keys: readonly string[]) => void; }, ): Promise { @@ -1058,8 +1027,7 @@ async function syncRepository( ...listed.map((issue) => issue.node_id), ...unchanged.map((one) => one.issue.node), ]); - // A child detached, or an issue no longer blocked, names nothing on - // GitHub's side of what changed: ask about those Marfa holds under it. + // A detached child or unblocked issue names nothing in GitHub's changes: ask about those Marfa holds. const held: string[] = []; if (repository.comments !== undefined) { const under = { type: issueType, ids: [...listedNodes] }; @@ -1237,8 +1205,7 @@ async function syncRepository( ); } - // Comments of an issue that waits are read with it, once it is written: the - // run that lets it go reads them all, as for a new issue. + // Comments of an issue that waits are read with it, once it is written: the run that lets it go reads them all, as for a new issue. const waitingHere = written.filter( (one) => moving.has(one.node) && one.repository.node === node, ); @@ -1332,8 +1299,7 @@ async function syncRepository( ...(repository.id !== undefined && { id: repository.id }), open: open.pages, closed: { since: windowStart, pages: closed.pages }, - // The next run reads these by node, and writes each as a new issue once - // it has waited a window. + // The next run reads these by node, and writes each as a new issue once it has waited a window. ...(waitingHere.length > 0 && { waiting: Object.fromEntries( waitingHere.map((one) => [ @@ -1459,8 +1425,6 @@ async function marked( return { ...repository, private: hidden }; } -/** Rows read before the field existed, or before the repository changed - * its visibility, are not listed again, so each one held is told. */ async function markRows( context: Context, node: string, @@ -1533,7 +1497,6 @@ async function settledDuplicates(context: Context): Promise { .map((row) => `duplicate:${row.id}`); } -// A closed issue quiet since before the window is outside it, not gone. async function checkIssues( context: Context, octokit: Client, @@ -1564,9 +1527,7 @@ async function checkIssues( return !closed || quiet >= where.windowStart; }); await archiveGone(context, octokit, where, unlisted, follower); - // Every row listed or asked about has been through the whole check, so a - // condition about one that is no longer raised is gone. A row left out - // as closed and quiet was not checked, and keeps its conditions. + // A row left out as closed and quiet was not checked, and keeps its conditions. const asked = new Set(unlisted); const checked = rows.filter((row) => listed(row) || asked.has(row)); const numbers = new Set( @@ -1603,10 +1564,6 @@ async function checkIssues( ]); } -/** Asks GitHub about rows it no longer lists. A row whose issue was - * transferred to an issue Marfa has no other row for follows it. With - * `archiving` false, only that: the run may not archive these rows, so it - * says nothing of archiving them. */ async function archiveGone( context: Context, octokit: Client, @@ -1637,8 +1594,8 @@ async function archiveGone( followed.push(next); continue; } + // A person who archived this row has settled it. if (next.kind === "duplicate") { - // A person who archived this row has settled it. if (row.state !== "active") continue; log.condition( `duplicate:${row.id}`, @@ -1711,8 +1668,7 @@ async function checkComments( "GET /repos/{owner}/{repo}/issues/comments", { owner: where.owner, repo: where.name, per_page: 100 }, )) as RestComment[]; - // Discussion comments are not in this listing and are checked with their - // discussions. + // Discussion comments are not in this listing and are checked with their discussions. const discussionComments = new Set( [...(await heldIn(context, where.node)).values()].flat(), ); @@ -1760,8 +1716,6 @@ async function checkComments( ); } -/** The comment rows, of those given, that belong to an active issue row whose - * address answers a move. */ async function movedThreads( context: Context, octokit: Client, @@ -1842,7 +1796,6 @@ async function readRelatedSources( } } -/** The number of the issue a comment row's address belongs to. */ function issueNumberOf(row: Item): number | undefined { const url = row.properties["url"]; const found = @@ -1852,8 +1805,6 @@ function issueNumberOf(row: Item): number | undefined { return found?.[1] === undefined ? undefined : Number(found[1]); } -/** The active rows of the issues that hold these comment rows, found by the - * number in each comment's address, other than those already asked about. */ async function issuesOfComments( context: Context, under: { type: string; id: string }, @@ -1977,9 +1928,7 @@ async function readNamed( const asked = await attempt(installation, () => commentsByNode(octokit, wanted), ); - // A discussion comment is not an issue's, and the token that reads issues - // may not show it: it is not gone, but only the read of its discussion - // counts it as read. + // A discussion comment is not an issue's: only the read of its discussion counts it as read. for (const id of [...(asked?.refused ?? []), ...(asked?.elsewhere ?? [])]) notIssueComments.add(id); for (const comment of asked?.found ?? []) { @@ -2108,9 +2057,7 @@ async function readNamed( return attempt(installation, () => askIssue(client, owner, name, number)); }, ); - // Issues that cannot be written yet because a rate limit stopped a check - // that says whether they are a transfer, or the copy of a moved issue's - // comments: written by a later run. + // Issues that cannot be written yet because a rate limit stopped a check that says whether they are a transfer, or the copy of a moved issue's comments: written by a later run. const stalled = new Set(); const stall = (node: string): void => { stalled.add(node); @@ -2138,8 +2085,7 @@ async function readNamed( ); if (found !== undefined) checked.add(installation); for (const [fresh, old] of found?.moves ?? []) moves.set(fresh, old); - // An issue that may be mid-transfer is written by a later run: the - // `transferred` delivery that follows it, or the schedule. + // An issue that may be mid-transfer is written by a later run: the `transferred` delivery that follows it, or the schedule. for (const node of found?.waiting ?? []) { issues.delete(node); for (const [key, comment] of comments) { @@ -2157,9 +2103,7 @@ async function readNamed( for (const comment of copies) comments.set(comment.node, comment); } } - // An installation whose check did not complete, or left before it, leaves - // its new issues for the next run, and so a moved issue whose comments were - // not read. + // An installation whose check did not complete, or left before it, leaves its new issues for the next run, and so a moved issue whose comments were not read. const unchecked = [...issues.values()] .map(({ issue }) => issue) .filter( @@ -2249,8 +2193,7 @@ async function readNamed( deferred: deferred.size > 0, }); unseenDiscussions = read.unseen; - // A discussion comment is none of an issue's: what its discussion's read - // settled is not judged again as one. + // A discussion comment is none of an issue's: what its discussion's read settled is not judged again as one. for (const link of read.handled) shown.add(link); } @@ -2336,8 +2279,7 @@ async function readNamed( hidden: (repositoryNode) => privateIn(privacy, repositoryNode), }; await archiveGone(context, octokit, { owner, name }, issueRows, follower); - // The delivery did not name these issues, so the run may follow them - // and may not archive them. + // The delivery did not name these issues, so the run may follow them and may not archive them. await archiveGone( context, octokit, diff --git a/connectors/github/src/repository-files.ts b/connectors/github/src/repository-files.ts index 0d06f95f..60073059 100644 --- a/connectors/github/src/repository-files.ts +++ b/connectors/github/src/repository-files.ts @@ -29,18 +29,14 @@ type Context = Pick< "held" | "upsert" | "archive" | "derive" | "linked" | "log" | "signal" >; -/** What github_files names in one repository. */ export interface FilesEntry { - /** As owner/name, lowercase, since GitHub's names ignore case. */ + // As owner/name, lowercase, since GitHub's names ignore case. readonly repository: string; - /** Paths from the repository's root, without leading or trailing slashes, - * each a directory or a Markdown file. */ readonly paths: readonly string[]; } const repositoryName = /^[a-z0-9_.-]+\/[a-z0-9_.-]+$/; -/** The setting's entries, or a start refused with the entry that is wrong. */ export function filesOf(value: string | undefined): FilesEntry[] { if (value === undefined) return []; const byName = new Map>(); @@ -79,21 +75,15 @@ export function filesOf(value: string | undefined): FilesEntry[] { })); } -/** Larger files are skipped: a body this long is not a note, and the - * instance caps a request well above it. */ +// A body this long is not a note, and the instance caps a request well above it. export const sizeAtMost = 512 * 1024; -/** File names that say what a file is for rather than what it is about, so - * the directory holding one names it better. */ const generic = new Set(["readme", "index", "skill", "agents", "claude"]); const markdown = /\.(?:md|markdown)$/i; -/** The most files one condition names. */ const namedAtMost = 10; -/** The saved state, by repository node: what the last complete read of the - * repository's files saw, so an unchanged branch costs one request. */ const savedKey = "repository-files"; interface Saved { @@ -110,8 +100,6 @@ function savedOf(state: State): Record { : {}; } -/** Forgets what was read of a repository taken out of the sync, so its files - * are read whole if it comes back. */ export function forgetFiles(state: State, node: string): void { const saved = savedOf(state); if (saved[node] === undefined) return; @@ -170,7 +158,6 @@ interface Blob { readonly size: number; } -/** Why GitHub would not give the tree or a blob, for a condition. */ function refusal(error: unknown): string | undefined { if (error instanceof PermissionRequired) return error.message; if ( @@ -183,7 +170,6 @@ function refusal(error: unknown): string | undefined { return code === undefined ? undefined : `GitHub answered ${String(code)}`; } -/** Each held row of the type under the repository, by path. */ function heldUnder( rows: readonly Item[], node: string, @@ -216,24 +202,14 @@ export interface Synced { } export interface FilesRun { - /** The repositories the run syncs, by lowercase full name. */ readonly synced: ReadonlyMap; - /** The repositories github_repositories pauses, by lowercase full name. */ readonly paused: ReadonlySet; - /** Whether every listing of the run answered, without which a repository - * missing from it may still be there. */ + // Without every listing answering, a repository missing from it may still be there. readonly complete: boolean; readonly reached: (...keys: string[]) => void; - /** Names a repository whose files wait for GitHub's rate limit. */ readonly waiting: (name: string) => void; } -/** - * Mirrors the Markdown files under the paths github_files names, from each - * repository's default branch, with a collection for each directory that - * holds them. GitHub is the source: these kinds are read only, so the kit - * puts back a change made in Marfa. - */ export async function syncFiles( context: Context, state: State, @@ -286,9 +262,7 @@ export async function syncFiles( state.set(savedKey, saved); } -/** Reads one repository's files and writes what changed; returns what to - * save, or nothing where the run read the tree but not all of it, so the - * next run reads it whole even if the branch is back as it was. */ +// Nothing is saved where the run read the tree but not all of it, so the next run reads it whole. async function syncRepositoryFiles( context: Context, octokit: Client, @@ -567,8 +541,7 @@ async function syncRepositoryFiles( : undefined; } -/** Each new path whose contents a vanished one held, by the path it moved - * from; where several share contents, they pair in path order. */ +// Where several share contents, they pair in path order. function pairMoves( vanished: readonly { path: string; sha: unknown }[], arrived: readonly Blob[], @@ -587,8 +560,6 @@ function pairMoves( return moves; } -/** A directory renamed with its files: each directory a file move leaves - * and the one it reaches, where only that pair says so. */ function pairDirectoryMoves( moves: ReadonlyMap, left: (path: string) => boolean, @@ -617,8 +588,6 @@ function pairDirectoryMoves( return pairs; } -/** Archives a repository's files and directories, as a repository taken out - * of the sync. */ export async function takeOutFiles( context: Pick, node: string, diff --git a/connectors/github/src/setup.ts b/connectors/github/src/setup.ts index df6a7ef5..bc715205 100644 --- a/connectors/github/src/setup.ts +++ b/connectors/github/src/setup.ts @@ -21,8 +21,7 @@ export interface SetupEnv { readonly github_app_name?: string | undefined; } -/** The App's name unless the setup names another; GitHub holds each - * name once, so a second person's setup names its own. */ +// GitHub holds each App name once. export const defaultName = "Marfa"; interface Conversion { @@ -33,7 +32,6 @@ interface Conversion { webhook_secret: string | null; } -/** The webhook events the connector reads; installations come unasked. */ export const events = [ "issues", "issue_comment", @@ -49,8 +47,7 @@ export const events = [ "status", ]; -/** The public address's own path, a prefix the instance sits behind, kept - * before the endpoint's. */ +// The public address's own path, a prefix the instance sits behind, is kept before the endpoint's. export function hookUrl(publicUrl: string, path: string): string { const address = new URL(publicUrl); address.pathname = `${address.pathname.replace(/\/+$/, "")}${path}`; @@ -90,7 +87,6 @@ export function manifest(options: { callback: string; hook: string; active: boolean; - /** Whether issues and their comments are read only. */ readOnly: boolean; discussionsReadOnly: boolean; }): Record { diff --git a/connectors/github/src/stars.ts b/connectors/github/src/stars.ts index eedff64c..5f6a2801 100644 --- a/connectors/github/src/stars.ts +++ b/connectors/github/src/stars.ts @@ -23,19 +23,12 @@ type Context = Pick< "held" | "inspect" | "upsert" | "archive" | "derive" | "log" | "signal" >; -/** The saved state: the repositories the last complete listing lacked, which - * GitHub's offset paging can do to a star that is still there when a star - * removed meanwhile shifts the pages, with the setting of the token that - * listed them, since two tokens do not list the same stars. A scheduled run - * that lists no stars clears it, so the two listings that settle a lost star - * are always consecutive. */ +// GitHub pages stars by offset, so a star removed while the listing is read shifts the rest and one still there is missed: +// a mark or row is lost only when two consecutive complete listings lack it, so a scheduled run that lists none clears this. const missedKey = "stars-missed"; -/** The condition for rows kept because GitHub would not say the repository is - * gone. */ export const starsKept = "stars-kept"; -/** The most repositories one condition names. */ const namedAtMost = 10; interface Star { @@ -43,11 +36,9 @@ interface Star { readonly at: string; } -/** The only media type that gives the time each star was made. */ +// The only media type that gives the time each star was made. const starMedia = "application/vnd.github.star+json" as const; -/** Every star of the person the token belongs to, or an error: a listing - * that stops partway is never a list of what they starred. */ async function listStars(octokit: Client): Promise> { const listing = (await octokit.paginate({ method: "GET", @@ -82,9 +73,7 @@ function whyNot(error: unknown, reading: string): string { : `GitHub answered ${String(code)}`; } -/** Whether a row is kept for its star alone, which a lost star may archive. - * A row another process syncs, and one no run has said of, is only ever - * unmarked. */ +// A row another process syncs, and one no run has said of, is only ever unmarked. function starOnly(row: Item | undefined): boolean { return row?.properties["synced"] === false; } @@ -96,18 +85,13 @@ function marked(row: Item | undefined): boolean { ); } -/** The token a run lists stars with. The notifications token is a classic - * token without `repo`, which lists public stars only, so what it does not - * list proves nothing of a private repository. */ +// The notifications token is a classic token without `repo`: it lists public stars only, so what it lacks proves nothing of a private repository. export interface Reader { readonly octokit: Client; - /** The setting that holds the token, for what is said of it. */ readonly name: string; readonly publicOnly: boolean; } -/** The repositories the last listing lacked, or none where another token - * made that listing. */ function missedOf(value: unknown, by: string): Set { if (typeof value !== "object" || value === null) return new Set(); const { by: was, nodes } = value as { by?: unknown; nodes?: unknown }; @@ -118,43 +102,20 @@ function missedOf(value: unknown, by: string): Set { ); } -/** - * What a run knows of the person's stars. A scheduled run with a token lists - * them; any other run, and one whose listing failed, takes each repository's - * mark from the row it last wrote, so a read that did not happen never - * changes a mark. - * - * GitHub pages the listing by offset, so a star removed while it is read - * shifts the rest and one still there is missed. A repository loses its mark - * or its row only when two consecutive complete listings both lack it. - */ export class Stars { private constructor( - /** The stars GitHub listed this run, by repository node; absent where - * none was listed. */ private readonly read: ReadonlyMap | undefined, - /** The repository rows held, by node; empty where nothing needs them. */ private readonly rows: ReadonlyMap, - /** The marked repositories the last complete listing lacked. */ private readonly missed: ReadonlySet, private readonly reader: Reader | undefined, private readonly state: State, - /** Whether this process holds the star fields, which github_stars - * turns off. */ private readonly holds: boolean, ) {} - /** The repositories a run saw private, which a token that lists public - * stars only cannot say are unstarred. */ + // Repositories a run saw private, which a token that lists public stars only cannot say are unstarred. private readonly shielded = new Set(); - /** - * The held rows are read only to carry marks no listing gave: where a token - * is set and the listing failed or was not asked for, and where it - * succeeded, since the rows tell a star missed once from one never made. A - * run without a token carries no marks. `listing` is whether the run would - * list the stars: a scheduled run with github_stars on. - */ + // Held rows are read only to carry marks no listing gave; a run without a token carries none. static async open( context: Context, state: State, @@ -195,12 +156,10 @@ export class Stars { ); } - /** Whether this run listed the stars. */ get listed(): boolean { return this.read !== undefined; } - /** The marked repositories this listing lacks. */ private lacking(): Set { const lacking = new Set(); if (this.read === undefined) return lacking; @@ -209,9 +168,6 @@ export class Stars { return lacking; } - /** The repository as its row should say it: marked from the listing, or - * as the row last said, until a second listing lacks it. A process that - * holds no star field sends none. */ mark(repository: RestRepository): RestRepository { if (!this.holds) return repository; const node = repository.node_id; @@ -236,29 +192,11 @@ export class Stars { }; } - /** Whether the repository is starred as far as is known, which keeps its - * row when it leaves the sync: whether it is archived is settled after. */ starred(node: string): boolean { return this.read?.has(node) === true || marked(this.rows.get(node)); } - /** - * After a scheduled run has read the repositories it syncs: brings in each - * starred repository nothing else lists, as a repository row and no more, - * and settles the rows a lost star leaves, once two listings in a row have - * lacked the star. `listed` repositories were written by their own read. A - * row kept for a repository that is read some other way, such as one - * paused, only loses its mark, as does one whose row does not say it is - * kept for its star alone, since another process may sync it under the - * same source. A star-only row nothing keeps is archived, only when - * `complete` says every listing of the run answered, since one that did not - * may be why a repository is missing, only after GitHub's own read of the - * repository shows it is not hidden by an owner that refuses the token, and - * only if its row, read again just before, still says it is star-only. - * - * A starred row that does not say it is star-only takes only its marks - * from this run, so the fields its own process writes are left to it. - */ + // A star-only row nothing keeps is archived only when every listing of the run answered, after GitHub's own read shows an owner is not hiding it from the token, and only if its row, read again just before, is still star-only. async settle( context: Context, where: { @@ -308,7 +246,7 @@ export class Stars { } else if (!this.missed.has(node)) { unresolved.add(node); } else if (where.listed.has(node)) { - // Unmarked by its own read, which carried the second miss. + // Unmarked by its own read. } else if (kept && !publicOnly) { unmarked.push(node); } else if (kept || where.complete) { @@ -367,8 +305,6 @@ export class Stars { }); } - /** Why the repository's row must stay, or nothing where the token's own - * read shows the repository gone, or open to it and not starred. */ private async refused( context: Context, name: string, diff --git a/connectors/github/src/transfer.ts b/connectors/github/src/transfer.ts index b708bf93..ee8f03c9 100644 --- a/connectors/github/src/transfer.ts +++ b/connectors/github/src/transfer.ts @@ -20,25 +20,16 @@ import { import { status, type Client } from "./github.js"; import { issuesByNode, nodesOfNumbers } from "./graph.js"; -/** - * A transfer gives an issue a new node, number and address, and copies its - * comments with new nodes and the old times. The Marfa row is the same item, - * so each place that meets the new issue names the old node in `movedFrom`. - * Nothing is matched by title: the old address answering 301 to the new - * issue is the proof. - * - * GitHub shows the new issue before it records the transfer, so an issue that - * may be mid-transfer is not written until it is known to be one or not. - */ +// A transfer gives an issue a new node, number and address, and copies its comments with new nodes and the old times. +// The old address answering 301 to the new issue is the proof; titles are never matched. +// GitHub shows the new issue before it records the transfer, so a possible mid-transfer issue is not written until known. type Context = Pick< RunContext, "linked" | "known" | "log" >; -/** How long GitHub may take to record a transfer on the new issue's - * timeline. An issue Marfa has no row for, changed within it and made - * earlier than it, with no transfer on its timeline, waits for the next run. */ +// How long GitHub may take to record a transfer on the new issue's timeline: an issue Marfa has no row for, changed within it and made earlier, with no transfer on its timeline, waits for the next run. export const transferWindow = 2 * 60 * 1000; export interface Address { @@ -80,7 +71,6 @@ function addressOf(location: string | undefined): Address | undefined { }; } -/** What the issue's own address says, asked without following a move. */ export async function askIssue( octokit: Client, owner: string, @@ -115,8 +105,7 @@ export async function askIssue( } } -/** Whether GitHub changed the issue lately, though it was made well before: - * what a transfer does, and an edit to an old issue does too. */ +// A transfer changes the issue lately though it was made well before; an edit to an old issue does too. function mayBeMoving(issue: Issue, now: number): boolean { const changed = Date.parse(issue.updatedAt); const made = Date.parse(issue.createdAt); @@ -128,16 +117,8 @@ function mayBeMoving(issue: Issue, now: number): boolean { ); } -/** For the issues Marfa has no row for, by the transfer each carries from the - * query that read it, so none is asked about again: the old row of each that was - * transferred from a repository whose rows it holds, by the issue's creation - * time, which a transfer keeps, and then the old address's answer; and those - * that may be mid-transfer, which are not written yet: one with no transfer - * on its timeline, and one whose timeline shows a transfer from a repository - * Marfa holds rows for but whose old address has not yet answered with a - * move. An issue that has waited a full window since `firstSeen` is no longer - * held back, so a busy issue cannot wait for ever. Title and text are not - * used: either may have been edited on one side only. */ +// An issue held a full window since `firstSeen` is released, so a busy issue cannot wait for ever. +// Title and text are not used: either may have been edited on one side only. export async function movedFrom( context: Context, octokit: Client, @@ -204,12 +185,7 @@ export async function movedFrom( return { moves, waiting }; } -/** The old row of each new issue a delivery names together with the old - * issue, where the timeline has no transfer event yet: GitHub records it - * about when it sends `opened`, so it can be missing. The old address - * answering 301 to the new issue is the proof, as for `movedFrom`. An issue - * Marfa already has a row for is not a move: that is a duplicate, which - * `follow` finds from the old row's side. */ +// GitHub records the transfer about when it sends `opened`, so the timeline may lack it. export async function movedNamed( context: Pick, "inspect">, unseen: readonly string[], @@ -271,15 +247,7 @@ export function withMoves( }); } -/** Names, on the comments of moved issues, the rows they replace. The copies - * keep author, time and text, so those find each one. A row whose text was - * edited in Marfa is found by author and time where, once every exact match - * is made, it is the only row and the copy the only copy left with that - * author and time, so the order of the copies does not matter. A copy that - * has no match becomes a row of its own. Where the copy already has a row of - * its own as well as the row it replaces, both are kept and a `duplicate:` - * condition names them. The rows a copy replaces hang on the issue's own - * node unless `oldThreads` says another, as for an issue held twice. */ +// The copies keep author, time and text, so those find each one. A row edited in Marfa is found by author and time only once every exact match is made, so the order of the copies does not matter. export async function withMovedComments( context: Context, entries: readonly Entry[], @@ -342,9 +310,7 @@ export async function withMovedComments( ); if (exact !== undefined) take(entry, issue, exact); } - // Edited text: by author and time, where exactly one row and one copy of - // that author and time are left. With more of either, which is which is a - // guess. + // With more than one row or copy of an author and time, which is which is a guess. const groups = new Map< string, { entries: [Entry, string][]; rows: Item[] } @@ -405,8 +371,7 @@ export async function withMovedComments( }); } -/** Every comment of an issue: the copies of a transfer keep the old times, so - * no listing of what changed since names them. */ +// The copies of a transfer keep the old times, so no listing of what changed since names them. export async function commentsOf( octokit: Client, issue: Issue, @@ -428,9 +393,7 @@ export async function commentsOf( })); } -/** The entries for the comments of issues just rekeyed, each named for the - * row it replaces. Written after the issues are, so the rows are found - * under the new node. */ +// Written after the issues, so the rows are found under the new node. export async function movedComments( context: Context, octokit: Client, @@ -450,9 +413,6 @@ export async function movedComments( ); } -/** Raises a condition for each comment of a transferred issue that is a row of - * its own and also copies a comment row the old issue's row holds. Writes - * nothing. */ export async function duplicateComments( context: Context, octokit: Client, @@ -472,7 +432,6 @@ export async function duplicateComments( } export interface Follower { - /** Repositories whose issues the connector writes. */ synced: ReadonlySet; entry: (found: { issue: Issue; relations: Relations }) => Entry; hidden: (repository: string) => boolean; @@ -483,16 +442,9 @@ export type Followed = | { kind: "duplicate"; other: Item; issue: Issue } | { kind: "away"; why: string }; -/** The reason an issue moved out of what the connector reads, for the - * condition that says its row is archived. */ export const unreadable = "a repository the App cannot read"; -/** The entry for the issue an old address now leads to, naming the old row, - * where Marfa holds it. A different row that already holds the new issue's - * node means the new issue was written before the move was known, which the - * wait for the transfer record is meant to prevent: neither row is touched. - * Otherwise where the new issue is, so the caller archives the old row: - * unreadable, outside the sync, or not the same issue. */ +// A different row already holding the new node means the new issue was written before the move was known: neither row is touched. export async function follow( context: Pick, "inspect">, octokit: Client, diff --git a/connectors/github/src/unsettled.ts b/connectors/github/src/unsettled.ts index 4b282309..a9b27799 100644 --- a/connectors/github/src/unsettled.ts +++ b/connectors/github/src/unsettled.ts @@ -2,12 +2,9 @@ import type { State } from "@withmarfa/connector"; const key = "unsettled"; -/** Every repository, where it is not known which a create may be in. */ export const everywhere = "*"; -/** A repository where a create GitHub may have made waits to be found by its - * mark is not read this run, so what it made is never read in as a row of - * its own. */ +// A repository where a create GitHub may have made waits to be found by its mark is not read this run, so what it made is never read in as a row of its own. export function unsettle(state: State, node: string): void { const held = state.get(key); const nodes = Array.isArray(held) @@ -16,7 +13,6 @@ export function unsettle(state: State, node: string): void { state.set(key, [...new Set([...nodes, node])]); } -/** What creates this run left unsettled, cleared for the next. */ export function takeUnsettled(state: State): Set { const held = state.get(key); state.set(key, undefined); diff --git a/connectors/github/src/write.ts b/connectors/github/src/write.ts index 03ea76a0..59e335cb 100644 --- a/connectors/github/src/write.ts +++ b/connectors/github/src/write.ts @@ -58,8 +58,7 @@ import { everywhere, unsettle } from "./unsettled.js"; export type Context = WatchContext; -/** A try's time asked early by as far as the connector lets GitHub's clock - * be from ours, and a little more. */ +// A try's time asked early by as far as the connector lets GitHub's clock be from ours, and a little more. export const margin = (skewAtMost + 5 * 60) * 1000; function wanted(value: unknown): { @@ -99,8 +98,6 @@ function entries(value: unknown): Record[] { : []; } -/** Whether a stored `assignees` value holds only entries, the core shape. A - * bare string, or a value that is no list, is not that. */ export function assigneesReadable(value: unknown): boolean { if (value === undefined || value === null) return true; return ( @@ -111,12 +108,7 @@ export function assigneesReadable(value: unknown): boolean { ); } -/** The logins an item's `assignees` entries name. An entry with no `name`, or - * one that is not an entry at all, is not one GitHub can be asked to assign, - * and it is said once. A create (`creating`) sends the names it has. An - * update sends none of the list when any entry is unreadable, and gives - * `undefined`: a list sent without that person would unassign them at - * GitHub. */ +// An update sends none of the list when any entry is unreadable: a list sent without that person would unassign them at GitHub. function logins( context: Context, item: Item, @@ -189,8 +181,6 @@ export function unreachable(error: unknown): string | undefined { return undefined; } -/** Throws what GitHub's answer makes of a write it did not take: a wait - * for what can pass, a refusal for what will not. */ export async function refusedOrWaits( error: unknown, octokit: Client, @@ -211,10 +201,7 @@ export async function refusedOrWaits( throw new Refused(`GitHub refused ${what}: ${why}`); } -/** A create GitHub may have made, found by its mark. Whatever stops the - * look, or where nothing is listed yet, the create waits, and the - * repository it may be in is not read this run, so what it made is never - * read in as a row of its own; the next run looks again before sending. */ +// Where the look is stopped, the create waits and its repository is not read this run, so what it made is never read as a row of its own. export async function looking( context: Context, item: Item, @@ -258,9 +245,7 @@ export function linkRefused(error: unknown): never { throw error; } -/** The repositories the App reads, which a change may be placed in or - * resolved against. One that left the installation but is kept for its - * clean-up is not among them: the App can no longer reach it. */ +// One that left the installation but is kept for its clean-up is not among them: the App can no longer reach it. export function allKept(context: Context): Record { const value = context.state.get("repositories"); return typeof value === "object" && value !== null @@ -272,8 +257,7 @@ export function allKept(context: Context): Record { : {}; } -/** An answer names every field the vendor holds, or the next read takes the - * missing one for the vendor's change. */ +// An answer names every field the vendor holds, or the next read takes the missing one for a vendor change. function answerOf(context: Context, comment: Comment): Entry { return commentEntry( comment, @@ -288,11 +272,7 @@ function paused(node: string, kept: Kept): Unreachable { ); } -/** A token that looks things up across the repositories the connector - * holds under an installation, paused ones too, reading only. Where one - * has no id recorded yet, or GitHub refuses to name one, it reaches the - * whole installation instead: it only finds where a node sits, and - * `placeIn` refuses anything the connector does not sync. */ +// Reads only. Where no id is recorded yet, or GitHub refuses to name one, it reaches the whole installation: it only finds where a node sits, and `placeIn` refuses anything the connector does not sync. export function looker( context: Context, app: App, @@ -316,9 +296,7 @@ export function looker( ); } -/** A token for one write, naming by id only the repositories it touches - * that are synced and not paused, so a stale or refused repository holds - * up only the writes that touch it. */ +// Names by id only the repositories it touches that are synced and not paused, so a stale or refused repository holds up only the writes that touch it. function writer( context: Context, app: App, @@ -357,8 +335,6 @@ export interface Place { readonly repository: { readonly node: string; readonly name: string }; } -/** Where a write lands: a repository GitHub named, which the connector syncs - * and has not paused, or the write waits. */ export function placeIn( context: Context, app: App, @@ -382,8 +358,7 @@ export function placeIn( }; } -/** Asked of each installation the sync uses, as a node it cannot see - * answers nothing; one that refuses the App is passed over. */ +// A node an installation cannot see answers nothing; one that refuses the App is passed over. export async function seek( context: Context, app: App, @@ -406,9 +381,7 @@ export async function seek( return undefined; } -/** The issue an agreed node id is now, wherever GitHub says it sits, so a - * renamed or transferred repository, or a reused name, cannot misroute a - * write, and a row's own fields never choose its target. */ +// Resolved by the agreed node id wherever GitHub says it sits, so a renamed or transferred repository, or a reused name, cannot misroute a write. async function issueAt( context: Context, app: App, @@ -480,16 +453,7 @@ export async function repositoryAt( return placeIn(context, app, found, access); } -/** Tells a target GitHub dropped from one out of the App's reach. A node - * that shows under no installation is in none of the synced repositories - * once each of them, asked by its own node, still reads; while any does - * not, the target may be there, and the change waits. No row's text takes - * part, so neither an edited row nor a reused name can settle a change. - * `kind` is what the target is: an issue is hidden by its repository's - * Issues switch, a discussion by its Discussions switch. A change that - * has no agreed placement, such as a new comment, names the repository of - * the thread it goes into by its full name, `thread`, so that switch is - * judged too. */ +// A node under no installation counts as gone only once every synced repository, asked by its own node, still reads; no row's text takes part. export async function goneOrWaits( context: Context, app: App, @@ -552,8 +516,7 @@ export async function goneOrWaits( { scope: `${kind}-off:${node}` }, ); } - // Settled, unlike a refusal: the App can no longer find the target, which - // is no fault of the change, and the daily check or a delivery archives it. + // Settled, unlike a refusal: the App can no longer find the target, which is no fault of the change. context.log.condition( `target-gone:${item.id}`, `GitHub no longer shows what ${item.id} is linked to in any repository the connector syncs, so the change to it is not sent`, @@ -581,7 +544,7 @@ function none(): Related { return { added: new Map(), removed: new Map() }; } -/** Includes the relations this carry made, whatever a lagging read says. */ +// Includes the relations this carry made, whatever a lagging read says. async function answerIssue( context: Context, octokit: Client, @@ -719,8 +682,7 @@ async function relations( return related; } -/** Names an assignee GitHub dropped without a word, as it does one who - * cannot be assigned. */ +// GitHub drops an assignee who cannot be assigned without a word. function dropped( context: Context, item: Item, @@ -880,12 +842,10 @@ async function carryIssue( if (named !== undefined) patch["assignees"] = named; } const binned = change.kind === "trashed" || change.kind === "purged"; - // A restore is its own transition. It may reopen from the row's status - // even when that status did not change in this run. + // A restore is its own transition: it may reopen from the row's status even when that did not change in this run. const fromBin = change.kind === "restored" && change.was === "trashed"; const state = wanted(item.properties["status"]); - // A close reason is copied only when status itself is still to send. - // Coming back from the bin still reopens a row whose status is open. + // A close reason is copied only when status itself is still to send; coming back from the bin still reopens a row whose status is open. if ( change.changed.has("status") || (fromBin && diff --git a/connectors/github/test/discussions.test.ts b/connectors/github/test/discussions.test.ts index b77c9a8a..b4612092 100644 --- a/connectors/github/test/discussions.test.ts +++ b/connectors/github/test/discussions.test.ts @@ -93,7 +93,7 @@ async function ok(env: Record = {}) { return result.output; } -/** A run, then another that must send GitHub nothing more. */ +// A run, then another that must send GitHub nothing more. async function settled(env: Record = {}) { const output = await ok(env); const before = github.writes().length; @@ -431,7 +431,6 @@ describe("a discussion changed in Marfa", () => { const first = github.addDiscussionComment(discussion, "First", "ana"); const second = github.addDiscussionComment(discussion, "Second", "bo"); await ok(); - // A person's own link from one comment to another. marfa.drawEdge(row(first.node).id, row(second.node).id, "parent-of"); await ok({ github_read_only: "comment" }); await ok({ github_read_only: "comment" }); diff --git a/connectors/github/test/hooks.test.ts b/connectors/github/test/hooks.test.ts index d66b2ce3..b60bedcb 100644 --- a/connectors/github/test/hooks.test.ts +++ b/connectors/github/test/hooks.test.ts @@ -905,9 +905,7 @@ describe("a run for deliveries", () => { const reads = marfa.requests.filter( (one) => one.method === "GET" && one.path.startsWith("/items"), ); - // Ten, whether the repository holds 8 discussions or 30: only the named - // discussion's comments are read, with one more read for their replies, - // never every comment row or every discussion's. + // Ten whether the repository holds 8 discussions or 30: only the named discussion's comments are read. expect(reads.length).toBeLessThanOrEqual(11); expect( reads.filter((one) => one.query.get("filter")?.includes("comments-on")), diff --git a/connectors/github/test/notifications.test.ts b/connectors/github/test/notifications.test.ts index 053eb648..f5d665ae 100644 --- a/connectors/github/test/notifications.test.ts +++ b/connectors/github/test/notifications.test.ts @@ -114,7 +114,7 @@ function saved(): Saved { if (state?.notifications === undefined) throw new Error("No saved progress"); return state.notifications; } -/** Moves the saved moments back, as time passing would. */ +// Moves the saved moments back, as time passing would. function age(seconds: number, field: "polled" | "checked"): void { const progress = saved(); progress[field] = new Date( @@ -232,8 +232,7 @@ describe("notifications", () => { number: issue.number, }); const onlyIssues = await counted(); - // The witness: each thread of another kind makes the listing read that - // kind's rows, and only that kind's. + // The witness: each thread of another kind makes the listing read only that kind's rows. github.notifications.add(repo, { type: "PullRequest", title: pr.title, @@ -500,7 +499,6 @@ describe("notifications", () => { "notifications", ); expect(JSON.stringify(conditions())).not.toContain(token); - // The other kinds went on, and the thread already held was kept. expect(row(issue.node).properties["title"]).toBe("Renamed on GitHub"); expect( marfa.rows.filter((one) => one.type === "github.issue"), @@ -580,14 +578,12 @@ describe("notifications", () => { expect(held().map((one) => one.properties["github_id"])).toEqual([ inside.id, ]); - // Nothing changed on GitHub, yet the wider setting reads what it left out. await ok({ github_repositories: "someone/*, stranger/public" }); expect( held() .map((one) => one.properties["github_id"]) .sort(), ).toEqual([inside.id, outside.id, elsewhere.id].sort()); - // Narrowed again, what was read is left as it is, not archived. await ok({ github_repositories: "someone/tracker" }); expect(held().every((one) => one.state === "active")).toBe(true); expect(held()).toHaveLength(3); @@ -647,7 +643,6 @@ describe("notifications", () => { expect(row(gone.id).state).toBe("archived"); expect(row(kept.id).state).toBe("active"); expect(saved().missing).toEqual([]); - // It comes back as the same row when GitHub lists it again. github.notifications.threads.push(gone); github.notifications.change(gone, { unread: true }); await ok(); @@ -711,7 +706,6 @@ describe("notifications", () => { expect(row(moved.id).state).toBe("active"); expect(row(moved.id).properties["unread"]).toBe(true); expect(saved().missing).toEqual([moved.id]); - // The next listing is whole and finds it: it is no longer missing. await ok(); expect(row(moved.id).state).toBe("active"); expect(row(moved.id).properties["unread"]).toBe(false); diff --git a/connectors/github/test/pulls.test.ts b/connectors/github/test/pulls.test.ts index c54443e5..a1f273c1 100644 --- a/connectors/github/test/pulls.test.ts +++ b/connectors/github/test/pulls.test.ts @@ -174,7 +174,6 @@ describe("pull request reading", () => { expect(row(ready.node).properties["status"]).toBe("open"); expect(row(ready.node).properties).not.toHaveProperty("pr_state"); expect(row(ready.node).properties).not.toHaveProperty("draft"); - // A row from before the status carried both words. marfa.edit(row(ready.node).id, { pr_state: "open", draft: false }); github.edit(ready, { title: "Touched" }); await ok(); diff --git a/connectors/github/test/quiet-run.test.ts b/connectors/github/test/quiet-run.test.ts index 99386e11..0ea914dc 100644 --- a/connectors/github/test/quiet-run.test.ts +++ b/connectors/github/test/quiet-run.test.ts @@ -47,7 +47,6 @@ quietRun({ const issues = Array.from({ length: size }, () => github.addIssue(repository), ); - // A few relations, so the run asks Marfa what is held under them. for (const [at, issue] of issues.entries()) { if (at % 10 !== 1) continue; const other = issues[at - 1]; diff --git a/connectors/github/test/read.test.ts b/connectors/github/test/read.test.ts index 6fc47af2..112eecb7 100644 --- a/connectors/github/test/read.test.ts +++ b/connectors/github/test/read.test.ts @@ -121,8 +121,7 @@ function forgetPrivate(): void { Reflect.deleteProperty(one, "private"); } -/** GitHub's hour is spent by the first repository's read, though the - * installation's repositories were listed before it. */ +// GitHub's hour is spent by the first repository's read, though the installation's repositories were listed before it. function spendAtRead(): void { github.onAsked = (one) => { if (one.path.startsWith("/repos/")) github.exhaust("core"); @@ -233,8 +232,7 @@ describe("a first sync", () => { if (one.path !== "/repos/someone/second/issues") return; reported = github.asked.indexOf(one); } - // From the second repository's listing on, each request is counted - // and its answer says `left`. + // From the second repository's listing on, each request is counted and its answer says `left`. github.budget("core").remaining = left + 1; }; const output = await ok(); @@ -1438,7 +1436,6 @@ describe("what the adversarial review found", () => { closed_at: github.ago(200), updated_at: github.ago(200), }); - // Other listed issues, so the run asks about many at once. const listed = Array.from({ length: 30 }, (_, at) => github.addIssue(repository, { title: `Listed ${String(at)}` }), ); @@ -1653,7 +1650,6 @@ describe("a relation to an issue in a repository left out", () => { }); }); -// Helper: run the connector with a personal token instead of App credentials. async function onceWithToken( token: string, extra: Record = {}, @@ -1694,15 +1690,12 @@ describe("a personal access token run", () => { it("fails the run with a clear message when the token is rejected (401), and does not archive rows", async () => { const repository = github.addRepository("someone/tracker"); github.addIssue(repository); - // Sync first with a valid token to populate rows. await onceWithToken(personalToken); expect(marfa.rows.some((r) => r.type === "github.repository")).toBe(true); - // Now run with a wrong token. const result = await onceWithToken("wrong_token_12345678"); expect(result.code).toBe(1); expect(result.output).toContain("github_personal_token"); expect(result.output).not.toContain("wrong_token"); - // Rows must not be archived. expect( marfa.rows.filter( (r) => r.type === "github.repository" && r.state === "active", @@ -1757,7 +1750,6 @@ describe("a personal access token run", () => { it("refuses to start when both App settings and token are set", async () => { const result = await once({ github_personal_token: personalToken, - // once() already sets github_app_id and github_private_key }); expect(result.code).toBe(4); expect(result.output).toMatch(/one of|either/i); @@ -1818,14 +1810,12 @@ describe("a personal access token run", () => { const repository = github.addRepository("someone/tracker"); const issue = github.addIssue(repository, { title: "Original" }); await onceWithToken(personalToken); - // Edit the issue in Marfa; with issue read-only, the edit is put back. const issueRow = row(issue.node); marfa.edit(issueRow.id, { title: "Edited in Marfa" }); const result = await onceWithToken(personalToken, { github_read_only: "issue", }); expect(result.code, result.output).toBe(0); - // The issue on GitHub is unchanged. expect(issue.title).toBe("Original"); expect(github.writes()).toHaveLength(0); expect(row(issue.node).properties["title"]).toBe("Original"); diff --git a/connectors/github/test/repository-files.test.ts b/connectors/github/test/repository-files.test.ts index 9c1ca7a1..bca8b5c9 100644 --- a/connectors/github/test/repository-files.test.ts +++ b/connectors/github/test/repository-files.test.ts @@ -186,7 +186,6 @@ describe("repository files", () => { .map(String) .sort(), ); - // Two collections at the top: neither path's root sits under the other. expect( marfa.edges.filter( (one) => @@ -299,7 +298,6 @@ describe("repository files", () => { const said = conditions()[`files-skipped:${repository.node}`]; expect(said).toContain("runbooks/huge.md (over 512 KiB)"); expect(said).toContain("runbooks/latin.md"); - // The next run reads the same tree, so it keeps the condition. await sync(); expect(conditions()[`files-skipped:${repository.node}`]).toBe(said); }); @@ -445,7 +443,6 @@ describe("repository files", () => { ]); expect(at[0]?.properties["body"]).toBe("# Development\n"); expect(file("runbooks/development.md")?.state).toBe("archived"); - // A later change to the branch reads no blob of the file again. const blobs = () => github.asked.filter((one) => one.path.includes("/git/blobs/")).length; const before = blobs(); diff --git a/connectors/github/test/setup.test.ts b/connectors/github/test/setup.test.ts index 4d2645a3..caaa0944 100644 --- a/connectors/github/test/setup.test.ts +++ b/connectors/github/test/setup.test.ts @@ -52,8 +52,6 @@ afterEach(async () => { await github.stop(); }); -/** Runs setup, answering what it logged and the commands it printed on - * standard output. */ function setup( env: Record, seen: (line: string) => void, @@ -329,7 +327,6 @@ describe("setup", () => { }); await visited; expect(finished.code).toBe(0); - // issue is read-only but comment is still carried, so issues:write is needed. expect(manifest).toMatchObject({ default_permissions: { issues: "write", metadata: "read" }, }); diff --git a/connectors/github/test/stars.test.ts b/connectors/github/test/stars.test.ts index c50f02e9..695e8f75 100644 --- a/connectors/github/test/stars.test.ts +++ b/connectors/github/test/stars.test.ts @@ -44,8 +44,6 @@ const connections = [ let key: string; let marfa: ScriptedServer; let github: GitHubStub; -/** The repositories the token lists as the person's own; any other it - * reaches only as a star. */ const reach = new Set(); beforeAll(() => { @@ -135,7 +133,6 @@ function unlist(repository: Repository): void { github.personalRepositories = new Set(reach); } -/** A repository the person has starred and no token collaborates on. */ function starOnly(name: string, fields: Partial = {}) { const repository = github.addRepository(name, { private: false, ...fields }); github.star(repository); @@ -168,7 +165,6 @@ describe("starred repositories", () => { const at = repositoryRow(tracker).properties["starred_at"]; expect(repositoryRow(starred).properties["starred"]).toBe(true); - // Another process owns these stars now: this one's token lists none of them. github.unstar(starred); github.unstar(tracker); const before = marfa.log.length; @@ -191,14 +187,12 @@ describe("starred repositories", () => { }); it("only unmarks a repository another process syncs, and archives only a row nothing syncs", async () => { - // Process B syncs the organization with its own token and reads no stars; - // process A reads the person's stars, each on a key of the source. + // Process B syncs the organization with its own token and reads no stars; process A reads the person's stars, each on a key of the source. const other = "github_pat_withmarfa_12345678"; const synced = github.addRepository("org/x", { private: false }); const issue = github.addIssue(synced); const own = github.addRepository("someone/own"); const only = starOnly("someone/only"); - // Star-only under A first, then taken up by B. const later = starOnly("org/later"); github.star(synced); const bSyncs = [synced]; @@ -496,8 +490,7 @@ describe("starred repositories", () => { await sync(); expect(repositoryRow(gone).state).toBe("active"); - // The failed listing broke the run of complete ones, so this is the - // first miss again, and the next is the second. + // The failed listing broke the run of complete ones, so this is the first miss again, and the next is the second. github.starsFailAt = undefined; await sync(); expect(repositoryRow(gone).state).toBe("active"); @@ -651,7 +644,6 @@ describe("starred repositories", () => { expect(repositoryRow(tracker).id).toBe(id); expect(repositoryRow(tracker).state).toBe("active"); expect(repositoryRow(tracker).properties["starred"]).toBe(true); - // Another process may still sync it, so the row keeps saying it is synced. expect(repositoryRow(tracker).properties["synced"]).toBe(true); github.unstar(tracker); @@ -784,7 +776,6 @@ describe("starred repositories", () => { describe("stars read with the notifications token", () => { const classic = "ghp_classic_notifications_12345678"; - /** No installation of the App reaches it, so it is a star and nothing else. */ const elsewhere = { installation: 99 }; beforeEach(() => { @@ -859,8 +850,7 @@ describe("stars read with the notifications token", () => { await sync(); expect(repositoryRow(secretOnly).properties["starred"]).toBe(true); expect(repositoryRow(secretSynced).properties["starred"]).toBe(true); - // The person's rows now come from the App, which still reaches - // one of them; the other is a star and nothing else. + // The person's rows now come from the App, which still reaches one of them; the other is a star and nothing else. secretOnly.installation = 99; for (let at = 0; at < 4; at += 1) await syncWithClassic(); diff --git a/connectors/github/test/tokens.test.ts b/connectors/github/test/tokens.test.ts index 753f20c4..8d35b915 100644 --- a/connectors/github/test/tokens.test.ts +++ b/connectors/github/test/tokens.test.ts @@ -256,7 +256,6 @@ describe("a personal access token", () => { repo: "tracker", }); expect(seen).toContain(personalToken); - // The repository was reachable without an installation token. expect( github.asked.find((one) => one.path === "/repos/someone/tracker")?.status, ).toBe(200); diff --git a/connectors/github/test/transfer-match.test.ts b/connectors/github/test/transfer-match.test.ts index b32a3f77..d4a4a27e 100644 --- a/connectors/github/test/transfer-match.test.ts +++ b/connectors/github/test/transfer-match.test.ts @@ -36,7 +36,6 @@ function comment(node: string, body: string, issue: string): Entry { } describe("matching the comments of a moved issue", () => { - // Two comments by one author in one second, the first edited in Marfa. const rows = (): Item[] => [ item({ github_id: "C1", body: "First, edited", from: "alice" }, at), item({ github_id: "C2", body: "Second", from: "alice" }, at), @@ -69,8 +68,7 @@ describe("matching the comments of a moved issue", () => { ])( "leaves both unmatched where two copies share one row's author and time: %s", async (_, reversed) => { - // One edited row, and two copies by the same author in the same second: - // either copy could be its. + // One edited row, and two copies by the same author in the same second: either copy could be its. const held = [ item({ github_id: "C1", body: "First, edited", from: "alice" }, at), ]; @@ -226,8 +224,6 @@ describe("an issue that may be mid-transfer", () => { }; } - /** What the run finds out about the issues, with no transfer on any - * timeline and none of them held by a row. */ async function waiting( issues: Issue[], options: { @@ -285,8 +281,6 @@ describe("an issue that may be mid-transfer", () => { ).toEqual(["N1"]); }); - /** An issue whose timeline shows a transfer from a repository Marfa holds - * a row of, though the old address still answers 200. */ async function showing( issues: Issue[], firstSeen: Record = {}, diff --git a/connectors/github/test/transfer.test.ts b/connectors/github/test/transfer.test.ts index 0d7bbc5a..5e3638a2 100644 --- a/connectors/github/test/transfer.test.ts +++ b/connectors/github/test/transfer.test.ts @@ -99,8 +99,7 @@ async function until(holds: () => boolean, what: string): Promise { } } -/** Runs the connector as a service, past its first read, then hands over to - * the body, which delivers webhooks to it. */ +// Runs the connector as a service, past its first read, then hands over to the body, which delivers webhooks to it. async function watching(body: () => Promise): Promise { const child = spawn("node", [built, "--every", "1h", "--look-every", "1s"], { env: marfa.processEnv(env()), @@ -147,7 +146,6 @@ function lastWrites(after: number): string[] { let source: Repository; let target: Repository; -/** Source and target as the connector lists them: in the order given. */ function repositories(sourceFirst: boolean): void { if (sourceFirst) { source = github.addRepository("someone/source"); @@ -399,7 +397,6 @@ describe("a transferred issue", () => { expect(row(first.node).id).toBe(firstId); expect(row(first.node).state).toBe("active"); - // Both move: each follows its own address. const movedFirst = github.transfer(first, target); await once(); expect(row(movedFirst.node).id).toBe(firstId); @@ -427,13 +424,10 @@ describe("a transferred issue", () => { const stub = github.issues.find((one) => one.node === away.node); if (stub !== undefined) delete stub.movedTo; await once(); - // Its timeline shows a transfer from a repository Marfa holds a row of, - // and no old address confirms it, so it waits. + // Its timeline shows a transfer from a repository Marfa holds a row of, and no old address confirms it, so it waits. expect( marfa.rows.some((one) => one.properties["github_id"] === moved.node), ).toBe(false); - // Once a full window has passed with no proof, it is a new issue, and - // not the row of either of the others that share its title and time. const state = marfa.states.get("github")?.["state"] as | { repositories?: Record>>; @@ -456,7 +450,6 @@ function conditions(): Record { >; } -/** A time well before the transfer window, as an old issue has. */ function earlier(minutes: number): string { return new Date(Date.now() - minutes * 60_000) .toISOString() @@ -464,7 +457,6 @@ function earlier(minutes: number): string { } describe("a transferred issue whose transfer record is late", () => { - /** An issue made long ago, with a comment the App may carry back. */ function oldIssue(title: string) { const moving = github.addIssue(source, { title, @@ -506,7 +498,6 @@ describe("a transferred issue whose transfer record is late", () => { ); }; if (openedFirst) { - // GitHub has not recorded the transfer: the new issue waits. await delivered("opened"); expect( marfa.rows.some( @@ -555,7 +546,6 @@ describe("a transferred issue whose transfer record is late", () => { const moved = github.transfer(moving, target, { late: true, showing }); await once(); - // Written by no run yet: no second row, and no copy of the comment. expect(rowsOf("github.issue")).toHaveLength(1); expect(rowsOf("github.comment")).toHaveLength(1); expect(marfa.byId(issueId).state).toBe("active"); @@ -660,7 +650,6 @@ describe("a transferred issue whose transfer record is late", () => { }, ); - /** The daily check is due again in every repository. */ function checkDue(): void { const state = marfa.states.get("github")?.["state"] as { repositories?: Record> } | undefined; @@ -922,8 +911,7 @@ describe("an issue that waits for its transfer record on a first sync", () => { expect(Object.keys(waited() ?? {})).toEqual([busy.node]); expect(listed()["open"]).toBeDefined(); - // Another change inside the window: it keeps waiting, and nothing already - // read is read again. + // Another change inside the window: it keeps waiting, and nothing already read is read again. touch(); github.asked = []; await once(); diff --git a/connectors/github/test/write.test.ts b/connectors/github/test/write.test.ts index e4ce4302..c6e75cb9 100644 --- a/connectors/github/test/write.test.ts +++ b/connectors/github/test/write.test.ts @@ -676,7 +676,6 @@ describe("a row made in Marfa", () => { }); await ok(); const original = row(issue.node); - // Marfa copies the original's repository edge to the copy it writes. const copy = marfa.conflictedCopy(original.id, { body: "Theirs" }); marfa.drawEdge(copy.id, row(repository.node).id, "github.in-repository"); diff --git a/connectors/google-calendar/src/api.ts b/connectors/google-calendar/src/api.ts index 8fe1e2ce..4160f158 100644 --- a/connectors/google-calendar/src/api.ts +++ b/connectors/google-calendar/src/api.ts @@ -26,7 +26,6 @@ export function list(from: Json | undefined, key: string): unknown[] { return Array.isArray(value) ? (value as unknown[]) : []; } -/** Every page of a listing: its items, and the token the last page ends with. */ export interface Listing { readonly items: Json[]; readonly syncToken: string | undefined; @@ -34,7 +33,6 @@ export interface Listing { const mostPages = 10_000; -/** Google's Calendar API, within the sign-in's token and time limit. */ export class CalendarApi { constructor( private readonly google: Google, @@ -74,7 +72,6 @@ export class CalendarApi { throw new GoogleError("Google kept answering pages", "passing"); } - /** Every calendar of the account, hidden ones too. */ calendars(): Promise { return this.pages("/users/me/calendarList", { showHidden: "true", @@ -82,8 +79,6 @@ export class CalendarApi { }); } - /** One calendar of the account's list, or `"gone"` where Google says it - * is no longer on it. */ async calendar(calendarId: string): Promise { try { return await this.get( @@ -96,9 +91,8 @@ export class CalendarApi { } } - /** The events of a calendar, whole or since the sync token. Deleted ones - * are always asked for: a read since a token must have them. A token - * Google no longer holds answers 410, which throws. */ + // Deleted events are always asked for: a read since a sync token must have them. + // A token Google no longer holds answers 410, which throws. events(calendarId: string, syncToken?: string): Promise { return this.pages(`/calendars/${encodeURIComponent(calendarId)}/events`, { singleEvents: "false", @@ -108,8 +102,6 @@ export class CalendarApi { }); } - /** One event, or `"gone"` where Google says it is deleted or was never - * there. */ async event(calendarId: string, eventId: string): Promise { try { return await this.get( @@ -153,8 +145,8 @@ export class CalendarApi { : `${events}/${encodeURIComponent(eventId)}`; } - /** Makes an event under the id given, which Google answers 409 where the - * calendar already holds it, deleted or not. */ + // Google answers 409 where the calendar already holds the id, deleted or not. + // The create's own id is how a lost answer is found again: do not replace it with an id Google makes. async insert(calendarId: string, event: Json): Promise { const made = await this.write( "POST", @@ -168,8 +160,7 @@ export class CalendarApi { return made; } - /** Changes the fields named, and only those, while the event is still at - * `etag`; Google answers 412 where it changed since. */ + // Google answers 412 where the event changed since `etag`. async patch( calendarId: string, eventId: string, @@ -189,8 +180,7 @@ export class CalendarApi { return changed; } - /** Deletes an event while it is still at `etag`. One Google no longer has - * is already deleted. */ + // An event Google no longer has is already deleted. async remove( calendarId: string, eventId: string, @@ -209,8 +199,7 @@ export class CalendarApi { } } - /** Moves an event to another calendar, keeping its id, while it is still - * at `etag`; Google answers 412 where it changed since. */ + // Google answers 412 where the event changed since `etag`. async move( calendarId: string, eventId: string, @@ -230,8 +219,6 @@ export class CalendarApi { return moved; } - /** The occurrences of a series that began at `originalStart`, cancelled - * ones included. */ async occurrence( calendarId: string, seriesId: string, @@ -249,9 +236,6 @@ export class CalendarApi { } } - /** Every event of a calendar, with the changed and cancelled occurrences - * of its series, in whatever year they fall, and only the fields that say - * whether Marfa may change one: none for a calendar Google no longer has. */ async inventory(calendarId: string): Promise { try { const { items } = await this.pages(this.eventPath(calendarId), { @@ -268,7 +252,6 @@ export class CalendarApi { } } - /** The cancelled occurrences of a series between two moments. */ async cancelled( calendarId: string, seriesId: string, @@ -300,7 +283,6 @@ export function isGone(error: unknown): boolean { ); } -/** Google no longer holds the sync token. */ export function tokenExpired(error: unknown): boolean { return error instanceof GoogleError && error.status === 410; } diff --git a/connectors/google-calendar/src/config.ts b/connectors/google-calendar/src/config.ts index 7ba20344..73102fe0 100644 --- a/connectors/google-calendar/src/config.ts +++ b/connectors/google-calendar/src/config.ts @@ -8,18 +8,14 @@ export const source = "google-calendar"; export const calendarType = calendarDefinition.id; export const eventType = eventDefinition.id; -/** An event on a calendar. It orphans, so trashing a calendar in Marfa takes - * none of its events with it, and changing it moves the event. */ +// Orphans, so trashing a calendar in Marfa takes none of its events with it. export const inCalendar = "google.calendar.in-calendar"; -/** The instance's own `parent-of`, read from the exception's side. */ export const childOf = "child-of"; export const eventsScope = "https://www.googleapis.com/auth/calendar.events"; export const calendarListScope = "https://www.googleapis.com/auth/calendar.calendarlist.readonly"; export const scopes = [eventsScope, calendarListScope] as const; -/** What the connector signs in for: the rows of these types under `source` - * hold the account in their `source_id`. */ export const needs = { plugin: name, source, @@ -42,8 +38,7 @@ export const settings = [ }, ] as const satisfies SettingsDeclaration; -/** The event fields Google holds that Marfa never changes there: they are - * put back where a person changes them. */ +// Fields Google holds that Marfa never changes there: they are put back where a person changes them. export const eventReadOnly = [ "original_starts_at", "url", @@ -61,17 +56,13 @@ export const eventReadOnly = [ childOf, ] as const; -/** Facts about an event that are not something done to it. */ export const eventDerived = ["etag", "editable", "uneditable_reason"] as const; -/** The safety stop on deleting: a batch of trashes and purges is held when - * it would delete more than this many events of one calendar, and more than - * a quarter of the events it holds. */ +// A batch of trashes and purges is held when it would delete more than this many events of one calendar and over a quarter of what it holds. export const deleteLimit = 10; -/** Google's calendar of contacts' birthdays, which is not a calendar of - * events a person made. Written in parts so that the tree check for personal - * addresses does not read Google's fixed id as one. */ +// Google's contacts-birthdays calendar, which is not a calendar of events a person made. +// Written in parts so the tree check for personal addresses does not read its fixed id as one. export const birthdays = "addressbook#contacts" + "@group.v.calendar.google.com"; diff --git a/connectors/google-calendar/src/definition.ts b/connectors/google-calendar/src/definition.ts index 5bf1c7e9..5f005858 100644 --- a/connectors/google-calendar/src/definition.ts +++ b/connectors/google-calendar/src/definition.ts @@ -56,7 +56,6 @@ function names(value: string | undefined): Set { ); } -/** The connector; a test passes the address of its stub of Google. */ export function connector(options?: GoogleOptions) { const base = `${options?.endpoints?.api ?? "https://www.googleapis.com"}/calendar/v3`; const now = options?.now ?? Date.now; @@ -96,7 +95,6 @@ export function connector(options?: GoogleOptions) { const google = connectGoogle(context, needs, options); const access = await google.ready(); if (!access.has(calendarListScope)) { - // Nothing is read, so every check of the calendars is skipped. context.log.unreached({ prefixes: [...calendarChecks] }); return; } diff --git a/connectors/google-calendar/src/events.ts b/connectors/google-calendar/src/events.ts index 76b92e4d..f9cac6c2 100644 --- a/connectors/google-calendar/src/events.ts +++ b/connectors/google-calendar/src/events.ts @@ -8,7 +8,6 @@ import { flag, isJson, list, object, text, type Json } from "./api.js"; import { calendarType, childOf, eventType, inCalendar } from "./config.js"; import { dayStart, iso, nextDay, validZone } from "./time.js"; -/** What a read knows of a calendar it syncs. */ export interface CalendarInfo { readonly id: string; readonly title: string; @@ -19,8 +18,6 @@ export interface CalendarInfo { readonly color: string | undefined; } -/** A description Google holds as Markdown: `""` where it holds nothing, and - * `undefined` where it cannot be converted. */ function markdownOf(value: string): string | undefined { try { return htmlToMarkdown(value); @@ -30,33 +27,18 @@ function markdownOf(value: string): string | undefined { } } -/** - * Google lets a description hold HTML, and a description is the row's body, - * which is Markdown: HTML is converted, and text is kept as it is. A - * description Google holds that cannot be converted is left out. - */ +// Google lets a description hold HTML; the row's body is Markdown, so HTML is converted. export function descriptionOf(value: string | undefined): string | undefined { if (value === undefined) return undefined; const markdown = markdownOf(value); return markdown === undefined || markdown === "" ? undefined : markdown; } -/** - * What Google is sent for a description: the row's Markdown as the HTML - * Google shows, or as plain text where it holds no formatting. Throws - * `NotConvertible`, with its reason, for a description it cannot convert. - */ export function descriptionToGoogle(markdown: string): string { return markdownToHtml(markdown); } -/** - * Whether what Google would be sent says what Google already holds. Both are - * read back as Markdown, so that formatting Google keeps differently, such as - * a line break, is not a change and an unchanged description never rewrites - * the formatted one Google holds. Where either cannot be read back, as with - * a description of too many elements, only the same text is the same. - */ +// Both are read back as Markdown, so formatting Google keeps differently, such as a line break, is no change and never rewrites the formatted description. export function sameDescription( sent: string, held: string | undefined, @@ -68,7 +50,6 @@ export function sameDescription( : here === there; } -/** The access roles that may change the events of a calendar. */ export const owned = new Set(["owner", "writer"]); export function zoneOf(...names: (string | undefined)[]): string { @@ -78,7 +59,6 @@ export function zoneOf(...names: (string | undefined)[]): string { return "UTC"; } -/** A calendar as the list gives it, or nothing for one without an id. */ export function calendarOf(item: Json): CalendarInfo | undefined { const id = text(item, "id"); if (id === undefined) return undefined; @@ -109,27 +89,19 @@ export function calendarEntry(account: string, calendar: CalendarInfo): Entry { }; } -/** The link of an event row: the calendar is part of it, since one event id - * can sit on two calendars. */ +// The calendar is part of the link: one event id can sit on two calendars. export function linkOf(calendarId: string, eventId: string): string { return `${calendarId}/${eventId}`; } -/** - * A write that makes an event under the row's own id, kept in the outbound - * journal until it is answered. Until then the read leaves that event - * alone, since the write links it and a row read for it would be a second - * one. - */ +// Until answered the read leaves that event alone: the write links it, and a row read for it would be a second one. export interface Making { readonly calendarId: string; readonly eventId: string; readonly body: Readonly>; - /** The conditional update to an event found under this create's id. */ readonly patch?: { readonly fields: Readonly>; readonly etag: string | null; - /** The status read before a patch Google explicitly refused with 412. */ readonly refusedAtStatus?: string; }; } @@ -147,20 +119,12 @@ export function makingOf(request: JsonValue): Making | undefined { return request as unknown as Making; } -/** - * The change a changed occurrence made in Marfa sends to the occurrence it - * replaces, kept in the outbound journal until it lands. Until then the read - * leaves the occurrence's row alone, since Google still holds the occurrence - * as it was, which may be cancelled. - */ +// Until it lands the read leaves the occurrence's row alone: Google still holds it as it was, possibly cancelled. export interface Replacing { readonly calendarId: string; readonly seriesId: string; - /** The occurrence's own id. */ readonly eventId: string; - /** The patch, as first sent. */ readonly fields: Readonly>; - /** The version of the occurrence the patch was made against. */ readonly etag: string | null; } @@ -179,12 +143,10 @@ export function replacingOf(request: JsonValue): Replacing | undefined { return request as unknown as Replacing; } -/** The id an event row's link holds after the calendar's. */ export function eventIdOf(calendarId: string, link: string): string { return link.slice(calendarId.length + 1); } -/** The calendar a link names, and the event after it. */ export function splitLink( link: string, ): { calendarId: string; eventId: string } | undefined { @@ -207,7 +169,6 @@ export function momentOf(value: Json | undefined): Moment | undefined { return { date, dateTime, timeZone: text(value, "timeZone") }; } -/** An event Google lists, kept as it came with its few fields read. */ export interface GoogleEvent { readonly raw: Json; readonly id: string; @@ -234,17 +195,11 @@ export function eventOf(raw: Json): GoogleEvent | undefined { }; } -/** Whether an event gets a row: a working-location entry is not an - * appointment. */ export function appointment(event: GoogleEvent): boolean { return event.kind !== "workingLocation"; } -/** - * Why Marfa may not change an event, or nothing where it may. An event with - * a guest other than the account is someone else's to agree to, so Marfa - * leaves it alone even where Google would let the account change it. - */ +// An event with a guest other than the account is someone else's to agree to: Marfa leaves it alone even where Google would let the account change it. export function uneditable( event: GoogleEvent, calendar: Pick, @@ -257,7 +212,6 @@ export function uneditable( if (organizer !== undefined && flag(organizer, "self") !== true) { return "someone else organizes the event"; } - // A change would reach the guests' calendars, which Marfa does not touch. const others = list(event.raw, "attendees").some( (one) => !isJson(one) || flag(one, "self") !== true, ); @@ -295,8 +249,6 @@ const responses: ReadonlyMap = new Map([ // domain, no spaces. A guest's other address-like text is left out, not sent. const address = /^[^\s@]+@[^\s@.]+(?:\.[^\s@.]+)+$/; -/** A guest as the core `attendees` field holds it: a name and an address - * where Google gives them, and the reply. None where it has neither. */ function attendee(value: unknown): Json | undefined { if (!isJson(value)) return undefined; const email = text(value, "email"); @@ -310,8 +262,6 @@ function attendee(value: unknown): Json | undefined { return out; } -/** The times of an event, in Marfa's terms; `undefined` where Google gave - * none that can be read. */ function timesOf(event: GoogleEvent, calendar: CalendarInfo) { const start = momentOf(object(event.raw, "start")); const end = momentOf(object(event.raw, "end")); @@ -352,11 +302,7 @@ function timesOf(event: GoogleEvent, calendar: CalendarInfo) { } as const; } -/** - * The original start of a changed occurrence. A date-only one, of an all-day - * series, is the midnight of that date in the zone it names, or else in - * `zone`, which is the zone the series is read in: the calendar's. - */ +// A date-only original start of an all-day series is midnight of that date in the series' zone. export function originalStartOf( event: GoogleEvent, zone: string, @@ -373,17 +319,11 @@ export function originalStartOf( export interface Mapped { readonly entry: Entry; - /** Where the event begins, for ordering a series' cancellations. */ readonly startMs: number; readonly zone: string; } -/** - * An event as an entry of `google.calendar.event`. The times follow the - * event's own zone, or the calendar's, and an all-day event is the local - * midnights of its dates in that zone, never the zone of this process. - * Returns `undefined` for an event whose times cannot be read. - */ +// An all-day event is the local midnights of its dates in the event's own or the calendar's zone, never this process's. export function eventEntry( account: string, calendar: CalendarInfo, diff --git a/connectors/google-calendar/src/read.ts b/connectors/google-calendar/src/read.ts index 4f1f7b9d..9f2faf55 100644 --- a/connectors/google-calendar/src/read.ts +++ b/connectors/google-calendar/src/read.ts @@ -47,8 +47,7 @@ import { iso } from "./time.js"; export type Context = RunContext; type Scoped = ScopedRunContext; -/** Bumped when the way events are read changes, so that every calendar is - * read whole once more. */ +// Bumped when the way events are read changes, so every calendar is read whole once more. const version = 2; const day = 86_400_000; const horizonYears = 5; @@ -56,7 +55,6 @@ const horizonYears = 5; interface Progress { token?: string; shape: string; - /** Events still to read after their calendar's sync token advances. */ deferred?: string[]; } @@ -85,12 +83,6 @@ function linkIn(item: Item): string | undefined { return typeof link === "string" ? link : undefined; } -/** - * The account's events as Marfa holds them, by calendar, read once in a run - * and only where a step needs every row of a calendar: a whole read, a - * series that is gone and a calendar that leaves the list. A read since a - * sync token that meets none of those reads no rows. - */ class Holdings { private rows: Promise> | undefined; @@ -115,7 +107,6 @@ class Holdings { } } -/** The prefixes of the conditions a read raises. */ export const calendarChecks = [ "calendar-refused:", "calendar-unconfirmed:", @@ -125,7 +116,6 @@ export const calendarChecks = [ "read-only-calendar-unknown:", ] as const; -/** Keeps the conditions of a calendar whose events this run did not read. */ function unreachedCalendar(context: Pick, id: string): void { context.log.unreached({ keys: [ @@ -138,10 +128,7 @@ function unreachedCalendar(context: Pick, id: string): void { } interface Listed { - /** The calendars to read: those the account owns or writes to, and the - * read-only ones the connector is told to read. */ readonly chosen: Map; - /** Every calendar the list holds, whether read or not. */ readonly onList: Set; } @@ -189,17 +176,11 @@ export interface Reading { readonly now: () => number; } -/** What one run shares between its calendars. */ interface Run extends Reading { readonly holdings: Holdings; - /** The calendars Marfa held rows or progress for when the run began: the - * only ones an event can have moved from. */ readonly before: ReadonlySet; - /** Links a row was moved from during this run, so one move is not used - * twice. */ readonly claimed: Set; - /** A row Marfa refuses is kept for a retry, and the calendar's token still - * advances; the retry asks Google for the event again once it is due. */ + // A row Marfa refuses is kept for a retry and the token still advances; the retry asks Google again once due. readonly retry: { retry: { mode: "refetch"; context: string } }; } @@ -225,7 +206,6 @@ async function save( } } -/** The link a retry record names, from its link or its `source_id`. */ function refusedLink(record: PendingInbound): string { const { link, sourceId } = record.identity; if (link !== undefined) return link; @@ -233,14 +213,12 @@ function refusedLink(record: PendingInbound): string { return at === -1 ? sourceId : sourceId.slice(at + 1); } -/** Reads the account's calendars and their events into Marfa. */ export async function readCalendars(reading: Reading): Promise { const { context, api, access } = reading; const { log } = context; const listed = await api.calendars(); const { chosen, onList } = selection(listed.items, reading.named, context); if (!access.has(eventsScope)) { - // Without the events permission only the calendars themselves are read. log.unreached({ prefixes: calendarChecks.filter( (one) => one !== "read-only-calendar-unknown:", @@ -334,7 +312,6 @@ export async function readCalendars(reading: Reading): Promise { } } -/** Archives a calendar the connector no longer reads, with its events. */ async function leave(run: Run, id: string): Promise { const { context } = run; const scoped = context.forScope(`calendar:${id}`, run.retry); @@ -372,7 +349,6 @@ function shapeOf(context: Context, calendar: CalendarInfo): string { interface Plan { readonly entries: Entry[]; - /** The event id of each entry, by its link. */ readonly ids: Map; readonly archive: Set; readonly skipped: string[]; @@ -509,7 +485,6 @@ async function syncCalendar( }); } -/** The active rows Marfa holds under these links, by link. */ async function rowsOf( scoped: Scoped, links: readonly string[], @@ -526,8 +501,6 @@ async function rowsOf( ); } -/** Whether a row Marfa holds or held under one of these links, in any state, - * was a series. */ async function maybeSeries( scoped: Scoped, links: readonly string[], @@ -546,13 +519,6 @@ function recurrenceOf(row: Item | undefined): string[] { : []; } -/** - * The events of a calendar whose rows a write from Marfa still settles: an - * event it is making, which it links to its row, or deletes once the row is - * trashed or purged, and an occurrence a changed occurrence made in Marfa - * changes, which Google holds as it was, cancelled or not, until the change - * lands. The read leaves their rows alone until then. - */ function waitingOn(context: Context, calendarId: string): Set { const ids = new Set(); for (const intent of context.pendingOutbound()) { @@ -563,7 +529,6 @@ function waitingOn(context: Context, calendarId: string): Set { return ids; } -/** The cancelled occurrences of the series `id` among Google's events. */ function cancellationsOf(items: readonly Json[], id: string): Cancellation[] { return items.flatMap((raw) => { const event = eventOf(raw); @@ -696,9 +661,7 @@ async function planEvents( const seen = cancelled.get(id) ?? []; let all: Cancellation[] = seen; if (run.context.hints !== undefined) { - // The row may hold the edit this run is to send, so no cancellation is - // carried over from it: Google is asked for those of every year, once - // for the calendar, and a whole read has seen them already. + // The row may hold the edit this run sends, so no cancellation is carried over from it: Google is asked for those of every year, once per calendar. if (!whole) { inventory ??= await api.inventory(calendar.id); all = [...seen, ...cancellationsOf(inventory, id)]; @@ -736,10 +699,7 @@ async function planEvents( } for (const event of others) push(event); for (const id of dropped) plan.archive.add(linkOf(calendar.id, id)); - // A series that is gone takes its changed occurrences with it. Google's - // cancellation carries no rule, so the row says which was a series, in - // whatever state the person left it, or the retry of a series Marfa - // refused, which has none. A purged row no longer says, so it may have been. + // A series that is gone takes its changed occurrences with it. Google's cancellation carries no rule, so the row says which was a series, in any state, or a purged row may have been. const droppedLinks = [...dropped].map((id) => linkOf(calendar.id, id)); const refused = new Set( scoped.refusals.pending().map(({ record }) => refusedLink(record)), @@ -759,12 +719,6 @@ async function planEvents( return plan; } -/** - * Marks each new entry that Google moved from another calendar with the link - * it was known by there, so the row keeps its identity: Marfa holds a row for - * the same event id on a calendar read before this run, and Google no longer - * has the event there. A calendar that refuses the question is not a move. - */ async function withMoves( run: Run, scoped: Scoped, diff --git a/connectors/google-calendar/src/recurrence.ts b/connectors/google-calendar/src/recurrence.ts index 15501c57..0ee9a77f 100644 --- a/connectors/google-calendar/src/recurrence.ts +++ b/connectors/google-calendar/src/recurrence.ts @@ -1,7 +1,5 @@ import { compact, wallClockToInstant } from "./time.js"; -/** One occurrence of a series that is not held: a moment for a timed series, - * a calendar date for an all-day one. */ export type Cancellation = | { readonly kind: "instant"; readonly ms: number } | { readonly kind: "day"; readonly day: string }; @@ -10,9 +8,6 @@ const line = /^EXDATE((?:;[^:;]*)*):(.*)$/is; const dateOnly = /^(\d{4})(\d{2})(\d{2})$/; const dateTime = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(Z?)$/; -/** The occurrences a recurrence's `EXDATE` lines already remove, read as - * Marfa reads them: an instant as it is, a zoneless time in the series' - * zone, and a date as that day. A line that cannot be read removes none. */ export function removed( lines: readonly string[], zone: string, @@ -72,14 +67,8 @@ export function removed( return { instants, days }; } -/** - * Google's own `EXDATE` lines are kept as they came, and the occurrences it - * cancelled by name, which a series does not list, follow in one line of - * their own: an `EXDATE` in UTC for a timed series, since an instant is exact - * across a clock change, and `EXDATE;VALUE=DATE` for an all-day one. Nothing - * Google's lines already remove is added again, and the added dates are in - * order, so the same cancellations always give the same lines. - */ +// Google's own `EXDATE` lines are kept as they came; the occurrences it cancelled by name follow in one line of their own, +// in UTC for a timed series (an instant is exact across a clock change) and `EXDATE;VALUE=DATE` for an all-day one, in order. export function withCancellations( lines: readonly string[], cancelled: readonly Cancellation[], @@ -114,11 +103,7 @@ export function withCancellations( return [...lines, ...added]; } -/** - * What a series' recurrence removes beyond Google's own lines, which this - * connector added earlier, so a cancellation outside the window a later read - * asks Google about is not lost when the lines are made again. - */ +// Lines this connector added earlier: a cancellation outside the window a later read asks Google about is not lost when the lines are made again. export function carried( before: readonly string[], own: readonly string[], @@ -137,12 +122,9 @@ export function carried( ]; } +// An occurrence's id ends in its start. const idSuffix = /_(\d{8}T\d{6}Z|\d{8})$/; -/** - * The occurrence a cancelled or restored instance stands for: its original - * start where Google states it, else the moment its id ends with. - */ export function cancellationOf(event: { readonly id: string; readonly originalStartTime: @@ -187,7 +169,6 @@ export function cancellationOf(event: { }; } -/** The key a cancellation is compared and deduplicated by. */ export function keyOf(one: Cancellation): string { return one.kind === "instant" ? `t${String(one.ms)}` : `d${one.day}`; } diff --git a/connectors/google-calendar/src/time.ts b/connectors/google-calendar/src/time.ts index e03987f1..a0c30b1e 100644 --- a/connectors/google-calendar/src/time.ts +++ b/connectors/google-calendar/src/time.ts @@ -18,7 +18,6 @@ function formatter(zone: string): Intl.DateTimeFormat { return found; } -/** Whether the zone database resolves the name. */ export function validZone(zone: string): boolean { try { formatter(zone); @@ -28,7 +27,6 @@ export function validZone(zone: string): boolean { } } -/** Minutes the zone is ahead of UTC at the instant. */ export function offsetMinutes(zone: string, ms: number): number { const parts = new Map(); for (const part of formatter(zone).formatToParts(new Date(ms))) { @@ -54,11 +52,7 @@ export interface WallClock { readonly second: number; } -/** - * The instant a wall-clock reading shows in the zone. A time the clocks show - * twice is its first reading; a time they skip falls after the gap, as the - * clock before the change would show it. - */ +// A time the clocks show twice is its first reading; a time they skip falls after the gap. export function wallClockToInstant(zone: string, wall: WallClock): number { const naive = Date.UTC( wall.year, @@ -87,7 +81,6 @@ export function wallClockToInstant(zone: string, wall: WallClock): number { const dateShape = /^(\d{4})-(\d{2})-(\d{2})$/; -/** The instant a calendar date, as `YYYY-MM-DD`, begins in the zone. */ export function dayStart(zone: string, date: string): number | undefined { const match = dateShape.exec(date); if (match === null) return undefined; @@ -110,7 +103,6 @@ export function dayStart(zone: string, date: string): number | undefined { return wallClockToInstant(zone, wall); } -/** The calendar date after `date`, which must be a valid `YYYY-MM-DD`. */ export function nextDay(date: string): string { const match = dateShape.exec(date); const at = Date.UTC( @@ -121,17 +113,14 @@ export function nextDay(date: string): string { return new Date(at).toISOString().slice(0, 10); } -/** An instant as Marfa takes it: UTC, without fractions of a second. */ export function iso(ms: number): string { return new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z"); } -/** An instant in the compact UTC form an iCalendar date list takes. */ export function compact(ms: number): string { return iso(ms).replace(/[-:]/g, ""); } -/** The calendar date, as `YYYY-MM-DD`, the zone's clocks show at the instant. */ export function localDate(zone: string, ms: number): string { const parts = new Map(); for (const part of formatter(zone).formatToParts(new Date(ms))) { diff --git a/connectors/google-calendar/src/write.ts b/connectors/google-calendar/src/write.ts index 6ef336f0..28d70b6f 100644 --- a/connectors/google-calendar/src/write.ts +++ b/connectors/google-calendar/src/write.ts @@ -59,14 +59,11 @@ import { dayStart, iso, localDate, nextDay, validZone } from "./time.js"; export type WriteContext = WatchContext; -/** What a write needs of Google, asked once for each context the kit hands. */ interface Session { readonly api: CalendarApi; readonly account: string; readonly calendars: ReadonlyMap; readonly primary: CalendarInfo | undefined; - /** Google's answer for each calendar the listing left out, asked by id: - * nothing where it is gone. */ readonly asked: Map; } @@ -115,12 +112,7 @@ async function open(context: WriteContext, writing: Writing): Promise { }; } -/** - * A calendar of the account. One listing that leaves a calendar out doesn't - * prove it removed, so such a calendar is asked about by id, and only - * Google's answer that it is gone or deleted makes it gone. Where Google - * can't answer, nothing is decided, and the change waits for a later run. - */ +// One listing that leaves a calendar out does not prove it removed: only Google's answer that it is gone or deleted does. async function calendarFor( session: Session, calendarId: string, @@ -156,19 +148,13 @@ function linesOf(value: unknown): string[] { : []; } -/** How a condition names the row: by its title, and its Google id where it - * has one. */ function named(item: Item): string { const title = textOf(item, "title") ?? "(No title)"; const link = textOf(item, "google_id"); return link === undefined ? `"${title}"` : `"${title}" (${link})`; } -/** - * The Google id an event made from a row takes: the same for every try, so - * a create sent again after a lost answer finds what the first one made. - * Hex digits are among the base32hex ones Google takes. - */ +// The same id for every try, so a create sent again after a lost answer finds what the first made. Hex digits are base32hex ones, which Google takes. export function eventIdFor(itemId: string): string { return createHash("sha256") .update(`marfa google-calendar event\u0000${itemId}`) @@ -177,7 +163,6 @@ export function eventIdFor(itemId: string): string { const reserved = new Set(["forbiddenForNonOrganizer", "requiredAccessLevel"]); -/** What a change throws for what went wrong at Google. */ function answerFor(error: unknown, item: Item): unknown { if (error instanceof LinkTaken) return new Refused(error.message); if (!(error instanceof GoogleError)) return error; @@ -212,7 +197,6 @@ function decline(item: Item, reason: string): Declined { ); } -/** Carries a change made in Marfa to Google Calendar. */ export function carry( change: Change, context: WriteContext, @@ -221,7 +205,6 @@ export function carry( return guarded(change.item, () => carried(change, context, writing)); } -/** Makes a restored row's event live again in Google Calendar. */ export function remake( change: Change, context: WriteContext, @@ -285,8 +268,6 @@ function calendarIdOf(row: Item): string | undefined { return typeof id === "string" && id !== "" ? id : undefined; } -// --- Fields ----------------------------------------------------------------- - type Fields = Readonly>; interface Times { @@ -295,9 +276,7 @@ interface Times { readonly allDay: boolean; } -/** The row's times as Google takes them: an all-day event as its dates in - * the event's own zone, never this process's, and a timed one as instants - * with the zone beside them, which a series needs to expand. */ +// An all-day event as its dates in the event's own zone; a timed one as instants with the zone beside them, which a series needs to expand. function timesOf(item: Item, calendar: CalendarInfo): Times { const starts = Date.parse(textOf(item, "starts_at") ?? ""); if (!Number.isFinite(starts)) { @@ -340,8 +319,6 @@ const timeFields = [ "end_timezone", ] as const; -/** The row's description as Google is sent it, or `undefined` where the row - * has none. */ function descriptionOf(item: Item): string | undefined { const markdown = textOf(item, "description"); if (markdown === undefined) return undefined; @@ -373,15 +350,11 @@ function statusOf(item: Item): string { ); } -/** The status a write may send. An authorised exact word is that word. - * Anything else, including a row literal the kit did not authorise, is - * confirmed: a create and a cancelled event coming back still say so. */ +// Anything but an authorized exact word is confirmed: a create and a cancelled event coming back still say so. function sentStatus(item: Item, changed: ReadonlySet): string { return changed.has("status") ? statusOf(item) : "confirmed"; } -/** Every field Marfa sets on an event it makes or brings back. Guests are - * never among them: Marfa never invites anyone. */ function whole( item: Item, calendar: CalendarInfo, @@ -402,9 +375,7 @@ function same(a: unknown, b: unknown): boolean { return (a ?? null) === (b ?? null); } -/** The fields a change sends: only those changed in Marfa, and of them only - * what differs from the event as Google holds it, with a cleared field - * sent as `null`, which clears it in Google. */ +// A cleared field is sent as `null`, which clears it in Google. function patchOf( changed: ReadonlySet, item: Item, @@ -437,10 +408,7 @@ function patchOf( return out; } -/** The row's times as a patch to the event Google holds: a switch between - * all day and timed clears the key Google held. Where Google did not show - * the event, as when it answers a deleted one as gone, the other key is - * cleared whatever Google held. */ +// A switch between all day and timed clears the key Google held; where Google did not show the event, the other key is cleared whatever it held. function timesPatch( item: Item, raw: Json | undefined, @@ -459,12 +427,6 @@ function timesPatch( }; } -/** - * What a changed occurrence made in Marfa sends to the occurrence it - * replaces: its times, and each other field the row holds where it differs. - * A field the row does not hold keeps what the occurrence has from its - * series, and an occurrence cancelled in Google comes back. - */ function occurrencePatch( item: Item, raw: Json, @@ -497,10 +459,6 @@ function occurrencePatch( return { ...out, ...timesPatch(item, raw, calendar) }; } -// --- Answers ---------------------------------------------------------------- - -/** The row as Google left it. A series keeps the dates this connector adds - * for occurrences Google cancelled by name. */ function entryOf( session: Session, calendar: CalendarInfo, @@ -517,7 +475,6 @@ function entryOf( return eventEntry(session.account, calendar, event, lines)?.entry; } -/** The cancellations a series row holds beyond Google's own lines. */ function heldCancellations( rowLines: readonly string[], googleLines: readonly string[], @@ -529,8 +486,6 @@ function heldCancellations( }); } -// --- Create ----------------------------------------------------------------- - async function create( change: Change, context: WriteContext, @@ -571,7 +526,6 @@ async function create( ); } -/** The calendars a change draws the row to. */ function calendarsNamed(change: Change): Set { return new Set( (change.connections?.[inCalendar]?.added ?? []).flatMap((row) => { @@ -581,15 +535,6 @@ function calendarsNamed(change: Change): Set { ); } -/** - * A changed occurrence made in Marfa: a row beneath a series, naming the - * start it replaces. Google holds every occurrence of a series already, so - * the row changes that occurrence rather than making an event of its own. - * The change is kept in the outbound journal before anything is sent, with - * the occurrence's values it replaces as its baseline, so one that fails is - * settled against them, and the read leaves the occurrence's row alone until - * it lands. - */ async function replaceOccurrence( change: Change, parents: readonly Item[], @@ -664,18 +609,7 @@ async function replaceOccurrence( return replace(held, replacing, session, context, found.instance); } -/** - * Sends a journaled change of a changed occurrence made in Marfa and keeps - * it as done. The row is linked first, so an occurrence another row holds is - * refused before anything is sent. - * - * A change sent again finds the occurrence anew, cancelled or not, and - * settles each field against what Google holds now: a field at the value - * sent has landed, a field still at the value the change was made against - * is sent, and a field Google changed since keeps Google's value. What is - * sent is held to the version compared, and an occurrence cancelled in - * Google comes back, as the first try would have brought it. - */ +// A change sent again settles each field against what Google holds now: at the value sent has landed, still at the baseline is sent, changed since keeps Google's value. async function replace( held: OutboundIntent, replacing: Replacing, @@ -747,8 +681,6 @@ async function replace( return entry; } -/** An occurrence's value of a field its patch sets, as the patch compares - * it: no status is confirmed, and no title is empty. */ function heldValue(raw: Json, key: string): JsonValue { if (key === "status") return text(raw, "status") ?? "confirmed"; if (key === "summary") return text(raw, "summary") ?? ""; @@ -756,8 +688,6 @@ function heldValue(raw: Json, key: string): JsonValue { return value === undefined || value === "" ? null : (value as JsonValue); } -/** Whether an occurrence holds a field at a value, with times compared by - * their date or instant, whatever zone Google answers them in. */ function holds(raw: Json, key: string, value: JsonValue): boolean { const held = heldValue(raw, key); if (key !== "start" && key !== "end") return same(held, value); @@ -775,11 +705,6 @@ function seriesRefused(series: string, item: Item, reason: string): Refused { ); } -/** - * The occurrence of a series that a changed occurrence made in Marfa - * replaces, cancelled or not, and the series' zone, in which the row's - * times are read when it holds no zone of its own. - */ async function occurrenceFor( item: Item, original: number, @@ -828,12 +753,6 @@ async function occurrenceFor( return { instance, id, zone }; } -/** - * The write that makes the row's event under its own id. A new event has no - * occurrences to cancel one by one, so a series takes every line the row - * holds: its rules, and the dates it skips, both Google's own lines and the - * ones this connector added for occurrences Google cancelled by name. - */ function makingFor( item: Item, calendar: CalendarInfo, @@ -850,11 +769,7 @@ function makingFor( }; } -/** - * Keeps the write in the outbound journal before sending it, so a write - * whose answer is lost is sent again as it was, and the read leaves the - * event it makes alone until the row is linked to it. - */ +// Kept in the journal before sending, so a write whose answer is lost is sent again as it was. async function make( change: Change, making: Making, @@ -868,9 +783,6 @@ async function make( return settle(held, context, writing); } -/** Sends a journaled write, links the row to what it made, and keeps that - * as done. A write sent again first asks Google whether the first landed. - * The change of a changed occurrence is sent by `replace`. */ async function settle( held: OutboundIntent, context: WriteContext, @@ -912,12 +824,7 @@ async function settle( return entry; } -/** - * Makes the event under the row's own id. Google already holding that id - * means an earlier try landed and its answer was lost, so that event is - * the row's. A later authorised status edit can still apply to the value - * that first create set. A deleted event comes back with the row's values. - */ +// Google already holding the id means an earlier try landed and its answer was lost; a deleted event comes back with the row's values. async function insertOnce( held: OutboundIntent, calendar: CalendarInfo, @@ -1031,8 +938,6 @@ function startParam(one: Cancellation): string { return one.kind === "instant" ? iso(one.ms) : one.day; } -/** Google's occurrence of a series that began at the moment given, - * cancelled or not. */ async function occurrenceOf( session: Session, parts: { calendarId: string; eventId: string }, @@ -1050,8 +955,6 @@ async function occurrenceOf( }); } -// --- Update ----------------------------------------------------------------- - async function update( change: Change, parts: { calendarId: string; eventId: string }, @@ -1154,7 +1057,6 @@ async function update( return entryOf(session, calendar, current, cancelled); } -/** The calendar a change moves the event to, or nothing where it stays. */ function destinationOf(change: Change, from: string): string | undefined { const ids = calendarsNamed(change); if (ids.size > 1) { @@ -1167,14 +1069,10 @@ function destinationOf(change: Change, from: string): string | undefined { return to === undefined || to === from ? undefined : to; } -// --- Series ----------------------------------------------------------------- - interface SeriesPlan { - /** The recurrence to send, where it differs from Google's. */ readonly lines: string[] | undefined; readonly cancel: Cancellation[]; readonly restore: Cancellation[]; - /** What the row holds beyond the lines sent, once the plan has landed. */ readonly cancelled: Cancellation[]; } @@ -1182,13 +1080,6 @@ function isExdate(line: string): boolean { return /^EXDATE[;:]/i.test(line.trim()); } -/** - * What a change to a series' recurrence asks of Google. Google's own lines - * that the row still holds are kept, and the lines this connector adds for - * occurrences Google cancelled by name are never sent. A date the row - * removes beyond the lines sent cancels that occurrence, and a cancelled - * occurrence whose date the row no longer removes comes back. - */ async function planSeries( item: Item, event: GoogleEvent, @@ -1240,16 +1131,12 @@ async function planSeries( }; } -/** Whether a change asks anything of a series' rules: a change to the - * recurrence of an event that is not an occurrence. */ function rulesChanged(change: Change, event: GoogleEvent): boolean { return ( change.changed.has("recurrence") && event.recurringEventId === undefined ); } -/** The plan for a change to a series' rules, declined where it would - * cancel or bring back an occurrence Marfa may not change. */ async function checkedPlan( item: Item, event: GoogleEvent, @@ -1279,7 +1166,6 @@ function removedBy( : sent.days.has(one.day); } -/** Each occurrence a plan changes, with the status it gives it. */ function stepsOf( plan: SeriesPlan, ): [Cancellation, "cancelled" | "confirmed"][] { @@ -1289,8 +1175,6 @@ function stepsOf( ] as [Cancellation, "cancelled" | "confirmed"][]; } -/** Why Marfa may not give an occurrence a status, or nothing where it may - * or Google holds it so already. */ function stepRefused( found: Json, status: string, @@ -1301,11 +1185,6 @@ function stepRefused( return event === undefined ? undefined : uneditable(event, calendar); } -/** - * Declines a change to a series that would cancel or bring back an - * occurrence Marfa may not change, such as a changed occurrence with other - * guests, as a change to that occurrence itself is declined. - */ async function checkSeries( item: Item, plan: SeriesPlan, @@ -1330,8 +1209,6 @@ async function checkSeries( if (refused.length > 0) throw decline(item, refused.join("; ")); } -/** A cancelled occurrence the calendar's listing holds that the lookup by its - * start does not find: bringing it back waits, rather than counting as done. */ function unfound( parts: { calendarId: string; eventId: string }, one: Cancellation, @@ -1373,11 +1250,7 @@ async function applySeries( } } -// --- Trash, purge and restore ----------------------------------------------- - -/** Deletes the event in Google, while Marfa may change it. Deleting a series - * deletes its changed occurrences with it, so Marfa must be able to change - * each of those too. */ +// Deleting a series deletes its changed occurrences with it, so Marfa must be able to change each. async function remove( item: Item, parts: { calendarId: string; eventId: string }, @@ -1423,12 +1296,6 @@ async function deleteEvent( ); } -/** - * Why Marfa may not delete an event as Google holds it, or nothing where it - * may: the event's own reason, or, for a series, that of a changed - * occurrence the delete would take with it. An occurrence Google already - * holds cancelled loses nothing to the delete. - */ function deleteRefused( event: GoogleEvent, calendar: CalendarInfo, @@ -1451,15 +1318,7 @@ function deleteRefused( return undefined; } -/** - * The trash or purge of a row whose create, or making again, got no answer - * and so never linked the row. The event that write made, if it landed, is - * under the row's own id on the calendar the saved write names, so it is - * deleted there, and the write is then settled, so it is never sent again. - * Where the delete's answer is lost too, the next run asks Google again. - * A changed occurrence's change that never landed made nothing, and Google - * held the occurrence before the row, so it is settled with nothing sent. - */ +// The event a landed create made is under the row's own id on the saved write's calendar, so it is deleted there and the write settled. async function overtaken( held: OutboundIntent, context: WriteContext, @@ -1520,8 +1379,7 @@ async function remade( if (textOf(item, "recurring_event_id") !== undefined) { throw decline(item, "Google Calendar no longer has the occurrence"); } - // Google may answer a deleted event as gone while it can still bring it - // back under its own id, which keeps its link and history. + // A restore is tried for an event Google answers as gone: do not skip it. const staged = change.changed.has("recurrence"); let back: Json; try { @@ -1574,11 +1432,8 @@ async function remade( return true; } -/** Brings back a deleted event as Google held it. */ const confirmed = { status: "confirmed" }; -/** Every field Marfa sets on an event it brings back, as a patch to the - * event as Google showed it, or to one it answered as gone. */ function restoring( item: Item, calendar: CalendarInfo, @@ -1591,13 +1446,7 @@ function restoring( }; } -/** - * Sends the row's fields, and the change made in Marfa to its rules, to a - * series Google brought back as it held it. The rules are planned and - * checked as an edit's are, from the series as it came back, since Google - * may answer a deleted series as gone and so show its own lines only then; - * a declined change sends none of the row's fields. - */ +// Google may answer a deleted series as gone and show its own lines only then, so the rules are planned from the series as it came back. async function restoreSeries( change: Change, parts: { calendarId: string; eventId: string }, @@ -1643,10 +1492,7 @@ async function restoreSeries( ); } -/** Makes a split piece Google refused to bring back anew under the row's - * id, so the row's link moves to it. A refusal does not prove the restore - * never landed, so the piece is made only while Google still holds it - * deleted, and the two are never both live. */ +// A refusal does not prove the restore never landed: the piece is made only while Google still holds it deleted, so the two are never both live. async function splitAgain( change: Change, parts: { calendarId: string; eventId: string }, @@ -1666,17 +1512,11 @@ async function splitAgain( return true; } -/** Google's id for the later part of a series it split at a "this and - * following" change: the first part's id, `_R` and when the split begins. - * An id given at a create takes only lowercase letters and digits, and an - * occurrence's ends in its start alone, so no other event has one. */ +// Google's id for the later part of a split series: the first part's id, `_R` and when the split begins. +// An id given at a create takes no `_`, so no event this connector makes has one. const splitPiece = /_R\d{8}(?:T\d{6}Z?)?$/; -/** Whether Google refused to bring back a deleted split piece. Google keeps - * one only as a stub, cancelled, and answers 400 to every write that would - * restore it, so it is gone for good. A 400 for any other event stays a - * refusal: making that event anew would drop what Google holds of it and - * Marfa does not. */ +// Narrow on purpose: a 400 for any other event is a refusal, since making it anew would drop what Google holds of it. function lostSplit(error: unknown, eventId: string): boolean { return ( error instanceof GoogleError && diff --git a/connectors/google-calendar/test/calendar-stub.ts b/connectors/google-calendar/test/calendar-stub.ts index 13f3ac6c..f6e94bc8 100644 --- a/connectors/google-calendar/test/calendar-stub.ts +++ b/connectors/google-calendar/test/calendar-stub.ts @@ -12,8 +12,6 @@ export interface Call { readonly body: Json | undefined; } -/** The id Google gives the later part of a series split by a "this and - * following" change. */ const splitPiece = /_R\d{8}(?:T\d{6}Z?)?$/; interface Stored { @@ -27,19 +25,13 @@ interface Failure { readonly body?: Json; } -/** Stands in for Google's Calendar API: the calendar list and its entries, - * and the events, one event and the instances of a series, with sync tokens - * and paging, and the writes: insert under a given id, patch, delete and - * move, each held to `If-Match`. */ export class CalendarStub { readonly calls: Call[] = []; calendars: Json[] = []; - /** Calendars on the account's list that one listing leaves out. */ + // On the account's list, though one listing leaves them out. unlisted: Json[] = []; - /** How many items a page holds. */ pageSize = 2500; - /** Whether a `GET` for a cancelled event answers it as cancelled, where - * Google may answer `410` instead. */ + // Google may answer a `GET` for a cancelled event as cancelled, or `410`. getsCancelled = false; private readonly stores = new Map>(); private readonly expired = new Map(); @@ -107,7 +99,6 @@ export class CalendarStub { send(response, status, answer); } - /** The calls that change something. */ writes(): Call[] { return this.calls.filter((call) => call.method !== "GET"); } @@ -117,7 +108,6 @@ export class CalendarStub { this.losing.push(match); } - /** The event as the stub holds it. */ event(calendar: string, id: string): Json | undefined { return this.store(calendar).get(id)?.event; } @@ -141,8 +131,7 @@ export class CalendarStub { return found; } - /** An event is made or changed. A change always gets a new etag and - * `updated`, as in Google, even when given the event's old ones. */ + // A change always gets a new etag and `updated`, as in Google, even when given the event's old ones. put(calendar: string, event: Json): void { this.clock += 1; const store = this.store(calendar); @@ -159,18 +148,15 @@ export class CalendarStub { }); } - /** Time passes in Google, so the next change is later than one made in - * Marfa meanwhile. */ + // Time passes in Google, so the next change is later than one made in Marfa meanwhile. advance(seconds: number): void { this.clock += seconds; } - /** Google's `updated` for a change now: later with every change. */ private updated(): string { return new Date(Date.UTC(2026, 8, 1, 8) + this.clock * 1000).toISOString(); } - /** Google's record of a deletion: the event stays, cancelled. */ cancel(calendar: string, id: string, rest: Json = {}): void { this.clock += 1; this.store(calendar).set(id, { @@ -179,13 +165,12 @@ export class CalendarStub { }); } - /** Google has forgotten the event altogether, as it does a deletion old - * enough that no token reaches it. */ + // As Google forgets a deletion old enough that no token reaches it. forget(calendar: string, id: string): void { this.store(calendar).delete(id); } - /** A token given before now is no longer held. */ + // A token given before now is no longer held. expire(calendar: string): void { this.expired.set(calendar, this.clock); this.clock += 1; @@ -358,7 +343,6 @@ export class CalendarStub { return [200, there]; } - /** Stores a change, with a new etag and `updated`. */ private write(store: Map, event: Json): Json { this.clock += 1; const next = { @@ -370,8 +354,6 @@ export class CalendarStub { return next; } - /** The occurrences of a series that began at `start`, made up from the - * series where Google holds no instance of its own. */ private occurrences( store: Map, series: string, @@ -402,8 +384,7 @@ export class CalendarStub { return event === undefined ? undefined : { event, version: 0 }; } - /** An occurrence Google makes up from its series, which holds no instance - * of its own until it is changed, and which carries the series' fields. */ + // Google makes up an occurrence from its series, which holds no instance until it is changed. private virtual(store: Map, id: string): Json | undefined { const at = id.lastIndexOf("_"); if (at <= 0) return undefined; @@ -553,8 +534,7 @@ function refusal( ]; } -/** A patch as Google takes one: a nested object merged into the one held, - * an array in place of the one held, and null clearing a field. */ +// As Google takes a patch: a nested object is merged, an array replaces, `null` clears. function merged(held: Json, patch: Json): Json { const out: Json = { ...held }; for (const [key, value] of Object.entries(patch)) { diff --git a/connectors/google-calendar/test/read.test.ts b/connectors/google-calendar/test/read.test.ts index 82dac0d7..f17baa3f 100644 --- a/connectors/google-calendar/test/read.test.ts +++ b/connectors/google-calendar/test/read.test.ts @@ -169,7 +169,6 @@ function eventCalls(): Call[] { return calendar.calls.filter((call) => call.path.includes("/events")); } -/** The reads of every event row Marfa holds. */ function heldReads(): number { return server.requests.filter( (request) => @@ -923,8 +922,8 @@ describe("a later run", () => { state: { calendars: Record }; }; const held = kept.state.calendars[me]; - // The shape the version before this one stored for this calendar. expect(held).toBeDefined(); + // The shape the version before this one stored for this calendar. if (held !== undefined) held.shape = "cc2307c264e49b2c"; calendar.calls.length = 0; diff --git a/connectors/google-calendar/test/write.test.ts b/connectors/google-calendar/test/write.test.ts index 54e47f9c..9c952aa2 100644 --- a/connectors/google-calendar/test/write.test.ts +++ b/connectors/google-calendar/test/write.test.ts @@ -1,6 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -// The built kit, the same one the connector imports, so the errors it throws -// are the classes the run checks for. +// The built kit, the same one the connector imports, so the errors it throws are the classes the run checks for. import { mark } from "../../../kit/src/agreement.js"; import { start } from "../../../kit/dist/main.js"; import { Harness } from "../../../kit/test/harness.js"; @@ -91,8 +90,6 @@ async function once(settings: Record = {}): Promise { ); } -/** Runs the connector on its schedule, makes `change` once the first run is - * over, and waits for the run the next look starts, which must succeed. */ async function looked(change: () => void): Promise { const built = connector({ endpoints: { ...google.endpoints, api: calendar.url }, @@ -192,8 +189,6 @@ function conditions(): Record { return harness.problems(); } -/** The value the held condition asks google_calendar_confirm_deletes to - * take. */ function confirmation(): string { const held = conditions()["deletes-held"] ?? ""; const value = /google_calendar_confirm_deletes=(\S+) for one run/.exec( @@ -1372,8 +1367,6 @@ describe("a trash, restore and purge", () => { ]); }); - /** One listing of the account's calendars leaves out the team calendar, - * which Google still has. */ function unlistTeam(): void { const entry = calendar.calendars.find((one) => one["id"] === team); if (entry === undefined) throw new Error("no team calendar"); @@ -1449,7 +1442,6 @@ describe("a trash, restore and purge", () => { }); describe("a trash or purge before a lost create is settled", () => { - /** A row made in Marfa whose create Google made, with the answer lost. */ async function lost(): Promise<{ one: Row; id: string }> { await landed(); const one = made(planning); @@ -1461,7 +1453,6 @@ describe("a trash or purge before a lost create is settled", () => { return { one, id }; } - /** A row made in Marfa whose create never reached Google. */ async function failed(): Promise<{ one: Row; id: string }> { await landed(); const one = made(planning); @@ -1537,8 +1528,7 @@ describe("a trash or purge before a lost create is settled", () => { expect(server.connectorState?.["outbound"]).toBeUndefined(); expect(conditions()).toEqual({}); - // The read takes an event under that id as any other once nothing is - // making it. + // The read takes an event under that id as any other once nothing is making it. calendar.put( me, timed( @@ -2037,8 +2027,6 @@ describe("a series", () => { ["answers it as deleted", false], ] as const; - /** A series trashed and carried, then restored with its recurrence, and - * any other field given, changed before the next run, which carries all. */ async function restoredWith( getsCancelled: boolean, lines: string[], diff --git a/connectors/raindrop/live/check.ts b/connectors/raindrop/live/check.ts index e0b91a86..2694a3d6 100644 --- a/connectors/raindrop/live/check.ts +++ b/connectors/raindrop/live/check.ts @@ -27,8 +27,7 @@ const realApi = "https://api.raindrop.io/rest/v1/"; const args = new Set(process.argv.slice(2)); const selfTest = args.has("--self-test"); const cleanOnly = args.has("--clean"); -// Outside the temporary folder, which a supervisor such as heavy-run may -// delete when the run ends, taking the list clean-up needs. +// Outside the temporary folder, which a supervisor such as heavy-run may delete when the run ends, taking the list clean-up needs. const madeFile = join( homedir(), ".cache", @@ -57,7 +56,6 @@ for (const arg of args) { } } -/** Every value printed passes through here, so the token never shows. */ const secrets: string[] = []; function redact(text: string): string { let out = text; @@ -87,8 +85,6 @@ process.on("SIGINT", () => { let failures = 0; let numbered = 0; -/** One numbered statement: `ok` with its evidence, or `FAIL` with why. It - * never throws, so a failure leaves the rest of the check to run. */ async function statement( text: string, observe: () => Promise, @@ -146,8 +142,6 @@ interface Answer { body: unknown; } -/** The check's own requests to Raindrop, which go through the fence like the - * connector's and are marked as the check's. */ class Raindrop { private readonly fence: Fence; private readonly placeholder: string; @@ -212,8 +206,6 @@ class Raindrop { return answer.body; } - /** Every bookmark in a collection, page by page, or, with `pages`, the - * first pages of them. */ async all( space: number, options: { search?: string; sort?: string; pages?: number } = {}, @@ -239,8 +231,7 @@ class Raindrop { return found; } - /** The bookmarks changed last in a collection, newest first: Raindrop's - * search lags new bookmarks by minutes, a listing does not. */ + // Listed rather than searched. recent(space: number, pages: number): Promise { return this.all(space, { sort: "-lastUpdate", pages }); } @@ -265,7 +256,6 @@ class Raindrop { return [...byId.values()]; } - /** Tag names, or `undefined` where the API has no tag listing. */ async tags(): Promise { const answer = await this.send("GET", "tags"); if (answer.status === 404) return undefined; @@ -302,8 +292,7 @@ class Raindrop { } } -/** Sends a request with its path exactly as written, which `fetch` would - * resolve first, and answers its status. */ +// The path is sent exactly as written, which `fetch` would resolve first. function sendAsWritten( base: string, method: string, @@ -341,16 +330,9 @@ function sendAsWritten( const ours = (one: Bookmark): boolean => one.tags.some((name) => name.toLowerCase().startsWith(tag)); -/** How many pages, newest first, are listed where the check looks for what - * it made: its own collections, Unsorted and Trash, where the fence lets it - * put bookmarks. */ const recentPages = 10; -/** - * The bookmarks carrying the check's tag, and the collections named for it, - * found by listing, not by search: Raindrop's search can miss a bookmark made - * minutes before. Search adds what it finds. - */ +// Found by listing, not by search. async function findOurs( raindrop: Raindrop, known: readonly number[], @@ -380,23 +362,13 @@ async function findOurs( }; } -/** - * Deletes everything the check made, whatever happened before: each bookmark - * moved to Trash and deleted again until Raindrop answers 404, each - * collection deleted, Trash listed for anything left, and the tags read. - * The made-ids file is cleared only once all of it is proved gone. - */ async function cleanUp( raindrop: Raindrop, fence: Fence, made: Made, prefix: string, ): Promise { - // The check refuses to start while anything carries its tag, so a bookmark - // that does, under its own address, can only be one it made and lost the id - // of; a collection named as it names its own likewise. - // The fence's first read of the account, when it took one, rules out - // anything that was there before. + // The check refuses to start while anything carries its tag, so one that does can only be one it made and lost the id of. const adopt = async (): Promise => { let adopted = 0; const found = await findOurs(raindrop, [...made.collections]); @@ -569,8 +541,6 @@ async function cleanUp( ); } -/** The library the self-test starts the stand-in with: what the check must - * never change. */ function seed(stub: Stub): { reading: number; seeded: number; @@ -626,7 +596,6 @@ async function marfaClient(): Promise<{ } async function main(): Promise { - // What a stopped self-test made went with its stand-in. if (selfTest) rmSync(madeFile, { force: true }); const made = new Made(madeFile); let stub: Stub | undefined; @@ -668,9 +637,6 @@ async function main(): Promise { } } -/** What already carries the check's tag or is named for it. Search finds a - * bookmark tagged long ago; the ones changed last, listed, find one tagged - * in the last minutes, which search can miss. */ async function alreadyTagged( raindrop: Raindrop, ): Promise<{ tagged: Set; named: Collection[] }> { @@ -719,7 +685,6 @@ async function check( const seeded = stub === undefined ? undefined : seed(stub); const untouched = seeded?.library(); await fence.inventory(); - // A bookmark the self-test makes as the check would and loses the id of. let lost: number | undefined; const { ProofServer } = await load( "scripts/dist/proof/server.js", @@ -780,8 +745,6 @@ async function check( const pause = (seconds: number): Promise => sleep(selfTest ? 200 : seconds * 1000); - /** One `--once` run of the real connector, its settings set first. A - * run that finds the hold of one stopped before waits it out. */ const run = async ( more: Record = {}, ): Promise<{ code: number; output: string }> => { @@ -820,7 +783,6 @@ async function check( }; const tail = (output: string): string => output.trim().split("\n").slice(-6).join(" | "); - /** Runs until `settled` answers its evidence, a few runs at most. */ const runsUntil = async ( settled: () => Promise, more: Record = {}, @@ -899,7 +861,6 @@ async function check( `Live check of the Raindrop connector${selfTest ? ", self-test against the stand-in" : ""}, run ${runId}. Made ids are kept in ${made.file}.`, ); - // 1. The first import, read only. const importStart = fence.entries.length; await statement( "a first import with raindrop_read_only on brings in every bookmark, Trash included, as /user/stats and the listings count them", @@ -989,7 +950,6 @@ async function check( ); }); - // 2. Both ways, on what the check makes. const top = await raindrop.makeCollection(name("collection")); const child = await raindrop.makeCollection(name("nested"), top._id); const bin = await raindrop.makeCollection(name("binned in Marfa")); @@ -1064,7 +1024,6 @@ async function check( }), ); - // Made in Marfa. const topRow = await rowOf("collection", top._id); const childRow = await rowOf("collection", child._id); let mRow: Item | undefined; diff --git a/connectors/raindrop/live/fence.ts b/connectors/raindrop/live/fence.ts index 661b95eb..dd884332 100644 --- a/connectors/raindrop/live/fence.ts +++ b/connectors/raindrop/live/fence.ts @@ -16,20 +16,14 @@ import { import { dirname } from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; -/** Raindrop's own collection ids: every bookmark not in Trash, Unsorted and Trash. - * No write through the fence ever names one as the collection it changes. */ export const reserved: ReadonlySet = new Set([0, -1, -99]); export const unsorted = -1; export const trash = -99; -/** The ids of everything the check made in Raindrop, kept in a file as they - * are made, so a run that stops can be cleaned by `--clean`. */ export class Made { readonly file: string; readonly raindrops = new Set(); readonly collections = new Set(); - /** Creates the fence forwarded whose answer held no id, so what they made - * cannot be named. */ readonly unrecorded: string[] = []; constructor(file: string) { @@ -68,8 +62,7 @@ export class Made { this.save(); } - /** Written whole and moved into place, so a stop never leaves half a file; - * removed once nothing is left to clean. */ + // Written whole and moved into place, so a stop never leaves half a file. save(): void { if (this.empty()) { rmSync(this.file, { force: true }); @@ -89,30 +82,21 @@ export class Made { } } -/** Who sent a request: the check itself, which marks its own, or the - * connector under test. */ export type Sender = "check" | "connector"; export interface Entry { readonly sender: Sender; readonly method: string; - /** The path under the API's base, with its query. */ readonly path: string; - /** What the fence did: forwarded a read or an allowed write, refused it, - * answered 429 itself, or forwarded it and dropped the answer. */ verdict: "read" | "allowed" | "refused" | "throttled" | "dropped"; status?: number; reason?: string; - /** The `link` a `POST /raindrop` sent. */ link?: string; } export interface FenceOptions { - /** Raindrop's API base, ending in a slash. */ readonly upstream: string; - /** The token sent upstream, which never leaves the fence. */ readonly token: string; - /** What the connector and the check send instead of the token. */ readonly placeholder: string; readonly made: Made; } @@ -121,8 +105,6 @@ function isObject(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } -/** The collection a body moves or puts a bookmark in, `null` for none named, - * or `NaN` for one the fence cannot read, which no rule allows. */ function target(body: Record, key: string): number | null { if (!(key in body) || body[key] === null) return null; const value = body[key]; @@ -130,9 +112,7 @@ function target(body: Record, key: string): number | null { return typeof id === "number" && Number.isSafeInteger(id) ? id : NaN; } -/** The reads the connector and the check make, each with the query names it - * may carry. Raindrop has reads that change things, such as `GET /backup`, - * so any other read is refused. */ +// Raindrop has reads that change things, such as `GET /backup`, so any other read is refused. const reads: readonly (readonly [RegExp, readonly string[]])[] = [ [/^user$/, []], [/^user\/stats$/, []], @@ -155,8 +135,6 @@ function readable(path: string, query: URLSearchParams): boolean { ); } -/** Whether a JSON text, already parsed, names a key twice in one object, - * which parsers settle differently. */ function duplicateKey(text: string): boolean { let at = 0; const space = (): void => { @@ -205,8 +183,6 @@ function duplicateKey(text: string): boolean { return value(); } -/** A body as strict JSON reads it: UTF-8 with no byte-order mark and no key - * named twice in an object, or `undefined` for one the fence refuses. */ function strictJson(sent: Buffer): { value: unknown } | undefined { try { const text = new TextDecoder("utf-8", { @@ -220,7 +196,6 @@ function strictJson(sent: Buffer): { value: unknown } | undefined { } } -/** The ids of the bookmarks or collections a read answered. */ function idsIn(body: unknown): number[] { if (!isObject(body)) return []; const listed: unknown = body["items"]; @@ -233,7 +208,6 @@ function idsIn(body: unknown): number[] { .filter((id): id is number => typeof id === "number"); } -/** Which ids a path's answer names: bookmarks or collections. */ function kindOf(path: string): "raindrop" | "collection" | undefined { if (/^raindrops?\//.test(path)) return "raindrop"; if (/^collections?(\/|$)/.test(path)) return "collection"; @@ -250,36 +224,22 @@ const passedHeaders = [ "x-ratelimit-reset", ]; -/** - * A local proxy for Raindrop's API that lets every read through and a write - * only when it touches nothing but what the check made. It swaps the - * placeholder the connector holds for the real token, so a request that - * reaches Raindrop by any other way is refused there. - */ export class Fence { url = ""; readonly entries: Entry[] = []; - /** Every write the fence refused, which fails the check. */ readonly violations: Entry[] = []; - /** Called once an allowed write is answered upstream and before the answer - * is passed on; answering `"drop"` drops it, as a lost answer does. */ + // Called once an allowed write is answered upstream and before the answer is passed on. afterForward: ((entry: Entry) => "drop" | undefined) | undefined; private readonly options: FenceOptions; private readonly http: Server; private throttles = 0; private losses = 0; - /** Counts the fence's own events, so it can tell whether an answer that - * showed an id was whole before a create was sent. */ private tick = 0; - /** Each id a read answered, by kind, with the tick its answer ended. */ private readonly seen = { raindrop: new Map(), collection: new Map(), }; - /** When `inventory` began, on Raindrop's clock, from its `Date` header; - * `undefined` until the fence has read the whole library. */ private startedAt: number | undefined; - /** The tick `inventory` ended on. */ private inventoried: number | undefined; constructor(options: FenceOptions) { @@ -318,19 +278,14 @@ export class Fence { }); } - /** Answers the connector's next `count` requests with 429 and a - * `Retry-After`, sending none of them on. */ throttle(count: number): void { this.throttles = count; } - /** Forwards the connector's next `POST /raindrop` and drops its answer. */ loseNextCreate(): void { this.losses = 1; } - /** The writes sent through the fence since entry `from`, a search sent as - * a `POST` left out. */ writesSince(from: number, sender?: Sender): Entry[] { return this.entries .slice(from) @@ -497,7 +452,6 @@ export class Fence { res.end(bytes); } - /** Notes each id a read answered, and when, before the answer goes on. */ private note(path: string, bytes: Buffer): void { const kind = kindOf(path); if (kind === undefined) return; @@ -513,11 +467,7 @@ export class Fence { } } - /** - * Reads every bookmark and collection in the account, so a create that - * answers one of them is never taken for something the check made. Called - * once, before anything is made. - */ + // Called once, before anything is made, so a create that answers an existing id is never taken for one the check made. async inventory(): Promise { let startedAt: number | undefined; const read = async (path: string): Promise => { @@ -545,8 +495,6 @@ export class Fence { this.inventoried = this.tick; } - /** Whether the first read of the account found this bookmark or collection, - * so the check never takes it for its own. */ existedBefore(kind: "raindrop" | "collection", id: number): boolean { const at = this.seen[kind].get(id); return ( @@ -556,12 +504,7 @@ export class Fence { ); } - /** - * Keeps the id a create answered, before the answer goes on, only when it - * is new: not in the library before the create was sent, and made after - * the fence first read the library, on Raindrop's clock. An id it refuses - * or cannot judge is a violation, and is kept out of what clean-up deletes. - */ + // Kept only when new: not in the library before the create was sent, and made after the fence first read it. An id it cannot judge is a violation. private record( entry: Entry, path: string, @@ -609,8 +552,6 @@ export class Fence { this.violations.push(entry); } - /** Why a write is refused, or `undefined` when it touches only what the - * check made. */ private async judge( method: string, path: string, @@ -696,7 +637,6 @@ export class Fence { return `${method} ${path} is not a write the fence knows`; } - /** A read straight to Raindrop, for what the fence must know first. */ private async upstreamRead( path: string, ): Promise<{ body: Record; date: number | undefined }> { @@ -723,7 +663,6 @@ export class Fence { } } - /** Refuses unless every bookmark in `collections` is the check's. */ private async onlyOwnIn( collections: readonly number[], ): Promise { diff --git a/connectors/raindrop/live/test/fence.test.ts b/connectors/raindrop/live/test/fence.test.ts index bbfcd455..1d893de7 100644 --- a/connectors/raindrop/live/test/fence.test.ts +++ b/connectors/raindrop/live/test/fence.test.ts @@ -20,8 +20,6 @@ type Handler = (seen: Seen) => { headers?: Record; }; -/** A local server standing in for Raindrop, or for a host the token must - * never reach. */ async function serve(handler: Handler = () => ({})): Promise<{ url: string; seen: Seen[]; @@ -65,8 +63,6 @@ async function serve(handler: Handler = () => ({})): Promise<{ const token = "real-token-for-the-test"; const placeholder = "placeholder-for-the-test"; -/** Sends a request exactly as written, path included, which `fetch` would - * normalize. */ function send( base: string, method: string, diff --git a/connectors/raindrop/src/client.ts b/connectors/raindrop/src/client.ts index ec22c934..f32df3f9 100644 --- a/connectors/raindrop/src/client.ts +++ b/connectors/raindrop/src/client.ts @@ -1,30 +1,27 @@ import { SettingsRefused } from "@withmarfa/connector"; import type { Pacer } from "@withmarfa/connector/pacer"; -/** Raindrop's own collection ids: every bookmark but Trash, Unsorted, and Trash. */ +// Raindrop's own collection ids: 0 all but Trash, -1 Unsorted, -99 Trash. export const everything = 0; export const unsorted = -1; export const trash = -99; -/** The most bookmarks Raindrop lists on one page. */ +// Raindrop lists at most 50 bookmarks a page. export const pageSize = 50; const timeoutMs = 30_000; -/** Raindrop's answer, read where it matters; everything else is left as sent. */ export interface RaindropUser { _id: number; fullName?: string; - /** Whether the account is Pro, which permanent copies need. */ + // Permanent copies need a Pro account. pro?: boolean; groups?: { title?: string; collections?: number[] }[]; } export interface RaindropStats { - /** Bookmarks in every collection but Trash. */ all: number; trash: number; - /** When any bookmark last changed, as `/user/stats` gives it. */ changed: string | null; } @@ -39,7 +36,6 @@ export interface RaindropCollection { parent?: { $id?: number } | null; access?: { level?: number; draggable?: boolean }; collaborators?: unknown; - /** How many bookmarks it holds, its nested collections' left out. */ count?: number; created?: string; lastUpdate?: string; @@ -77,14 +73,10 @@ export interface RaindropBookmark { highlights?: RaindropHighlight[]; } -/** Raindrop answered with a status that is neither success nor one the read - * can act on, gave an answer without the shape it promises, or did not - * answer at all. A status of `undefined` is a fault to try again. */ export class RaindropFailed extends Error { constructor( readonly status: number | undefined, path: string, - /** Raindrop's own reason, where its answer gave one. */ readonly reason?: string, ) { super( @@ -97,15 +89,11 @@ export class RaindropFailed extends Error { } } -/** How a write is sent: `durable` waits out a 429 through the kit's durable - * wait and sends it again; without it a 429 throws `Unreachable` with - * `requestNotApplied`, for a write kept in the outbound journal. */ +// Without `durable` a 429 throws `Unreachable` with `requestNotApplied`, for a write kept in the outbound journal. export interface WriteOptions { readonly durable?: boolean; } -/** The address every request is made under: https, or http on this machine - * for a test, with no credentials, query or fragment, ending in a slash. */ export function endpoint(value: string): string { let url: URL; try { @@ -133,20 +121,13 @@ export interface ClientOptions { readonly base: string; readonly token: string; readonly signal: AbortSignal; - /** Every request to Raindrop goes through it: the budget, the count - * Raindrop sends and the wait a 429 asks for. */ readonly pacer: Pacer; - /** The kit's durable wait, which a pause awaits before the request goes. */ readonly waitUntil: (retryAt: string) => Promise; } -/** What `/raindrop/{id}/file` answered: the bytes, a link to them elsewhere, - * or that there is no such file. */ export type FileAnswer = { readonly bytes: Response } | { readonly link: string } | undefined; -/** Raindrop's REST API. Every request goes through `send`, so pacing is - * in one place. */ export class RaindropClient { private readonly base: string; @@ -154,14 +135,8 @@ export class RaindropClient { this.base = endpoint(options.base); } - /** - * One request through the pacer, which sends a read, or a durable write, - * again after the wait a 429 names. A 401, or a 403 on the account, is - * the token refused, which stops the run as its settings do; a 403 on - * anything else is that one thing refused. `whole` limits the whole answer, body included, to the - * time; otherwise it limits the wait for the answer's headers only, for a - * body that is a file. - */ + // A 401, or a 403 on the account, is the token refused, which stops the run; a 403 on anything else is that one thing refused. + // `whole` limits the whole answer, body included, to the time; otherwise only the wait for the answer's headers, for a body that is a file. private async send( url: URL, accept: string, @@ -220,10 +195,6 @@ export class RaindropClient { return response; } - /** - * One GET for JSON. A 404 answers `undefined` where `missing` allows it; - * any other failure throws. - */ async request( path: string, query: Readonly> = {}, @@ -237,8 +208,6 @@ export class RaindropClient { return this.answered(response, path, missing); } - /** Raindrop's JSON answer, or `undefined` for a 404 where `missing` - * allows it; any other failure throws, with Raindrop's reason. */ private async answered( response: Response, path: string, @@ -268,10 +237,6 @@ export class RaindropClient { return body; } - /** - * One write. A 404 answers `undefined`, as Raindrop answers for a - * bookmark or collection it has not got; any other failure throws. - */ async write( method: "POST" | "PUT" | "DELETE", path: string, @@ -287,7 +252,6 @@ export class RaindropClient { return this.answered(response, path, true); } - /** Makes a bookmark, as `POST /raindrop` does, and answers it. */ async createBookmark( body: Record, options: WriteOptions = {}, @@ -298,7 +262,6 @@ export class RaindropClient { ) as unknown as RaindropBookmark; } - /** Changes a bookmark, or answers `undefined` where Raindrop has none. */ async updateBookmark( id: string, body: Record, @@ -311,8 +274,7 @@ export class RaindropClient { : (itemOf(answer, path) as unknown as RaindropBookmark); } - /** Moves a bookmark to Trash, or deletes one already there for good; - * `false` where Raindrop has none. */ + // Moves a bookmark to Trash, or deletes one already there for good. async deleteBookmark(id: string): Promise { const answer = await this.write( "DELETE", @@ -321,8 +283,7 @@ export class RaindropClient { return answer !== undefined; } - /** Moves every bookmark in collection `from`, its nested collections' - * left out, to collection `to`, and answers how many Raindrop moved. */ + // Nested collections' bookmarks are left out. async moveAll(from: number, to: number): Promise { if (!Number.isSafeInteger(from) || from <= 0) { throw new Error(`${String(from)} is not a collection of the account`); @@ -335,7 +296,6 @@ export class RaindropClient { return typeof modified === "number" ? modified : 0; } - /** The ids of the bookmarks Raindrop holds under any of `urls`. */ async exists(urls: readonly string[]): Promise { const path = "import/url/exists"; const url = new URL(path, this.base); @@ -361,7 +321,6 @@ export class RaindropClient { : []; } - /** Makes a collection, as `POST /collection` does, and answers it. */ async createCollection( body: Record, options: WriteOptions = {}, @@ -372,7 +331,6 @@ export class RaindropClient { ) as unknown as RaindropCollection; } - /** Changes a collection, or answers `undefined` where Raindrop has none. */ async updateCollection( id: string, body: Record, @@ -384,8 +342,7 @@ export class RaindropClient { : (itemOf(answer, path) as unknown as RaindropCollection); } - /** Deletes a collection and those nested in it; `false` where Raindrop - * has none. */ + // Deletes the collections nested in it too. async deleteCollection(id: string): Promise { const answer = await this.write( "DELETE", @@ -394,11 +351,7 @@ export class RaindropClient { return answer !== undefined; } - /** - * The signed address a bookmark's permanent copy is kept at, or - * `undefined` where Raindrop has no copy to give. The address is for the - * storage host: it is fetched without the token. - */ + // The storage host's address is fetched without the token. async copyLink(id: string): Promise { const path = `raindrop/${encodeURIComponent(id)}/cache`; const body = await this.request(path, { json: "1" }, true); @@ -410,11 +363,7 @@ export class RaindropClient { return link; } - /** - * An uploaded file's bytes, from Raindrop with the token. The caller reads - * the body. A redirect is handed back as a link, for the caller to follow - * without the token. - */ + // A redirect is handed back as a link, for the caller to follow without the token. async file(id: string): Promise { const path = `raindrop/${encodeURIComponent(id)}/file`; const url = new URL(path, this.base); @@ -464,8 +413,7 @@ export class RaindropClient { }; } - /** The top-level collections, then every collection, top-level ones - * included: each listing alone has been seen to leave some out. */ + // Each listing alone has been seen to leave some out. async collections(): Promise { const roots = itemsOf(await this.request("collections"), "collections"); const all = itemsOf( @@ -481,7 +429,6 @@ export class RaindropClient { return [...byId.values()]; } - /** One collection, or `undefined` where Raindrop says it has none. */ async collection(id: string): Promise { const path = `collection/${encodeURIComponent(id)}`; const body = await this.request(path, {}, true); @@ -490,8 +437,6 @@ export class RaindropClient { : (found(body, path) as unknown as RaindropCollection); } - /** One page of the bookmarks in `space`, oldest first, or with `-lastUpdate` - * the one changed last first. */ async page( space: number, page: number, @@ -511,7 +456,6 @@ export class RaindropClient { .map((item) => item as unknown as RaindropBookmark); } - /** One bookmark, or `undefined` where Raindrop says it has none. */ async bookmark(id: string): Promise { const path = `raindrop/${encodeURIComponent(id)}`; const body = await this.request(path, {}, true); @@ -525,8 +469,6 @@ function isObject(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } -/** The `item` an answer holds, which Raindrop shapes as the bookmark or - * collection asked about. */ function itemOf( body: Record | undefined, path: string, @@ -538,8 +480,7 @@ function itemOf( return item; } -/** The `item` a read answered, which only a 404 may leave out: an answer - * without one is a fault, never proof that the thing is gone. */ +// An answer without an item is a fault, never proof the thing is gone. function found(body: unknown, path: string): Record { const item = isObject(body) ? body["item"] : undefined; if (!isObject(item) || typeof item["_id"] !== "number") { @@ -548,8 +489,6 @@ function found(body: unknown, path: string): Record { return item; } -/** The `items` of a listing; an answer without the list is a fault, never - * an empty page. */ function itemsOf(body: unknown, path: string): Record[] { const items = isObject(body) ? body["items"] : undefined; if (!Array.isArray(items)) { @@ -558,8 +497,7 @@ function itemsOf(body: unknown, path: string): Record[] { return items.filter(isObject); } -/** The one answer that proves Raindrop has not got a bookmark or collection: - * a 404 whose body is `{"result":false,"status":404}`. */ +// The one answer that proves Raindrop has not got it: a 404 whose body is `{"result":false,"status":404}`. function notFound(status: number, body: unknown): boolean { return ( status === 404 && diff --git a/connectors/raindrop/src/definition.ts b/connectors/raindrop/src/definition.ts index 808e98d7..1e4e8b9a 100644 --- a/connectors/raindrop/src/definition.ts +++ b/connectors/raindrop/src/definition.ts @@ -18,12 +18,8 @@ import { } from "./rows.js"; export interface Options { - /** The clock the read reads; a test sets the harness's. */ readonly now?: () => Date; - /** The clocks the pacer reads and sleeps by; a test counts waits. */ readonly clock?: PacerClock; - /** Makes a bookmark's thumbnail from its cover's address; a test or the - * proof supplies one that can reach a stand-in over http. */ readonly thumbnail?: typeof thumbnailFromAddress; } @@ -36,7 +32,6 @@ function wholeNumber(name: string, value: number): void { export function connector(options: Options = {}) { const now = options.now ?? (() => new Date()); const thumbnail = options.thumbnail ?? thumbnailFromAddress; - // One budget for the connector's life, so runs under `--every` share it. let paced: { perMinute: number; pacer: Pacer } | undefined; const pacerFor = (perMinute: number): Pacer => { if (paced?.perMinute !== perMinute) { diff --git a/connectors/raindrop/src/download.ts b/connectors/raindrop/src/download.ts index 683cfc4b..d3c499e6 100644 --- a/connectors/raindrop/src/download.ts +++ b/connectors/raindrop/src/download.ts @@ -9,19 +9,14 @@ import { RefusedAddress, } from "@withmarfa/connector/network"; -/** The wait for a storage host's answer to begin. */ const headerMs = 30_000; -/** How long a body may go without a byte before it is given up. */ const idleMs = 60_000; const maxRedirects = 3; -/** The file is larger than the limit, by what the host declared or by what - * it sent. */ export class TooLarge extends Error { override name = "TooLarge"; } -/** The storage host refused the address, as an expired signature is. */ export class StorageRefused extends Error { override name = "StorageRefused"; constructor(readonly status: number) { @@ -29,8 +24,7 @@ export class StorageRefused extends Error { } } -/** The storage host did not answer as a file is fetched. The message holds - * no address, which is signed. */ +// The message holds no address, which is signed. export class StorageFailed extends Error { override name = "StorageFailed"; } @@ -38,13 +32,7 @@ export class StorageFailed extends Error { const local = (url: URL): boolean => ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname); -/** - * The address to fetch a file from, or `undefined` for one it must not be - * fetched from: not an address, with credentials, not https (http only - * between two addresses on this machine, which a test's stand-in is), or a - * private network's literal address. `api` is the address the API is - * reached at. - */ +// Not https is refused, except between two addresses on this machine, which a test's stand-in is. export function acceptable(link: string, api: string): URL | undefined { let url: URL; let base: URL; @@ -65,7 +53,6 @@ export function acceptable(link: string, api: string): URL | undefined { export interface Fetched { readonly body: ReadableStream; - /** The `Content-Type` the host sent, without parameters, if any. */ readonly type: string | undefined; } @@ -75,7 +62,6 @@ export interface DownloadOptions { readonly signal: AbortSignal; readonly headerMs?: number; readonly idleMs?: number; - /** Told why a body ended with an error, once the caller has it. */ readonly onError?: (error: Error) => void; } @@ -100,13 +86,6 @@ function get( }); } -/** - * Starts the fetch of a file from `link`, which is not Raindrop's and gets - * no token. It follows a few redirects, each checked as the link is, and - * connects to each https host only where its name resolves to no private or - * local address. The body is a stream that ends with an error once it holds - * more than `max` bytes, or goes `idleMs` without one. - */ export async function download( link: string, options: DownloadOptions, @@ -164,10 +143,6 @@ export async function download( } } -/** - * The body of an answer that is a file, ended with an error as `download`'s - * is. A declared length over the limit is refused before a byte is read. - */ export async function received( response: Response, options: DownloadOptions, @@ -200,8 +175,6 @@ async function kept( }; } -/** The media type of a `Content-Type` value, lowercase and without its - * parameters, or `undefined` for one that is not a type. */ export function typeOf(value: string | null): string | undefined { const type = value?.split(";")[0]?.trim().toLowerCase(); return type !== undefined && @@ -210,8 +183,6 @@ export function typeOf(value: string | null): string | undefined { : undefined; } -/** `body` as it is read, ended with an error past `max` bytes or after - * `idle` milliseconds without any. */ export function limited( body: ReadableStream, max: number, diff --git a/connectors/raindrop/src/files.ts b/connectors/raindrop/src/files.ts index c4d9693d..78125aa3 100644 --- a/connectors/raindrop/src/files.ts +++ b/connectors/raindrop/src/files.ts @@ -31,24 +31,18 @@ import { } from "./rows.js"; import { pack, unpack } from "./seen.js"; -/** The scope the copies and files are written in, after the metadata, so a - * file that will not load never holds back the read's own progress. */ +// Written after the metadata, so a file that will not load never holds back the read's progress. export const filesScope = "files"; -/** The most copies and files a run fetches, and the most bytes it takes, so - * the request budget is shared with the next read. The queue holds the rest. */ +// So the request budget is shared with the next read; the queue holds the rest. export const maxLoadsPerRun = 40; export const maxBytesPerRun = 1024 ** 3; -/** The most jobs a run looks at, loaded or not. */ export const maxJobsPerRun = 200; -/** The most copies, and the most files, kept waiting in the state; past it - * the next sweep finds the rest. */ +// Past it the next sweep finds the rest. export const maxQueued = 5000; -/** The most failed tries whose wait is kept. */ const maxRetries = 500; -/** Bookmarks whose description is kept in memory between the listing and the - * job; a job past this asks Raindrop for its bookmark when it comes. */ +// A job past this asks Raindrop for its bookmark when it comes. const keptDescriptions = 2000; const halfHour = 30 * 60 * 1000; const day = 24 * 60 * 60 * 1000; @@ -71,13 +65,9 @@ export interface FilesOptions { readonly client: RaindropClient; readonly account: string; readonly now: () => Date; - /** The API's address, which a link to storage is judged against. */ readonly api: string; - /** The largest copy or file to keep, in bytes. */ readonly max: number; - /** Whether the account is Pro, where `/user` says. */ readonly pro: boolean | undefined; - /** Whether each kind is written now; a kind turned off costs no request. */ readonly copies: boolean; readonly uploads: boolean; readonly kept: FilesState | undefined; @@ -89,12 +79,10 @@ type Kind = "copy" | "file"; interface Meter { loads: number; bytes: number; - /** The entries the kit asked the bytes of. */ readonly called: Set; readonly outcome: Map; } -/** Raindrop has no copy or file to give. */ class Gone extends Error { override name = "Gone"; } @@ -105,8 +93,7 @@ const megabytes = (bytes: number): string => const keyOf = (kind: Kind, id: number): string => kind === "copy" ? copyKey(String(id)) : fileKey(String(id)); -/** Whether a property Marfa holds is the one an entry would write: times - * are compared as instants, since Marfa may write one another way. */ +// Times are compared as instants, since Marfa may write one another way. function same(held: unknown, written: unknown): boolean { if (held === written) return true; return ( @@ -130,24 +117,13 @@ const none: FileSource = { load: () => Promise.reject(new Error("not loaded")), }; -/** - * The copies and uploaded files of the bookmarks a read lists. A read offers - * each bookmark it lists, and each copy or file whose row Marfa does not - * already hold as Raindrop describes it waits, by kind, in the read's - * progress, to be done after the metadata, in its own scope, a few at a - * time, with a checkpoint after each. Every request for bytes is made inside - * the entry's `load`, so the kit asks for it only where the bytes changed, - * and a kind turned off asks for nothing. - */ +// Every request for bytes is made inside the entry's `load`, so the kit asks for it only where the bytes changed, and a kind turned off asks for nothing. export class Files { private readonly queues: Record>; private retries: Map; - /** Whether more waited than the state kept. */ private more: boolean; private readonly described = new Map(); - /** Whether the queue or the waits changed since they were last saved. */ private dirty = false; - /** The log of the scope in use, for what a load finds. */ private log: Log | undefined; private unsaved(): boolean { @@ -172,8 +148,6 @@ export class Files { return this.options.copies; } - /** Whether every copy and file kept waiting is done while more wait that - * only a sweep lists again. */ get drained(): boolean { return ( this.on && @@ -183,14 +157,11 @@ export class Files { ); } - /** Forgets that more waited than were kept, for a sweep that lists every - * bookmark again. */ relist(): void { if (this.more) this.dirty = true; this.more = false; } - /** What to keep in the read's progress. */ state(): FilesState | undefined { const kept = (kind: Kind): Set => { const ids = [...this.queues[kind]].sort((a, b) => a - b); @@ -223,8 +194,6 @@ export class Files { }; } - /** What to do for `bookmark`: raises the condition for what it will not - * keep. */ private plan(bookmark: RaindropBookmark, log: Log): Record { const id = String(bookmark._id); let copy = false; @@ -259,16 +228,12 @@ export class Files { return { copy, file }; } - /** The entry of `kind` for `item`. */ private entry(kind: Kind, item: RaindropBookmark, file: FileSource): Entry { return kind === "copy" ? copyOf(item, this.options.account, file) : fileOf(item, this.options.account, file); } - /** Queues the copy or file of each bookmark a read listed that has one to - * keep and that Marfa does not hold as Raindrop describes it. A bookmark - * in Trash has none: it follows its bookmark. */ async offer( scope: OfferScope, items: readonly RaindropBookmark[], @@ -326,8 +291,6 @@ export class Files { }); } - /** Archives the copy and file of each bookmark that went to Trash or is - * gone, and queues nothing for it. */ async follow( scope: Pick, "archive">, ids: readonly string[], @@ -342,19 +305,11 @@ export class Files { if (this.options.uploads) await scope.archive(fileType.id, ids); } - /** Raises nothing and clears nothing of what the read's own listing would - * have judged, for a read that did not list every bookmark. */ static unreached(log: Log): void { log.unreached({ prefixes: [copyLargePrefix, fileLargePrefix] }); } - /** - * Does the queued jobs that are due, up to the run's bounds, each copy and - * each file in a scope of its own. A scope whose entry could not be loaded - * does not advance, so one that failed never holds back the next. The state - * that says what is done is saved by the next scope that advances, or by the - * last, which holds no row. - */ + // A scope whose entry could not be loaded does not advance, so one that failed never holds back the next. The state that says what is done is saved by the next scope that advances, or by the last, which holds no row. async process( open: (name: string) => FilesScope, checkpoint: ( @@ -394,7 +349,6 @@ export class Files { } } - /** Saves the queue and the waits as they are now. */ private async save( scope: FilesScope, checkpoint: ( @@ -409,7 +363,6 @@ export class Files { return saved; } - /** One bookmark's copy or file, written in a scope of its own. */ private async job( kind: Kind, id: number, @@ -469,7 +422,6 @@ export class Files { if (this.retries.delete(keyOf(kind, id))) this.dirty = true; } - /** Puts a job back for a later run, after a wait that doubles. */ private fail(kind: Kind, id: number): void { const key = keyOf(kind, id); const tried = this.retries.get(key)?.n ?? 0; diff --git a/connectors/raindrop/src/journal.ts b/connectors/raindrop/src/journal.ts index 8fc957c3..7f51c9b0 100644 --- a/connectors/raindrop/src/journal.ts +++ b/connectors/raindrop/src/journal.ts @@ -7,13 +7,7 @@ import type { export type Kind = "bookmark" | "collection" | "highlight"; -/** - * A create kept in the outbound journal before it is sent, with what - * Raindrop already held that the create could be taken for, read just - * before it is kept: the bookmarks at its address, the collections of its - * title under its parent, or the highlights of its bookmark. A create whose - * answer was lost made only what is new since, so no clock is compared. - */ +// A create whose answer was lost made only what is new since this snapshot, so no clock is compared. export type Making = | { op: "create"; @@ -35,7 +29,6 @@ export type Making = before: string[]; }; -/** The delete of what a create made, under a trash that overtook it. */ export interface Undoing { op: "delete"; kind: Kind; @@ -45,9 +38,7 @@ export interface Undoing { export type Request = Making | Undoing; -/** The request a journal entry holds, or `undefined` where it is not one - * this connector keeps: a create without what was there before could take - * the owner's own for what it made. */ +// A create without what was there before could take the owner's own for what it made. export function requestOf(value: JsonValue): Request | undefined { if (typeof value !== "object" || value === null || Array.isArray(value)) { return undefined; @@ -86,9 +77,6 @@ export function highlightsMadeBy( ); } -/** Whether a kept create may have made a bookmark: one Raindrop did not - * hold before at the address it sent, with the title it sent where it - * sent one. */ export function bookmarkMadeBy( request: Extract, bookmark: RaindropBookmark, @@ -101,14 +89,12 @@ export function bookmarkMadeBy( ); } -/** The parent a collection create sent, if any. */ function parentSent( request: Extract, ): number | undefined { return (request.body["parent"] as { $id?: number } | undefined)?.$id; } -/** Whether a collection has the title and parent a create sends. */ export function sameCollection( collection: RaindropCollection, title: JsonValue | undefined, @@ -120,8 +106,6 @@ export function sameCollection( ); } -/** Whether a kept create may have made a collection: one Raindrop did not - * hold before, of the title it sent, under the parent it sent. */ export function collectionMadeBy( request: Extract, collection: RaindropCollection, @@ -132,13 +116,7 @@ export function collectionMadeBy( ); } -/** - * What the creates still waiting in the journal may have made, which a read - * leaves out: the create links its own row to it, and a read that wrote it - * first would make a second row the link could not then be set on. A - * create Raindrop refused with a 429 made nothing; what an overtaken create - * made is named by its delete. - */ +// A read leaves these out: the create links its own row to what it made, and a read that wrote it first would make a second row. A create refused with 429 made nothing. export class Unclaimed { private readonly bookmarks: Extract[] = []; private readonly collections: Extract[] = []; @@ -190,7 +168,6 @@ export class Unclaimed { ); } - /** The highlights of a bookmark a waiting create may have made. */ highlightsOf(bookmark: RaindropBookmark): Set { const ids = new Set(this.undone.get("highlight") ?? []); for (const request of this.highlights.get(String(bookmark._id)) ?? []) { diff --git a/connectors/raindrop/src/progress.ts b/connectors/raindrop/src/progress.ts index dc466b4c..4df020d8 100644 --- a/connectors/raindrop/src/progress.ts +++ b/connectors/raindrop/src/progress.ts @@ -1,7 +1,6 @@ import type { ThumbnailRefusals } from "@withmarfa/connector/thumbnails"; import { everything, trash } from "./client.js"; -/** What `/user/stats` said when a read started, and when that was. */ export interface Read { at: string; all: number; @@ -9,38 +8,22 @@ export interface Read { changed: string | null; } -/** A sweep under way: where it got to, how many bookmarks it listed, and - * the held bookmarks it passed without listing. */ export interface Sweep { started: Read; space: number; page: number; - /** Which pass of this sweep it is: one during which anything changed is - * read again. */ pass: number; - /** How many bookmarks this pass listed outside Trash and in it. */ listed: [number, number]; - /** The `created` time, in milliseconds, of the last bookmark of the last - * page read in `space`. */ cursor?: number; - /** The held bookmarks saved before `cursor` that this pass has not listed, - * packed as `pack` packs them, each asked about once the pass adds up. */ candidates: string; - /** Set where more were passed than `candidates` keeps. */ more?: true; } -/** A bookmark's copy or file waiting to be fetched, and when to try again - * where a try failed. */ export interface Retry { n: number; due: string; } -/** The ids of the bookmarks whose copy, and whose file, is still to be - * fetched, each packed as `pack` packs them, and the tries that failed, by - * the copy's or file's key. `more` is set where more waited than were kept, - * so the next sweep finds the rest. */ export interface FilesState { copies: string; uploads: string; @@ -50,19 +33,12 @@ export interface FilesState { export interface Progress { account?: string; - /** The last read that finished, a sweep or a read of what changed. */ read?: Read; - /** When the last finished sweep started. */ swept?: string; sweep?: Sweep; - /** The fields the kit wrote when the last sweep finished: one that has - * changed since, with a kind turned on, is read in full again. */ mark?: string; files?: FilesState; - /** The covers that gave no thumbnail, by bookmark. */ thumbs?: ThumbnailRefusals; - /** The bookmark whose cover had the last turn, which the next run's turns - * start after. */ thumbsCursor?: string; } @@ -143,7 +119,6 @@ function thumbsOf(value: unknown): ThumbnailRefusals | undefined { return kept; } -/** The progress without the named fields. */ export function without( progress: Progress, ...fields: (keyof Progress)[] @@ -155,8 +130,6 @@ export function without( ); } -/** What the state holds, with anything it cannot read left out, so a read - * begins again rather than trusting it. */ export function progressOf(value: unknown): Progress { if (!isObject(value)) return {}; const files = filesOf(value["files"]); diff --git a/connectors/raindrop/src/read.ts b/connectors/raindrop/src/read.ts index 151026bc..2d55b5b2 100644 --- a/connectors/raindrop/src/read.ts +++ b/connectors/raindrop/src/read.ts @@ -57,21 +57,14 @@ type Scope = Pick< | "inspect" >; -/** What one read shares between its pages: the copies and files it queues, - * and the covers it keeps for the thumbnails made after it. */ interface Shared { readonly account: string; readonly files: Files; - /** Absent where the bookmark's `thumbnail` field is not written. */ readonly covers: Covers | undefined; - /** Set for a read of only the rows Marfa named, which queues no copy or - * file. */ readonly hinted: boolean; - /** What creates still waiting may have made, which the read leaves out. */ readonly unclaimed: Unclaimed; } -/** The one read scope, so every write and checkpoint is in order. */ export const scopeName = "library"; const progressKey = "library"; @@ -81,8 +74,6 @@ export const unsettledKey = "sweep-unsettled"; export const parentMissingKey = (id: string): string => `collection-parent-missing:${id}`; -/** Whether Raindrop refused this one thing, as a 403 on a bookmark it does - * not let the token read is, rather than failed. */ function refusedOne(error: unknown): error is RaindropFailed { return ( error instanceof RaindropFailed && @@ -102,37 +93,28 @@ function readOf(at: Date, stats: RaindropStats): Read { }; } -/** How far before the last read a read of what changed reaches back, for - * clocks that differ and a change Raindrop listed late. */ +// Clocks differ and Raindrop may list a change late. export const overlap = 10 * 60 * 1000; -/** The most times a read of what changed reads again because Raindrop - * changed while it read. */ export const maxChangedPasses = 3; -/** The time a read of what changed reads back to: the earlier of when the - * last read started and Raindrop's last change then, less `overlap`. */ export function cutoffOf(last: Read): number { const at = Date.parse(last.at); const changed = last.changed === null ? Number.NaN : Date.parse(last.changed); return (Number.isNaN(changed) ? at : Math.min(at, changed)) - overlap; } -/** The bookmarks a read listed, each with the highlights it listed. */ type Listed = Map>; export interface ReadOptions { readonly client: RaindropClient; readonly now: () => Date; readonly thumbnail: typeof thumbnailFromAddress; - /** The API's address and the largest copy or file to keep. */ readonly apiUrl: string; readonly maxBytes: number; } -/** The fields each kind is written with now: a change in them, such as a - * kind turned on, is read in full, since a read of what changed would bring - * them only onto the bookmarks Raindrop changed. */ +// A change in the fields written, such as a kind turned on, is read in full, since a read of what changed would bring them only onto the bookmarks Raindrop changed. function markOf(written: (type: string) => readonly string[]): string { return JSON.stringify( [bookmarkType, collectionType, highlightType, copyType, fileType].map( @@ -141,11 +123,6 @@ function markOf(written: (type: string) => readonly string[]): string { ); } -/** - * One whole read: the account, every collection, then the bookmarks that - * changed, or every bookmark when a sweep is due, and then the copies and - * files that wait to be fetched. - */ export async function read( context: Pick< RunContext, @@ -221,9 +198,6 @@ export async function read( }); } -/** The collections, then the bookmarks that changed, or every bookmark when - * a sweep is due. Answers whether the read finished, so the copies and files - * that wait may be fetched. */ async function readLibrary( context: Pick, "log" | "written">, scope: Scope, @@ -257,8 +231,7 @@ async function readLibrary( if (due || last === undefined) { const resumed = progress.sweep !== undefined; const finished = await sweep(scope, options, shared, progress, stats, mark); - // A sweep taken up where an earlier run stopped did not list the pages - // before it, so what those pages raised stands. + // A sweep taken up where an earlier run stopped did not list the pages before it, so what those pages raised stands. if (!finished || resumed) Files.unreached(context.log); if (!finished) return false; } else { @@ -276,9 +249,7 @@ async function readLibrary( cutoffOf(last), stats, ); - // Measured from the stats it began with, so a bookmark deleted for - // good while it read still makes the next run sweep. One Raindrop - // changed under every time leaves the last read where it was. + // Measured from the stats it began with, so a bookmark deleted for good while it read still makes the next run sweep. One Raindrop changed under every time leaves the last read where it was. await save( scope, settled ? { ...progress, read: readOf(started, stats) } : progress, @@ -289,14 +260,10 @@ async function readLibrary( return true; } -/** - * Makes the thumbnails of the covers the read listed without one, and saves - * the refusals and the cursor with the progress the read saved. A thumbnail - * that cannot be made leaves the bookmark without one and is no condition. - */ async function thumbnailPass(scope: Scope, shared: Shared): Promise { const { covers } = shared; if (covers === undefined || covers.waiting.size === 0) return; + // A thumbnail that cannot be made leaves the bookmark without one and is no condition. try { const done = await makeThumbnails(covers, (id, uri, address) => scope.derive( @@ -331,7 +298,6 @@ async function thumbnailPass(scope: Scope, shared: Shared): Promise { } } -/** What the progress keeps of the covers. */ function coversOf(covers: Covers | undefined): Partial { if (covers === undefined) return {}; return { @@ -342,8 +308,6 @@ function coversOf(covers: Covers | undefined): Partial { }; } -/** Saves `progress` with what the read shares: the queue of copies and files - * and what it keeps of the covers. */ async function save( scope: Scope, progress: Progress, @@ -363,16 +327,7 @@ async function save( } } -/** - * Reads what changed since `cutoff`: each of all bookmarks and Trash from - * the bookmark changed last, a page at a time, until a page ends with one - * changed before `cutoff`. Raindrop lists a change there at once, where its - * search lags by minutes. A change during the read moves bookmarks between - * pages, which can leave one out, so a read during which `/user/stats` - * moved is read again, up to `maxChangedPasses`, writing only what is new - * or changed since it was listed. Answers whether one read began and ended - * with the same stats. - */ +// A change during the read moves bookmarks between pages, which can leave one out, so a read during which `/user/stats` moved is read again, up to `maxChangedPasses`. async function readChanged( scope: Scope, client: RaindropClient, @@ -424,13 +379,7 @@ async function readChanged( return settled; } -/** - * Reads only the rows Marfa named, such as those whose change it just - * carried: each bookmark and collection by its id, and each highlight - * through its bookmark. It takes no checkpoint and moves no cursor, since - * the rest was not read, and archives only a named row Raindrop no longer - * has. - */ +// Takes no checkpoint and moves no cursor, since the rest was not read; archives only a named row Raindrop no longer has. async function readHinted( scope: Scope, client: RaindropClient, @@ -503,8 +452,6 @@ async function readHinted( await settleHighlights(scope, listed, new Set(gone), bookmarks); } -/** What `get` answers, or `null` where Raindrop refused that one thing, - * which is then left as Marfa holds it. */ async function oneOf( scope: Scope, kind: string, @@ -522,8 +469,6 @@ async function oneOf( } } -/** Every collection, whole. One neither listing names is archived once - * Raindrop answers that it has no such collection. */ async function readCollections( scope: Scope, client: RaindropClient, @@ -585,11 +530,6 @@ async function readCollections( if (failed !== undefined) throw failed; } -/** - * Writes one page of bookmarks with their highlights, leaving out any - * `seen` holds already, and adds each to `seen` and `listed`. A bookmark in - * Trash is archived. - */ async function write( scope: Scope, shared: Shared, @@ -657,8 +597,6 @@ async function write( } } -/** The collection each of these bookmarks in Trash was in, as its row - * holds it, by the bookmark's id. */ async function heldCollections( scope: Scope, ids: readonly string[], @@ -676,7 +614,6 @@ async function heldCollections( return held; } -/** The bookmarks' entries, each with the thumbnail of its cover. */ async function withThumbnails( scope: Scope, shared: Shared, @@ -712,11 +649,6 @@ async function withThumbnails( return bookmarks.map((one) => byId.get(one.id) ?? one.entry); } -/** - * Archives each highlight whose bookmark this read listed without it, since - * a listed bookmark carries all its highlights, and each highlight of a - * bookmark in `gone`. - */ async function settleHighlights( scope: Scope, listed: Listed, @@ -747,16 +679,12 @@ async function settleHighlights( if (archive.length > 0) await scope.archive(highlightType.id, archive); } -/** The most held bookmarks a sweep keeps to ask about; past it, the sweep - * asks about these and leaves the rest to the next. */ +// Past it, the sweep asks about these and leaves the rest to the next. export const maxCandidates = 10_000; -/** The most passes a sweep makes before it gives up on one during which - * nothing changed. */ export const maxPasses = 3; -/** The most bookmarks a run asks about after passes that did not add up, - * whose shifted pages can leave out bookmarks Raindrop still holds. */ +// Passes that did not add up have shifted pages that can leave out bookmarks Raindrop still holds. export const unsettledAsks = 100; function fresh(at: Date, stats: RaindropStats, pass: number): Sweep { @@ -770,18 +698,14 @@ function fresh(at: Date, stats: RaindropStats, pass: number): Sweep { }; } -/** A held bookmark as a sweep weighs it. */ interface HeldBookmark { readonly id: string; readonly active: boolean; readonly space: number; - /** When it was saved, in milliseconds, or `Infinity` where its row says - * not, so it is weighed only once its space is read to the end. */ + // `Infinity` where its row says not, so it is weighed only once its space is read to the end. readonly saved: number; } -/** What a sweep reads of Marfa once a run: the held bookmarks of each space, - * oldest first, and the active highlights of each bookmark. */ interface Ledger { readonly spaces: ReadonlyMap; readonly highlights: Map>; @@ -826,9 +750,6 @@ async function ledgerOf(scope: Scope): Promise { return { spaces, highlights }; } -/** Archives the highlights `ledger` holds active for each bookmark in - * `listed` that its listing left out, and every one of each bookmark in - * `gone`. */ async function settle( scope: Scope, ledger: Ledger, @@ -854,18 +775,7 @@ async function settle( if (archive.length > 0) await scope.archive(highlightType.id, archive); } -/** - * Reads every bookmark, in Trash too, oldest first, saving its place after - * each page and taking it up a page early after a stop. Each page settles - * its bookmarks' highlights at once. A held bookmark the listing passed - * without naming is kept to ask about, and archived where Raindrop answers - * that it has none, which proves it gone whatever the pass found. A pass - * during which `/user/stats` moved, or whose count differs from it, is read - * again, up to `maxPasses`, and only one that adds up finishes the sweep. - * After one that adds up, every kept bookmark is asked about; after one - * that does not, at most `unsettledAsks` in the run. A pass taken up after - * a stop is measured from the stats at this run's start. - */ +// A held bookmark the listing passed without naming is asked about and archived where Raindrop answers it has none. A pass during which `/user/stats` moved, or whose count differs from it, is read again. async function sweep( scope: Scope, { client, now }: ReadOptions, @@ -876,8 +786,7 @@ async function sweep( ): Promise { let current = progress.sweep ?? fresh(now(), stats, 0); let resumed = progress.sweep !== undefined; - // What the settle check compares against: the pass's start, or for a pass - // taken up after a stop, this run's start. + // What the settle check compares against: the pass's start, or for a pass taken up after a stop, this run's start. let baseline: Read = resumed ? readOf(now(), stats) : current.started; let asks = unsettledAsks; const goneAll = new Set(); @@ -897,8 +806,6 @@ async function sweep( if (candidates.size < maxCandidates) candidates.add(Number(id)); else more = true; }; - /** Asks Raindrop about each of `ids`, archives each it has not got and - * writes each it has; answers the failure that stopped it, if any. */ const ask = async (ids: readonly number[]): Promise => { const gone: string[] = []; const answered: RaindropBookmark[] = []; @@ -935,7 +842,6 @@ async function sweep( } return failed; }; - /** Saves where the sweep is and throws `failed`. */ const stop = async (failed: Error): Promise => { keep(); await save(scope, { ...progress, sweep: current }, shared); @@ -1056,8 +962,6 @@ async function sweep( const failed = await ask([...candidates].sort((a, b) => a - b)); if (shared.covers !== undefined) { - // What Marfa held when the sweep began and what it listed since, less - // what Raindrop deleted for good. const keep = new Set([ ...[...ledger.spaces.values()].flatMap((list) => list.map((one) => one.id), diff --git a/connectors/raindrop/src/rows.ts b/connectors/raindrop/src/rows.ts index d05e2ccc..a1bb33b9 100644 --- a/connectors/raindrop/src/rows.ts +++ b/connectors/raindrop/src/rows.ts @@ -12,8 +12,7 @@ import copyJson from "./raindrop.copy.json" with { type: "json" }; import fileJson from "./raindrop.file.json" with { type: "json" }; import highlightJson from "./raindrop.highlight.json" with { type: "json" }; -// Imported JSON widens every string; the kit holds each file to the -// server's shape when it starts. +// Imported JSON widens every string; the kit holds each file to the server's shape when it starts. export const bookmarkType = bookmarkJson as TypeDefinition; export const collectionType = collectionJson as TypeDefinition; export const highlightType = highlightJson as TypeDefinition; @@ -27,7 +26,6 @@ export const attachedTo = "attached-to"; export const untitledCollection = "Untitled collection"; -/** Every highlight color Raindrop takes. */ export const raindropColors = new Set([ "blue", "brown", @@ -43,8 +41,7 @@ export const raindropColors = new Set([ "yellow", ]); -/** The colors `core.highlight` holds; Raindrop's other six live only in - * `raindrop_color`. */ +// Raindrop's other six colors live only in `raindrop_color`. export const coreColors = new Set([ "yellow", "blue", @@ -64,12 +61,9 @@ export interface Bookmark { readonly space: number; readonly entry: Entry; readonly highlights: readonly Entry[]; - /** Highlights Raindrop sent without a passage, which no row can hold. */ readonly blank: number; } -/** A link the `url` kind takes: an absolute address, trimmed, without tab - * or line breaks. */ export function urlValue(text: string): string | undefined { const trimmed = text.trim().replace(/[\t\n\r]/g, ""); return URL.canParse(trimmed) ? trimmed : undefined; @@ -91,8 +85,6 @@ function time(value: unknown): string | undefined { : undefined; } -/** Sets `field` to the link `value` holds, or keeps `value` as sent under - * `originals` where the `url` kind would refuse it. */ function link( properties: Record, originals: Record, @@ -116,10 +108,6 @@ export function spaceOf(bookmark: RaindropBookmark): number { return typeof id === "number" ? id : unsorted; } -/** - * The bookmark's entry. `wasIn` is the collection a bookmark in Trash was in - * before, as its row holds it, since Raindrop no longer names it. - */ export function bookmarkOf( bookmark: RaindropBookmark, account: string, @@ -158,8 +146,7 @@ export function bookmarkOf( if (Object.keys(originals).length > 0) { properties["original_values"] = originals; } - // A bookmark in Trash keeps the collection it had, which Raindrop no - // longer names; one in Unsorted is in none. + // A bookmark in Trash keeps the collection it had, which Raindrop no longer names. const connections: Record = {}; if (space !== trash) { connections[inCollection] = @@ -196,19 +183,16 @@ const attachment = (id: string): Entry["connections"] => ({ [attachedTo]: [{ type: bookmarkType.id, id }], }); -/** What names a bookmark to a person: its title, else its address. */ export function nameOf(bookmark: RaindropBookmark): string { return text(bookmark.title) ?? text(bookmark.link) ?? "a bookmark"; } -/** The key of a permanent copy's bytes: they change when Raindrop makes the - * copy again, or when its size does. */ +// The bytes change when Raindrop makes the copy again, or when its size does. export function copyBytesKey(bookmark: RaindropBookmark): string { return `${bookmark.cache?.created ?? ""}:${String(bookmark.cache?.size ?? "")}`; } -/** The key of an uploaded file's bytes: its name and size. Not `lastUpdate`, - * which every edit of the bookmark, a tag included, moves. */ +// Not `lastUpdate`, which every edit of the bookmark, a tag included, moves. export function fileBytesKey(bookmark: RaindropBookmark): string { return `${bookmark.file?.name ?? ""}:${String(bookmark.file?.size ?? "")}`; } @@ -285,8 +269,6 @@ export function highlightOf( }; } -/** Where a top-level collection sits in the sidebar: its place in its group - * and the group's title. */ export type Placement = ReadonlyMap< number, { position: number; group?: string } @@ -309,11 +291,6 @@ export function placementOf( return placed; } -/** - * The collection's entry, under its parent where Raindrop names one this - * read holds. `orphaned` is set where the parent is named and missing, and - * the collection then sits at the top level. - */ export function collectionOf( collection: RaindropCollection, account: string, diff --git a/connectors/raindrop/src/seen.ts b/connectors/raindrop/src/seen.ts index 81397f84..2460e56b 100644 --- a/connectors/raindrop/src/seen.ts +++ b/connectors/raindrop/src/seen.ts @@ -1,17 +1,9 @@ import { deflateSync, inflateSync } from "node:zlib"; -/** - * The most a packed set may take in the connector's state. The state holds - * 512 KiB in all, and the rest of what it keeps is small. - */ +// The state holds 512 KiB in all. export const maxPackedLength = 384 * 1024; -/** - * A set of Raindrop's numeric ids, kept compactly: sorted, each written as - * its distance from the one before in base-128 varints, deflated, then - * base64. A library of 100,000 bookmarks takes a few hundred kilobytes at - * most. `undefined` where the set is too large to keep. - */ +// Sorted ids as base-128 varint distances, deflated, then base64. `undefined` where the set is too large to keep. export function pack(ids: ReadonlySet): string | undefined { const sorted = [...ids].filter((id) => Number.isSafeInteger(id) && id >= 0); sorted.sort((a, b) => a - b); @@ -30,7 +22,6 @@ export function pack(ids: ReadonlySet): string | undefined { return packed.length > maxPackedLength ? undefined : packed; } -/** The set `pack` made, or an empty one from anything else. */ export function unpack(value: unknown): Set { const ids = new Set(); if (typeof value !== "string" || value.length > maxPackedLength) return ids; diff --git a/connectors/raindrop/src/settings.ts b/connectors/raindrop/src/settings.ts index ae07fcd1..792100aa 100644 --- a/connectors/raindrop/src/settings.ts +++ b/connectors/raindrop/src/settings.ts @@ -2,7 +2,6 @@ import type { SettingsDeclaration } from "@withmarfa/connector"; const defaultApiUrl = "https://api.raindrop.io/rest/v1/"; const defaultRequestsPerMinute = 60; -/** 300 MiB, as large as Raindrop lets a Pro account upload. */ const defaultFileMaxBytes = 314_572_800; export const settings = [ diff --git a/connectors/raindrop/src/thumbnails.ts b/connectors/raindrop/src/thumbnails.ts index a3245cc5..a92500cf 100644 --- a/connectors/raindrop/src/thumbnails.ts +++ b/connectors/raindrop/src/thumbnails.ts @@ -9,39 +9,28 @@ import { type ThumbnailRefusals, } from "@withmarfa/connector/thumbnails"; -/** Covers fetched at once. */ const pool = 4; -/** The most covers a run asks for, so a first read of a large library shares - * its time with the rest of the run. */ +// So a first read of a large library shares its time with the rest of the run. export const coversPerRun = 500; -/** Failures that may pass, from one host, before it is left alone this run. */ +// Failures that may pass, from one host, before it is left alone this run. const hostFailures = 3; export interface Cover { readonly id: string; readonly entry: Entry; - /** In Trash: a thumbnail is kept, never made. */ readonly trashed: boolean; } -/** What one run keeps of the covers: the refusals, the cursor of the turns, - * and the covers it listed that are still to be made. */ export interface Covers { readonly make: typeof thumbnailFromAddress; readonly signal: AbortSignal; readonly now: () => Date; readonly refusals: ThumbnailRefusals; - /** The bookmark the last turn was given to, kept for the next run. */ cursor: string | undefined; - /** By bookmark: the cover's address and the thumbnail the row holds. */ readonly waiting: Map; } -/** - * Puts in each bookmark's entry the thumbnail its row holds while it was made - * from the entry's `image_url`, since an entry without one clears it, and - * keeps each cover without its thumbnail to be made after the read. - */ +// An entry without `image_url` clears the thumbnail, so each entry carries the one its row holds. export function heldThumbnails( covers: Covers, list: readonly Cover[], @@ -67,14 +56,6 @@ export function heldThumbnails( }); } -/** - * Makes the thumbnails of the covers the read kept waiting, in the kit's - * turns from the cursor, so covers behind many that are refused still have - * their turn, and hands each one made to `write` with the address it was - * made from, to write only to a row that still holds it. A cover is not fetched - * where a refusal is kept for its address, or the run's budget, or its - * host's, is spent. One that cannot give a thumbnail raises no condition. - */ export async function makeThumbnails( covers: Covers, write: (id: string, uri: string, address: string) => Promise, diff --git a/connectors/raindrop/src/write.ts b/connectors/raindrop/src/write.ts index dc91adad..92978d89 100644 --- a/connectors/raindrop/src/write.ts +++ b/connectors/raindrop/src/write.ts @@ -52,33 +52,28 @@ import type { settings } from "./settings.js"; export type WriteContext = WatchContext; -/** What a write needs from the connector: the shared pacer. */ export interface Writing { readonly pacerFor: (perMinute: number) => Pacer; } -/** The most characters Raindrop keeps in each bookmark field. */ +// The most characters Raindrop keeps in each bookmark field. export const limits = { title: 1000, excerpt: 10_000, note: 10_000 } as const; -/** Tags Marfa keeps for itself, never sent to Raindrop as tags. */ +// Tags Marfa keeps for itself, never sent to Raindrop as tags and never removed from it. const ownTags = new Set(["favorite", "conflicted-copy"]); -/** What a write needs of Raindrop, asked once for each context. */ interface Session { readonly client: RaindropClient; user(): Promise; account(): Promise; - /** The token's account, once checked against the one the connector keeps; - * throws where they differ, so no write reaches the wrong account. */ + // Throws where the token's account differs from the one the connector keeps, so no write reaches the wrong account. checked(): Promise; collections(): Promise; - /** Forgets the collections, after a write that changes them. */ forget(): void; } const sessions = new WeakMap(); -/** Where the read keeps the account it first read. */ const keptAccount = "library"; function sessionFor(context: WriteContext, writing: Writing): Session { @@ -127,14 +122,11 @@ function sessionFor(context: WriteContext, writing: Writing): Session { return session; } -// --- Reading the row -------------------------------------------------------- - function textOf(item: Item, key: string): string | undefined { const value = item.properties[key]; return typeof value === "string" && value !== "" ? value : undefined; } -/** How a condition names the row: its title and Raindrop id. */ function named(item: Item): string { const title = textOf(item, "title") ?? textOf(item, "text")?.slice(0, 60) ?? item.id; @@ -145,7 +137,6 @@ function named(item: Item): string { return link === undefined ? `"${title}"` : `"${title}" (${link})`; } -/** The Raindrop ids of the rows a connection names, in order. */ function linksOf(items: readonly Item[] | undefined, field: string): number[] { const ids: number[] = []; for (const one of items ?? []) { @@ -155,8 +146,6 @@ function linksOf(items: readonly Item[] | undefined, field: string): number[] { return ids; } -/** Throws where the row was read from another Raindrop account than the - * token's, so nothing is changed in the wrong account. */ async function sameAccount(item: Item, session: Session): Promise { const held = textOf(item, "raindrop_account"); if (held === undefined) return; @@ -168,9 +157,6 @@ async function sameAccount(item: Item, session: Session): Promise { } } -// --- Errors ----------------------------------------------------------------- - -/** What a change throws for what went wrong at Raindrop. */ function answerFor(error: unknown): unknown { if (error instanceof LinkTaken) return new Refused(error.message); if (!(error instanceof RaindropFailed)) return error; @@ -201,9 +187,6 @@ function gone(item: Item): Refused { ); } -// --- Entry points ----------------------------------------------------------- - -/** Carries a change made in Marfa to Raindrop. */ export function carry( change: Change, context: WriteContext, @@ -212,7 +195,6 @@ export function carry( return guarded(() => carried(change, context, sessionFor(context, writing))); } -/** Makes a restored row again where Raindrop no longer has it. */ export function remake( change: Change, context: WriteContext, @@ -251,8 +233,7 @@ async function carried( const what = kindOf(item); const link = textOf(item, linkField[what]); if (link === undefined) { - // Every create is journaled first, so a trash with nothing held has - // nothing to delete. + // Every create is journaled first, so a trash with nothing held has nothing to delete. return deleting ? undefined : create(change, context, session); } switch (what) { @@ -327,15 +308,12 @@ async function remade( } } -// --- The journal ------------------------------------------------------------ - function unknownRequest(item: Item): Refused { return new Refused( `The write kept for ${named(item)} is not one this connector makes`, ); } -/** Keeps the create in the outbound journal, then sends it. */ async function make( change: Change, making: Making, @@ -349,13 +327,7 @@ async function make( return settle(held, change, context, session, true); } -/** - * Sends a journaled create, links the row to what it made and keeps that as - * done. One kept before this call may have been sent with its answer lost, - * so it first looks for what it made in Raindrop, which takes no idempotency - * key; one Raindrop refused with a 429 made nothing, so it is sent again - * without looking, with what Raindrop holds read again first. - */ +// Raindrop takes no idempotency key, so a create kept before may have been sent: look for what it made first. One refused with 429 made nothing and is sent again without looking. async function settle( held: OutboundIntent, change: Change, @@ -401,14 +373,11 @@ async function settle( return entry; } -/** What a create made: Raindrop's id for it and its entry. */ interface Made { readonly id: string; readonly entry: Entry; } -/** Sends a create once. A 429 throws `Unreachable` marked as not applied, - * since the journal sends it again. */ async function send(request: Making, session: Session): Promise { const { client } = session; const account = await session.account(); @@ -460,13 +429,7 @@ function highlightMade( return { id: made._id, entry }; } -/** - * What a create may have made: a bookmark at the address it sent, with the - * title it sent; a collection of the title it sent under the parent it - * sent; a highlight with the text, note and color it sent. Each is matched - * to the request as it was kept when sent, never to the row as it is now, - * and only one Raindrop did not hold before the create was kept counts. - */ +// Each is matched to the request as it was kept when sent, never to the row as it is now, and only one Raindrop did not hold before the create counts. async function candidates(request: Making, session: Session): Promise { const { client } = session; const account = await session.account(); @@ -510,9 +473,6 @@ async function candidates(request: Making, session: Session): Promise { } } -/** The ids of what Raindrop holds now that a create could be taken for, - * read just before the create is kept or sent again. The collections are - * the session's, which the caller reads fresh. */ async function heldBefore( kind: "bookmark" | "collection", body: Record, @@ -534,8 +494,6 @@ async function heldBefore( } } -/** The create with what Raindrop holds read again, for a create sent again - * after Raindrop refused it with a 429. */ async function readBefore(request: Making, session: Session): Promise { if (request.kind !== "highlight") { session.forget(); @@ -556,11 +514,7 @@ async function readBefore(request: Making, session: Session): Promise { }; } -/** - * What a create whose answer was lost made, where that is proven: the one - * candidate. Where none matches, the create made nothing. Where more than - * one does, it may be the owner's, so it throws and changes nothing. - */ +// Where more than one candidate matches, it may be the owner's: throw and change nothing. async function recovered( item: Item, request: Making, @@ -577,7 +531,6 @@ async function recovered( ); } -/** The condition for a create Marfa cannot match to one thing it made. */ function unsure( item: Item, request: Making, @@ -594,13 +547,7 @@ function unsure( ); } -/** - * The trash or purge of a row whose create got no answer and so never - * linked the row. What the create made, if it landed, is found as a create - * sent again finds it, and deleted, and the create is then settled, so it - * is never sent again. Raindrop's own Trash keeps a bookmark it deleted, so - * the next read brings it in as an archived row. - */ +// Raindrop's own Trash keeps a bookmark it deleted, so the next read brings it in as an archived row. async function overtaken( held: OutboundIntent, change: Change, @@ -724,10 +671,6 @@ async function create( } } -// --- Bookmarks -------------------------------------------------------------- - -/** Text for a Raindrop field, refused where it is longer than Raindrop - * keeps, never cut. */ function limited( item: Item, field: keyof typeof limits, @@ -741,7 +684,6 @@ function limited( return value; } -/** The Raindrop fields of the row's `fields`, as Raindrop takes them. */ function bookmarkFields( item: Item, fields: Iterable, @@ -787,8 +729,6 @@ const bookmarkWritten = [ "reminder_at", ]; -/** The create of a bookmark in `collection`, with the tags and favorite the - * row holds, which a create or remake is handed. */ async function bookmarkMaking( item: Item, collection: number, @@ -819,13 +759,7 @@ async function bookmarkMaking( }; } -/** - * The collection a change puts the bookmark in: the one it is in, less those - * removed, plus those added. A bookmark sits in one collection, so where that - * leaves more than one, the first one added wins over the one it was in, the - * rest are taken back by the answer, and a condition says so; where it leaves - * none, Unsorted. - */ +// A bookmark sits in one collection: where a change leaves more than one, the first added wins and a condition says so. function movedTo( change: Change, current: number, @@ -845,8 +779,6 @@ function movedTo( return all[0] ?? unsorted; } -/** Declines a change to a bookmark in a collection the account can only - * view. */ async function viewOnly( item: Item, collection: number, @@ -865,8 +797,6 @@ async function viewOnly( } } -/** Where a restored bookmark goes: the collection drawn in Marfa, else the - * one it was in, else Unsorted, where that collection is gone. */ async function restoredTo( change: Change, item: Item, @@ -898,13 +828,7 @@ function bookmarkEntry( ).entry; } -/** - * Moves a bookmark to Raindrop's Trash with `PUT /raindrop/{id}`, which - * leaves one already there as it is, so a bookmark moved there meanwhile is - * never deleted for good. Only a purge with `raindrop_purge_deletes` on - * sends `DELETE`, and only to a bookmark in Trash. Answers the bookmark as - * the write left it, or `undefined` where Raindrop no longer has it. - */ +// `PUT` leaves a bookmark already in Trash as it is, so one moved there meanwhile is never deleted for good. async function toTrash( link: string, current: RaindropBookmark, @@ -925,21 +849,12 @@ async function toTrash( return after; } -/** The answer to an update of many bookmarks: how many Raindrop changed. */ function modifiedOf(answer: Record | undefined): number { const modified = answer?.["modified"]; return typeof modified === "number" ? modified : 0; } -/** - * Carries the tags added and removed in Marfa to Raindrop's own list, which - * may hold tags Marfa has not read yet. Tags only added go with Raindrop's - * "update many raindrops", which appends them. A removal reads the list just - * before it writes it back without the removed tags, keeping every other one, - * then reads it again to check. A tag literally named `favorite` or - * `conflicted-copy` in Raindrop is never removed, since Marfa holds those - * names for itself. Answers the bookmark as Raindrop then holds it. - */ +// Tags only added go with update-many, which appends them. A removal reads the list just before writing it back, since it may hold tags Marfa has not read yet, then reads it again to check. async function carryTags( item: Item, link: string, @@ -1061,10 +976,6 @@ async function carriedBookmark( return bookmarkEntry(after, account, wasIn); } -// --- Collections ------------------------------------------------------------ - -/** The collection a create or remake goes under: the parent drawn in Marfa, - * by the link Raindrop gave it, which a parent made again just now holds. */ function parentOf(change: Change): number | undefined { return linksOf(change.connections?.[childOf]?.added, "collection_id")[0]; } @@ -1113,7 +1024,6 @@ async function collectionEntry( ).entry; } -/** Declines a change to a collection the account does not own. */ function owned(item: Item, collection: RaindropCollection): void { const level = collection.access?.level; if (typeof level === "number" && level < 4) { @@ -1121,7 +1031,6 @@ function owned(item: Item, collection: RaindropCollection): void { } } -/** The collections nested in `id`, at every depth. */ function descendantsOf( id: number, collections: readonly RaindropCollection[], @@ -1185,12 +1094,8 @@ async function carriedCollection( return collectionEntry(after, session); } -/** How many times a collection is emptied before it is given up on for - * this run, where bookmarks keep arriving in it. */ const emptyingRounds = 3; -/** The bookmarks Raindrop lists in a collection and every collection nested - * in it, the first page of them, read fresh. */ async function leftIn( id: number, session: Session, @@ -1215,15 +1120,7 @@ async function leftIn( ); } -/** - * Deletes a collection and those nested in it. Raindrop's own delete sends - * their bookmarks to Trash, so each is first emptied into Unsorted: the - * nested collections are read fresh, each is emptied, and just before the - * delete the collection and all nested in it, listed or not, are checked - * empty. One found holding a bookmark is emptied again; after a few rounds - * the delete waits for a later run. A bookmark moved in between that check - * and the delete still goes to Raindrop's Trash, where it is kept. - */ +// Raindrop's own delete sends nested bookmarks to Trash, so each is emptied into Unsorted first and the whole checked empty just before the delete. A bookmark moved in between still goes to Trash, where it is kept. async function deleteCollection( item: Item, id: number, @@ -1261,11 +1158,6 @@ async function deleteCollection( ); } -// --- Highlights ------------------------------------------------------------- - -/** The Raindrop id of the bookmark a highlight is on: the connection a create - * or a remake is handed, where Marfa holds the highlight, or the bookmark - * the highlight was read on, which a purge keeps when its edges are gone. */ function bookmarkOfHighlight(change: Change): string | undefined { const rows = change.connections?.[excerptOf]?.added ?? change.placement?.[excerptOf]; @@ -1276,8 +1168,6 @@ function bookmarkOfHighlight(change: Change): string | undefined { return textOf(change.item, "raindrop_bookmark"); } -/** The color Raindrop takes for the row: its Raindrop color where set, which - * holds all twelve, else its core one. */ function colorOf(item: Item, fields: ReadonlySet): string | undefined { const raindrop = textOf(item, "raindrop_color"); if (fields.has("raindrop_color") && raindrop !== undefined) { @@ -1363,8 +1253,6 @@ async function carriedHighlight( return highlightOf(now, bookmark, await session.account()); } -// --- The delete hold --------------------------------------------------------- - interface Deleting { readonly id: string; readonly takes?: string[]; @@ -1372,9 +1260,6 @@ interface Deleting { readonly operation: Operation; } -/** How Raindrop deletes a thing: a bookmark moved to its Trash or deleted - * for good from there, a collection deleted, a highlight removed from its - * bookmark. */ type Operation = "trash" | "purge" | "collection delete" | "highlight removal"; function operationOf( @@ -1392,17 +1277,14 @@ function operationOf( } } -/** A delete the batch may send, before Raindrop's state is read. */ interface Planned { readonly delete: Deleting; - /** The bookmark to read fresh, which decides whether it deletes at all. */ readonly bookmark?: { readonly link: string; readonly purge: boolean }; } -/** More than this many, and more than a quarter of a whole, is held. */ +// More than this many, and more than a quarter of a whole, is held. const holdLimit = 20; -/** How many bookmarks Unsorted and Trash hold, and the library in all. */ async function counts( session: Session, ): Promise<{ all: number; unsorted: number; trash: number }> { @@ -1416,18 +1298,7 @@ async function counts( return { all: count(0), unsorted: count(unsorted), trash: count(trash) }; } -/** - * Holds a batch of trashes and purges that would delete more than 20 - * bookmarks, collections and highlights in Raindrop and more than a quarter - * of the library, or more than 20 bookmarks and more than a quarter of one - * collection, unless `raindrop_confirm_deletes` names that batch. It counts - * what Raindrop holds now: each bookmark is read fresh, so one already in - * Raindrop's Trash counts only where a purge deletes it for good, and one - * Raindrop no longer has counts not at all. A collection counts with every - * collection nested in it, which Raindrop's delete takes too, as does the - * collection a lost create made, which the trash of its row deletes. A - * bookmark Raindrop answers 403 for counts in the library as a whole. - */ +// Counts what Raindrop holds now: a bookmark already in Trash counts only where a purge deletes it for good, one Raindrop no longer has not at all, and a collection with every collection nested in it. A bookmark Raindrop answers 403 for counts in the library as a whole. export async function preflight( inventory: { readonly purges: readonly Change[]; @@ -1534,7 +1405,6 @@ export async function preflight( } return; } - // Each bookmark as Raindrop holds it now, and the collection it is in. const library: Deleting[] = []; const bySpace = new Map(); for (const one of planned) { @@ -1546,8 +1416,7 @@ export async function preflight( try { found = await client.bookmark(one.bookmark.link); } catch (error) { - // Raindrop refused this one bookmark: it counts in the library, and its - // own carry is refused. + // Raindrop refused this one bookmark: it counts in the library, and its own carry is refused. if (!(error instanceof RaindropFailed && error.status === 403)) { throw error; } diff --git a/connectors/raindrop/test/files.test.ts b/connectors/raindrop/test/files.test.ts index 4d75cf53..5aca0f2a 100644 --- a/connectors/raindrop/test/files.test.ts +++ b/connectors/raindrop/test/files.test.ts @@ -33,7 +33,6 @@ const fileOf = (id: number) => find(`file:${String(id)}`); const hashOf = (bytes: Buffer): string => createHash("sha256").update(bytes).digest("hex"); -/** The bytes Marfa holds for a row of a file kind. */ function storedBytes(key: string): Buffer | undefined { const ref = rowOf(key).properties["blob_ref"]; return typeof ref === "string" ? w.marfa.blobs.get(ref)?.bytes : undefined; diff --git a/connectors/raindrop/test/read.test.ts b/connectors/raindrop/test/read.test.ts index 23df09c8..dabd44e1 100644 --- a/connectors/raindrop/test/read.test.ts +++ b/connectors/raindrop/test/read.test.ts @@ -37,7 +37,6 @@ async function ok(settings?: Record): Promise { expect(code, JSON.stringify(w.harness.lastRun())).toBe(0); } -/** Bookmarks in Unsorted, each created a second apart. */ function library(size: number): StubBookmark[] { return Array.from({ length: size }, (_, at) => w.raindrop.bookmark(`Bookmark ${String(at)}`), @@ -47,7 +46,6 @@ function library(size: number): StubBookmark[] { const hour = 60 * 60 * 1000; const day = 24 * hour; -/** The listings of bookmarks asked for since request `from`. */ function listings(from: number) { return w.raindrop.requests .slice(from) @@ -198,8 +196,7 @@ describe("a read of what changed", () => { await ok(); expect(bookmarkRow(b).state).toBe("archived"); expect(bookmarkRow(b).properties["in_trash"]).toBe(true); - // Raindrop no longer names the collection of a bookmark in Trash, so - // the row keeps it. + // Raindrop no longer names the collection of a bookmark in Trash, so the row keeps it. expect(collectionOf(b)).toEqual([String(box._id)]); const before = w.raindrop.requests.length; w.raindrop.edit(a._id, { title: "A, again" }); @@ -268,9 +265,7 @@ describe("a read of what changed", () => { const made = Array.from({ length: 60 }, (_, at) => w.raindrop.bookmark(`Made ${String(at)}`), ); - // Before the second page: two bookmarks of the first page are deleted - // for good, which moves the first bookmark of the second page onto the - // first, and an old one is edited, which moves it to the front. + // Before the second page, two deletions shift it by one and an edit moves an old bookmark to the front. const [old] = all as [StubBookmark]; const [shifted, newest, next] = [made[9], made[59], made[58]] as [ StubBookmark, @@ -516,9 +511,7 @@ describe("the sweep", () => { it("ends a sweep during which bookmarks are added, deleted and moved to Trash with each once and none archived wrongly", async () => { const all = library(120); await ok(); - // all[3] is listed on the first page and then deleted; all[60] is - // deleted before its page. Two more go to Trash, two are added, and the - // pages after the first shift by two. + // all[3] is deleted after the first page and all[60] before its page, so later pages shift. const [early, later, binned, late] = [ all[3], all[60], @@ -555,8 +548,7 @@ describe("the sweep", () => { expect(wrongly).toEqual([]); expect(bookmarks()).toHaveLength(122); expect(new Set(bookmarks().map((one) => one.source_id)).size).toBe(122); - // Listed before it was deleted: the pass is read again, since Raindrop - // changed during it. + // Listed before it was deleted: the pass is read again, since Raindrop changed during it. expect(bookmarkRow(early).state).toBe("archived"); expect(bookmarks().filter((one) => one.state === "active")).toHaveLength( 118, @@ -611,8 +603,7 @@ describe("the sweep", () => { await ok(); const [gone] = all.slice(500) as [StubBookmark]; w.raindrop.remove(gone._id); - // During each pass, a bookmark on a page it already read is deleted for - // good, which moves every later bookmark back a place. + // During each pass, a bookmark on a page it already read is deleted for good, which moves every later bookmark back a place. const deleted: StubBookmark[] = []; w.raindrop.beforePage = (space, page) => { if (space !== 0 || page !== 10) return; diff --git a/connectors/raindrop/test/state.test.ts b/connectors/raindrop/test/state.test.ts index 1ea1e343..f3a57230 100644 --- a/connectors/raindrop/test/state.test.ts +++ b/connectors/raindrop/test/state.test.ts @@ -6,7 +6,7 @@ import { progressOf, type Progress } from "../src/progress.js"; import { maxCandidates } from "../src/read.js"; import { pack } from "../src/seen.js"; -/** The kit's cap on a connector's state. */ +// The kit's cap on a connector's state. const stateCap = 512 * 1024; const silent = { @@ -17,8 +17,7 @@ const silent = { unreached: () => undefined, } as unknown as Log; -/** `count` distinct ids spread over Raindrop's range, the worst case for - * packing. */ +// `count` distinct ids spread over Raindrop's range, the worst case for packing. function spread(count: number): number[] { const ids = new Set(); let seed = 7; diff --git a/connectors/raindrop/test/thumbnail-turns.test.ts b/connectors/raindrop/test/thumbnail-turns.test.ts index 1fd899d0..b29d1311 100644 --- a/connectors/raindrop/test/thumbnail-turns.test.ts +++ b/connectors/raindrop/test/thumbnail-turns.test.ts @@ -9,7 +9,6 @@ import { type Covers, } from "../src/thumbnails.js"; -/** A thumbnail Marfa takes: a JPEG data URI of canonical base64. */ const uri = `data:image/jpeg;base64,${Buffer.from([0xff, 0xd8, 0xff, 0xe0]).toString("base64")}`; const good = "https://good.example/cover.jpg"; diff --git a/connectors/raindrop/test/thumbnails.test.ts b/connectors/raindrop/test/thumbnails.test.ts index 78744734..626abfdb 100644 --- a/connectors/raindrop/test/thumbnails.test.ts +++ b/connectors/raindrop/test/thumbnails.test.ts @@ -33,7 +33,6 @@ const rowOf = (id: number) => { const thumbnailOf = (id: number): unknown => rowOf(id).properties["thumbnail"]; -/** A bookmark whose cover is `name`, which answers `cover`. */ function covered( title: string, name: string, @@ -45,7 +44,6 @@ function covered( const day = 24 * 60 * 60 * 1000; -/** The refused covers the connector keeps, by bookmark. */ function refusals(): Record { const kept = w.harness.kept() as { state?: { library?: { thumbs?: Record } }; @@ -130,7 +128,6 @@ describe("a bookmark's cover", () => { await ok(); expect(rowOf(one._id).properties["image_url"]).toBe(two); expect(thumbnailOf(one._id)).toBeUndefined(); - // The next runs carry the cover to Raindrop and make its picture. await ok(); await ok(); expect(thumbnailMadeFrom(String(thumbnailOf(one._id)))).toBe( diff --git a/connectors/raindrop/test/world.ts b/connectors/raindrop/test/world.ts index ed22c602..5e5d28ce 100644 --- a/connectors/raindrop/test/world.ts +++ b/connectors/raindrop/test/world.ts @@ -20,8 +20,7 @@ export const types = [ "raindrop.copy", "raindrop.file", ]; -/** The instance edge types the connector writes: its `child-of` is the - * shipped `parent-of` read from the child. */ +// The instance edge types the connector writes: its `child-of` is the shipped `parent-of` read from the child. export const edges = [ "in-collection", "parent-of", @@ -29,8 +28,6 @@ export const edges = [ "attached-to", ]; -/** The core types the connector's types are children of, as far as a - * scripted server needs them. */ export function coreTypes(marfa: ScriptedServer): void { const strings = (...names: string[]) => Object.fromEntries(names.map((name) => [name, { type: "string" }])); @@ -76,15 +73,11 @@ export interface World { harness: Harness; raindrop: RaindropStub; once(settings?: Record): Promise; - /** A run whose promise is handed back before it ends, with `args` in - * place of `--once` where given. */ begin(settings?: Record, args?: string[]): Promise; close(): Promise; } export interface WorldOptions { - /** Makes a thumbnail from a cover's address; the default reads the stub's - * covers over http. */ readonly thumbnail?: typeof thumbnailFromAddress; } diff --git a/connectors/raindrop/test/write.test.ts b/connectors/raindrop/test/write.test.ts index 4fa12dbe..b4931eaf 100644 --- a/connectors/raindrop/test/write.test.ts +++ b/connectors/raindrop/test/write.test.ts @@ -22,7 +22,6 @@ async function ok(settings?: Record): Promise { expect(code, JSON.stringify(w.harness.lastRun())).toBe(0); } -/** A run whose outcome the test reads from what it left. */ async function run(settings?: Record): Promise { return w.once(settings); } @@ -170,8 +169,7 @@ describe("a create whose answer was lost", () => { ).toHaveLength(1); }); - /** Sets Raindrop's clock so the next thing it makes is stamped `skew` - * from Marfa's clock. */ + // Sets Raindrop's clock so the next thing it makes is stamped `skew` from Marfa's clock. function skewed(skew: number): void { const now = w.harness.clock.now().getTime(); // The stub moves its clock a minute on before each thing it makes. @@ -237,8 +235,7 @@ describe("a create whose answer was lost", () => { expect(w.raindrop.bookmarks.size).toBe(0); w.harness.clock.advance(120_000); await ok(); - // Each send reads what is there before it, and nothing looks for what - // the refused one made. + // Each send reads what is there before it, and nothing looks for what the refused one made. expect(sent("POST", "import/url/exists")).toHaveLength(2); expect(sent("GET", /^raindrop\//)).toHaveLength(0); expect(sent("POST", "raindrop")).toHaveLength(2); @@ -253,8 +250,6 @@ describe("a create whose answer was lost", () => { title: "Again", }); await run(); - // The owner saves the same address before the create is sent again, - // and the answer to that send is lost. const owners = w.raindrop.bookmark("Again", { link: "https://example.org/again", }); @@ -284,7 +279,6 @@ describe("a create whose answer was lost", () => { w.harness.clock.advance(120_000); await run(); expect(sent("POST", "raindrop")).toHaveLength(1); - // The owner saves the same address and title meanwhile. const owners = w.raindrop.bookmark("Kept", { link: "https://example.org/kept", }); @@ -785,7 +779,6 @@ describe("a collection", () => { `PUT raindrops/${String(child._id)}`, `DELETE collection/${String(top._id)}`, ]); - // The next read brings the bookmarks the delete moved. await ok(); expect(bookmarkRow(one._id).state).toBe("active"); expect(w.marfa.targetsOf(bookmarkRow(one._id).id, "in-collection")).toEqual( @@ -963,7 +956,6 @@ describe("a highlight", () => { const h = w.raindrop.highlight(one._id, "A passage"); await ok(); const row = rowOf(`highlight:${h._id}`); - // A daily read that finds the bookmark without it archives it. const kept = w.raindrop.bookmarks.get(one._id)?.highlights ?? []; const [only] = kept.splice(0, 1); w.harness.clock.advance(2 * 24 * 60 * 60 * 1000); @@ -989,8 +981,6 @@ describe("a highlight", () => { }); }); -/** Runs `then` once, before the first request the connector sends that - * matches, as another device changing the library between two requests. */ function between( match: (method: string, path: string) => boolean, then: () => void, @@ -1095,8 +1085,6 @@ describe("a lost create is matched only on proof", () => { title: "Same", }); let owners: { _id: number } | undefined; - // The owner saves the same address after the create is kept and before - // it lands. between( (method, path) => method === "POST" && path === "raindrop", () => { diff --git a/connectors/readwise/src/content-pictures.ts b/connectors/readwise/src/content-pictures.ts index 6d5edbd2..540bc61e 100644 --- a/connectors/readwise/src/content-pictures.ts +++ b/connectors/readwise/src/content-pictures.ts @@ -34,31 +34,18 @@ import { ProgressNotSaved } from "./held.js"; import { mapReaderSource } from "./reader.js"; import type { ReaderReader } from "./reader-client.js"; -/** At most this many pictures are fetched in one run. */ export const maxPicturesPerRun = 100; -/** A picture that would take the bytes saved in one run past this is left - * for the next run. */ export const maxPictureBytesPerRun = 200 * 1024 * 1024; -/** No picture is fetched once this long has passed since the run's first - * picture fetch. A fetch that has begun may take up to 30 seconds more. */ +// A fetch that has begun may take up to 30 seconds more. export const maxPicturePassMs = 10 * 60 * 1000; -/** A picture whose fetch fails in a way that may pass is asked for this many - * times, a run at a time, before it is not kept. */ export const maxPictureAttempts = 3; -/** At most this many documents wait for picture work. */ export const maxPictureJobs = 256; -/** At most this many documents are read from Reader for pictures in one - * run. */ export const maxPictureDocumentsPerRun = 25; -/** At most this many refused pictures are remembered; the oldest go first. */ export const maxPictureRefusals = 1024; -/** A saved picture that lacks its connection is written again in at most - * this many runs in a row, then left. */ export const maxPictureRepairs = 5; const stateKey = "pictures"; -/** One run's share of picture fetches. Its time starts at the first fetch, - * so a listing slowed by Reader's rate limit leaves pictures their time. */ +// Its time starts at the first fetch, so a listing slowed by Reader's rate limit leaves pictures their time. export class PictureBudget { fetched = 0; bytes = 0; @@ -72,7 +59,6 @@ export class PictureBudget { ms: maxPicturePassMs, }, ) {} - /** The limit this run has reached, if any. */ reached(): string | undefined { if (this.limit !== undefined) return this.limit; if (this.fetched >= this.limits.pictures) @@ -84,19 +70,13 @@ export class PictureBudget { this.limit = `${String(this.limits.ms / 60_000)} minutes`; return this.limit; } - /** Counts a fetch about to begin. */ take(): void { this.started ??= this.now(); this.fetched++; } } -/** - * Whether a refused picture may be fetched later: a failure of the transfer - * or the upload, or an answer that asks a client to wait or try again (408, - * 425, 429 and any 5xx). Any other status, such as a 404 or a 403, is the - * host's answer about this picture. - */ +// 408, 425, 429 and any 5xx ask a client to wait or retry; any other status is the host's answer about this picture. export function pictureMayPass( reason: PictureRefusal | "upload_failed", status?: number, @@ -114,25 +94,17 @@ interface PictureJob { id: string; canonical: string; type: string; - /** Runs a fetch that may pass has failed in, by picture key. */ attempts?: Record; - /** Pictures were saved or repaired in an earlier run, and are listed as - * kept only once Marfa shows them attached. */ + // Listed as kept only once Marfa shows the pictures attached. saved?: true; - /** Runs in a row that failed, waited or repaired a connection. */ failures?: number; - /** Not tried again before this time, in milliseconds. */ due?: number; } interface PictureState { - /** Whether the picture kind was on in the last run that read this. */ on: boolean; queue: PictureJob[]; - /** Pictures given up on, by picture key, such as `svg` or - * `bad_status:404`. Kept across documents, runs and manifest rewrites. */ refused: Record; - /** While documents kept before the kind was turned on are handed to the - * queue: the last canonical key handed over. */ + // The last canonical key handed to the queue while documents kept before the kind was on, or left when the queue was full, are gone over again. backfill?: string; } const pictureKeyOf = (address: string): string => digest(address).slice(0, 24); @@ -183,8 +155,6 @@ function pictureState(state: Pick): PictureState { throw invalid(); return value as unknown as PictureState; } -/** The saved picture state, or, when it cannot be read, an empty queue - * saved in its place, so that picture work starts again. */ async function loadPictureState( state: CheckpointState, log: Pick["log"], "condition">, @@ -214,7 +184,6 @@ async function savePictureState( throw new ProgressNotSaved("Reader picture progress", result.reason); } -/** How Reader's content preservation lists pictures while the kind is on. */ export function pictureListing( state: Pick, ): PictureListing { @@ -230,11 +199,6 @@ export function pictureListing( }; } -/** - * Hands documents whose content changed to picture work. When the queue is - * full, the documents kept in Marfa are gone over again from the start, so - * none is missed. - */ export async function admitPictures( state: CheckpointState, jobs: readonly ContentJob[], @@ -260,11 +224,7 @@ export async function admitPictures( if (changed) await savePictureState(state, saved); } -/** - * Records that the picture kind is off, so that turning it on again goes over - * the documents kept meanwhile. Writes nothing where picture work never - * ran, and clears progress that cannot be read. - */ +// Records the kind as off, so turning it on again goes over the documents kept meanwhile. export async function pausePictures(state: CheckpointState): Promise { if (state.get(stateKey) === undefined) return; let saved: PictureState; @@ -285,21 +245,12 @@ type PictureContext = Pick< > & Pick, "held">; -/** - * One run of Reader's picture work, outside the content queue: hands - * documents kept before the kind was on to the queue, then for each document - * whose content is accounted for, saves its pictures within the run's - * limits, repairs a saved picture that lacks its connection, and once every - * picture is settled and attached, writes the manifest again at the - * revision it is at. - */ export async function drainPictures( context: PictureContext, client: ReaderReader, state: CheckpointState, options: { account: string; - /** The content queue, whose documents wait for their content first. */ contentState: Pick; now?: () => number; fetch?: typeof fetchPicture; @@ -382,7 +333,6 @@ export async function drainPictures( ); } -/** The job, tried again later, as the content queue does. */ function backedOff(job: PictureJob, now: () => number): PictureJob { const failures = (job.failures ?? 0) + 1; return { ...job, failures, due: now() + retryDelay(failures) }; @@ -470,7 +420,6 @@ async function picturesOf( if (repairing) next = backedOff({ ...next, failures: job.failures ?? 0 }, options.now); for (const [key, row] of repairing ? held.unattached : []) { - // The row as it is, written again with its connection. const repair = entry(job, key, "picture", revision); repair.properties = Object.fromEntries( readerPictureFields @@ -556,8 +505,7 @@ async function picturesOf( return { job: undefined, read: true, left: 0 }; } -/** Writes the manifest again at its revision, only while it is still the - * accounted manifest of that revision and only when its bytes change. */ +// Only while it is still the accounted manifest of that revision, and only when its bytes change. async function rewrite( context: PictureContext, job: PictureJob, diff --git a/connectors/readwise/src/content-queue.ts b/connectors/readwise/src/content-queue.ts index 36d97c9b..fb50a8bb 100644 --- a/connectors/readwise/src/content-queue.ts +++ b/connectors/readwise/src/content-queue.ts @@ -37,8 +37,7 @@ export type Context = Pick< RunContext, "known" | "signal" | "log" > & { - /** Without it, no picture is proven attached to its document, so none is - * listed as kept. */ + // Without it, no picture is proven attached to its document, so none is listed as kept. linked?: RunContext["linked"]; inspect( type: string, @@ -51,8 +50,6 @@ export type Context = Pick< name: string, ): Pick, "upsert" | "state">; }; -/** How long work that failed `attempts` runs in a row waits before it is - * tried again: doubling from two minutes, at most a day. */ export const retryDelay = (attempts: number): number => Math.min(24 * 60 * 60_000, 60_000 * 2 ** Math.min(attempts, 10)); @@ -107,12 +104,6 @@ export function isAccountedContent( typeof manifest.properties["blob_ref"] === "string" ); } -/** - * Writes one file or picture and checkpoints it. A row is written under the - * type it is held in, which a repair of an earlier release's picture, held as - * a file, passes as `type`; a new picture is a kind of its own, which a - * mapping may turn off. - */ export async function commit( context: Pick, file: Entry, @@ -135,11 +126,8 @@ export async function commit( `Reader content write was not acknowledged: ${result.reason}`, ); } -/** What Marfa holds of a plan's files, whoever wrote them. */ export interface FileEvidence { - /** Rows by canonical key. */ rows: Map; - /** Canonical keys this connector holds an agreement for. */ agreed: Set; purged: Set; } @@ -158,8 +146,7 @@ export async function fileEvidence( }; for (let offset = 0; offset < files.length; offset += 100) { const keys = files.slice(offset, offset + 100).map((file) => file.sourceId); - // A picture kind that is off is not read. The files hold any picture an - // earlier release saved as one, and the pictures any it saves now. + // The files hold pictures saved as files before the kind existed; a kind that is off is not read. const types = options.pictures ? [readerFileType.id, readerPictureType.id] : [readerFileType.id]; @@ -178,7 +165,6 @@ export async function fileEvidence( } return found; } -/** Whether a file row holds the bytes of the planned file. */ export function holds(row: Item | undefined, file: ContentFile): boolean { return ( typeof row?.properties["blob_ref"] === "string" && @@ -186,15 +172,9 @@ export function holds(row: Item | undefined, file: ContentFile): boolean { ); } -/** What Marfa holds of a document's pictures. */ export interface HeldPictures { - /** Active, with their bytes and address, and attached to the document. */ kept: Set; - /** Active, with their bytes and address, and not attached to the - * document, as a run that stopped before its connections were written - * leaves one. */ unattached: Map; - /** Purged, trashed, revoked or archived in Marfa. */ removed: Set; } export async function heldPictures( @@ -241,19 +221,9 @@ export async function heldPictures( return held; } -/** How a connector that saves pictures lists those of a document. */ export interface PictureListing { - /** The reason a picture was given up on, such as `svg` or - * `bad_status:404`. */ refused: (address: string) => string | undefined; } -/** - * Sets the status of each picture resource from what Marfa holds: kept when - * held and attached, not kept when removed in Marfa or refused, and - * otherwise not kept as a third party's. With `fetching`, a picture past the - * limit for one document is listed as over it. Answers the pictures that - * are still to fetch, in order. - */ export function listPictures( plan: ContentPlan, held: HeldPictures, @@ -393,8 +363,7 @@ async function preserve( sourceId: parent.source_id ?? job.canonical, properties: enrichment, }); - // Each picture address is looked for whatever the setting, so that a - // manifest either connector writes lists a picture Marfa holds as kept. + // Each picture address is looked for whatever the setting, so a manifest either connector writes lists a picture Marfa holds as kept. const whole = contentPlan(job.canonical, row, mapped.textFiles, { pictures: true, }); @@ -403,8 +372,7 @@ async function preserve( agreements: true, pictures: fetching, }); - // With nothing held and nothing to fetch, the plan is the one made - // without pictures, so the manifest is as it was before pictures. + // With nothing held and nothing to fetch, the plan is the one made without pictures, so the manifest does not change. const plan = fetching || whole.files.some( @@ -577,7 +545,6 @@ async function preserve( await commit(context, value); return { complete, progressed: progressed && !failed }; } -/** Queue acknowledgement is independent of metadata and of each resource's checkpoint. */ export async function drainContent( context: Context, client: ReaderReader, diff --git a/connectors/readwise/src/content-staging.ts b/connectors/readwise/src/content-staging.ts index 30c29364..8832215d 100644 --- a/connectors/readwise/src/content-staging.ts +++ b/connectors/readwise/src/content-staging.ts @@ -1,11 +1,6 @@ import type { FileSource } from "@withmarfa/connector"; -/** - * Finishes a vendor read outside the scoped write and replays what it read, - * as a stream, for each attempt the kit makes. The bytes are held in memory, - * never written to a file, which the permission flags do not allow a - * connector; their size is what `download` already limits. - */ +// Bytes are held in memory, never in a file, which the permission flags do not allow a connector. export async function stageContent( content: Awaited>, signal: AbortSignal, diff --git a/connectors/readwise/src/content-types.ts b/connectors/readwise/src/content-types.ts index d350a385..876687ac 100644 --- a/connectors/readwise/src/content-types.ts +++ b/connectors/readwise/src/content-types.ts @@ -40,11 +40,6 @@ export const readerFileFields = [ "source_url", ] as const; -/** - * A picture saved from a document's HTML, a kind of its own that ships off. - * It holds what a picture of the file type holds, and is attached to the - * source or highlight whose text draws it. - */ export const readerPictureType: TypeDefinition = { id: "readwise.picture", label: "Readwise picture", @@ -69,7 +64,6 @@ export const readerPictureType: TypeDefinition = { }; export const readerPictureFields = readerFileFields; -/** File writes remain inside the explicitly configured Readwise account. */ export function readerFilePolicy( account: string | undefined, item?: Item, diff --git a/connectors/readwise/src/content.ts b/connectors/readwise/src/content.ts index 0611852e..5e2f90b6 100644 --- a/connectors/readwise/src/content.ts +++ b/connectors/readwise/src/content.ts @@ -75,7 +75,7 @@ function mime(bytes: Uint8Array, declared: string | null): string { ? type : "application/octet-stream"; } -/** Storage never receives API authorization, cookies, referrers, or automatically followed redirects. */ +// Storage never receives API authorization, cookies, referrers or followed redirects. export async function download( value: string, signal: AbortSignal, @@ -205,7 +205,6 @@ export interface Resource { kind: ResourceKind; status: "kept" | "pending" | "unavailable" | "deliberately-unkept"; reason?: string; - /** The HTTP status of a picture's refused answer, beside `bad_status`. */ httpStatus?: number; fileKey?: string; maxBytes?: number; @@ -222,18 +221,9 @@ export interface ContentPlan { resources: Resource[]; files: ContentFile[]; } -/** At most this many picture addresses of one document are fetched, in the - * order they come; the rest are counted and not fetched. */ export const maxPicturesPerDocument = 50; -/** A longer picture address is not read from a document. */ const maxPictureAddressLength = 2048; -/** - * The web addresses of the pictures a document's HTML draws, then its - * `image_url`, each once in the URL parser's standard form: an `img`'s `src`, - * or its `data-src` where it has no `src`. `srcset` candidates are not - * pictures to save, since a reader draws `src`. Only `https` and `http` - * addresses count, and an image on Readwise storage keeps its own path. - */ +// `srcset` candidates are not saved: a reader draws `src`. export function pictureAddresses( html: string, image: string | null | undefined, @@ -263,8 +253,6 @@ export function pictureAddresses( if (image) take(image); return [...found]; } -/** The resource id of a picture: its whole address, so two addresses that - * differ only in the query are two pictures. */ export const pictureResourceId = (address: string): string => `picture:${digest(address)}`; function imageUrls(html: string): string[] { @@ -292,12 +280,6 @@ function imageUrls(html: string): string[] { visit(parse(html)); return found; } -/** - * With `pictures`, each picture address of the document is a resource of its - * own, an `https` one a file to keep and an `http` one not kept; without it, - * a picture on another website is one deliberately unkept image resource per - * origin and path. - */ export function contentPlan( canonical: string, row: ReaderDocument, @@ -351,7 +333,7 @@ export function contentPlan( const url = new URL(value); identity = url.origin + url.pathname; } catch { - /* Relative and inline images remain explicitly unkept. */ + // Relative and inline images stay unkept. } urls.set(`image:${digest(identity)}`, { value, kind: "image" }); } diff --git a/connectors/readwise/src/definition.ts b/connectors/readwise/src/definition.ts index 5dab2024..35ada05e 100644 --- a/connectors/readwise/src/definition.ts +++ b/connectors/readwise/src/definition.ts @@ -49,7 +49,6 @@ export function connector() { name: "source", direction: "both", type: sourceType, - // The thumbnail is the media type's own, which the source inherits. fields: [...sourceFields, thumbnailField], retired: retiredSourceFields, tags: true, @@ -97,8 +96,6 @@ export function connector() { policy: (item, entry) => readerFilePolicy(config?.account, item, entry), }, { - // The pictures a document's HTML draws from other websites. The kind - // ships off: with it off none is fetched or saved. name: "picture", direction: "in", enabled: false, @@ -116,8 +113,7 @@ export function connector() { from_type_constraints: [highlightType.id], to_type_constraints: [sourceType.id], }, - // Retired: cleared on every highlight written, so one synced before holds - // only `excerpt-of`. + // Retired: cleared on every highlight written, so one synced before holds only `excerpt-of`. { id: "references", cardinality: "many-to-many", @@ -133,7 +129,6 @@ export function connector() { to_type_constraints: [sourceType.id, highlightType.id], }, ], - // Nothing goes to Readwise unless Reader is on and may be written. carries: (values) => { const parsed = parseConfig(values); return parsed.reader && !parsed.inboundOnly diff --git a/connectors/readwise/src/display.ts b/connectors/readwise/src/display.ts index 75a45be3..6020d5bf 100644 --- a/connectors/readwise/src/display.ts +++ b/connectors/readwise/src/display.ts @@ -1,11 +1,7 @@ /** Readwise cuts a highlight's text at this many characters. */ export const readwisePassageLimit = 8_191; -/** - * The passage a highlight holds as Markdown, whole: the export passage keeps - * pictures and formatting that Reader's plain passage drops, unless Readwise - * cut it at its limit, and then Reader's passage is the whole one. - */ +// The export passage keeps pictures and formatting that Reader's plain passage drops, unless Readwise cut it at its limit. export function highlightPassage(text: string, exportText: unknown): string { return typeof exportText === "string" && exportText.trim() !== "" && diff --git a/connectors/readwise/src/export-sync.ts b/connectors/readwise/src/export-sync.ts index 3c4abd44..01214b89 100644 --- a/connectors/readwise/src/export-sync.ts +++ b/connectors/readwise/src/export-sync.ts @@ -280,8 +280,7 @@ export async function sync( reader?: ReaderReader; now?: () => number; maxPages?: number; - /** Set when Reader runs too: its listing keeps the rows it manages - * current, so the export leaves their refresh to it. */ + // Set when Reader runs too: its listing keeps the rows it manages current, so the export leaves their refresh to it. readerListing?: boolean; pictures?: PictureListing; held?: Held; diff --git a/connectors/readwise/src/export.ts b/connectors/readwise/src/export.ts index df10ce61..7743a089 100644 --- a/connectors/readwise/src/export.ts +++ b/connectors/readwise/src/export.ts @@ -155,7 +155,6 @@ export function parsePage(value: unknown): ExportPage { return { ...page, nextPageCursor: cursor } as unknown as ExportPage; } -/** Metadata and overflow writes must use the same export identity evidence. */ export function readerExportPassage( sources: readonly Source[], expected: { diff --git a/connectors/readwise/src/held.ts b/connectors/readwise/src/held.ts index f4653b56..e77a41fb 100644 --- a/connectors/readwise/src/held.ts +++ b/connectors/readwise/src/held.ts @@ -1,18 +1,9 @@ import type { Entry, OutboundIntent } from "@withmarfa/connector"; -/** - * The rows with a Reader write not yet settled while Reader may not be - * written. The kit keeps each such row as it is and refuses a read's write - * to it, so a read leaves it pending rather than stop at it. - */ export interface Held { key(key: string | undefined): boolean; entry(entry: Entry): boolean; - /** - * A create with no link, whose answer was lost, is held while Reader may not - * be written. The kit holds every entry of its type for it, so no scope of - * that type can save progress until it settles. - */ + // No scope of that type can save progress until the create settles. unlinkedCreate: boolean; } @@ -22,7 +13,6 @@ export const nothingHeld: Held = { unlinkedCreate: false, }; -/** A scope's progress was refused, with the kit's reason. */ export class ProgressNotSaved extends Error { constructor( what: string, diff --git a/connectors/readwise/src/http.ts b/connectors/readwise/src/http.ts index bea7be32..bbacf63a 100644 --- a/connectors/readwise/src/http.ts +++ b/connectors/readwise/src/http.ts @@ -39,7 +39,6 @@ export interface ReadwiseHttpOptions { timeoutMs?: number; maxBytes?: number; waitUntil?: (retryAt: string) => Promise; - /** Replaces the pacer shared by every client of the token, for a test. */ pacer?: Pacer; } export class ReadwiseHttp { diff --git a/connectors/readwise/src/kinds.ts b/connectors/readwise/src/kinds.ts index 86a4a8bb..5ff97bc4 100644 --- a/connectors/readwise/src/kinds.ts +++ b/connectors/readwise/src/kinds.ts @@ -5,7 +5,6 @@ type Kind = "url" | "datetime" | "date"; function digits(text: string, limit?: number): boolean { return /^\d+$/.test(text) && (limit === undefined || Number(text) < limit); } -/** A calendar date, as the server takes one. */ export function isDate(text: string): boolean { const match = /^(\d{4})-(\d\d)-(\d\d)$/.exec(text); if (!match) return false; @@ -20,7 +19,6 @@ export function isDate(text: string): boolean { ]; return days !== undefined && day > 0 && day <= days; } -/** A calendar date, or that date with a time and an offset, as the server takes one. */ export function isDatetime(text: string): boolean { if (isDate(text)) return true; if (text.length < 17 || text[10] !== "T" || !isDate(text.slice(0, 10))) @@ -50,7 +48,6 @@ export function isDatetime(text: string): boolean { return false; return time.length === 8 || (time[8] === "." && digits(time.slice(9))); } -/** The value the server stores for a URL, or undefined when it refuses one. */ export function urlValue(text: string): string | undefined { const trimmed = text.trim(); return URL.canParse(trimmed) ? trimmed.replace(/[\t\n\r]/g, "") : undefined; @@ -69,12 +66,7 @@ export function kindsOf( return kinds; } -/** - * Fits each value to its field's kind, so one value Readwise sends in - * another shape never stops the row being written. A blank value is left - * out. Any other value the kind refuses is left out of its field and kept, - * as sent, under `original_values`. - */ +// A value the kind refuses is kept as sent under `original_values`. export function fitKinds( values: Record, kinds: ReadonlyMap, diff --git a/connectors/readwise/src/managed.ts b/connectors/readwise/src/managed.ts index 119bce37..61430f15 100644 --- a/connectors/readwise/src/managed.ts +++ b/connectors/readwise/src/managed.ts @@ -35,7 +35,6 @@ export interface SharedContext { log: { condition(key: string, message: string): void }; } export class PreservationQueueFull extends Error {} -/** The kit keeps this row for a Reader write not yet settled. */ export class HeldRow extends Error {} export function exportPolicy( type: string, @@ -52,7 +51,6 @@ export function exportPolicy( if (managed && (entry === undefined || !incoming)) return { owned: false }; if (!managed && !incoming) return {}; const fields = type === "readwise.source" ? sourceFields : highlightFields; - // Export enrichment is independent; every Reader value observes local divergence. const exportFields = new Set([ "readwise_id", "readwise_source_id", @@ -100,7 +98,6 @@ export class SharedRows { private readonly preserve?: (job: ContentJob) => Promise, private readonly rows: { held?: Held; - /** Gains the source ID of each entry the export has from Reader. */ fromReader?: Set; } = {}, ) {} @@ -293,9 +290,7 @@ export class SharedRows { if (exportEntry !== undefined) { const { original_values: refused, ...exported } = exportEntry.properties; Object.assign(properties, exported); - // The export's refused values replace its earlier ones, and a field it - // now refuses no longer holds the value it sent before. Reader's own - // refused values are found again when its row is mapped. + // The export's refused values replace its earlier ones: a field it now refuses no longer holds the value it sent before. if (typeof refused === "object" && refused !== null) { for (const field of Object.keys(refused)) Reflect.deleteProperty(properties, field); diff --git a/connectors/readwise/src/mapping.ts b/connectors/readwise/src/mapping.ts index 008c9407..2df7c18f 100644 --- a/connectors/readwise/src/mapping.ts +++ b/connectors/readwise/src/mapping.ts @@ -9,7 +9,6 @@ export const sourceKinds = kindsOf(sourceType, { published_at: "datetime", }); export const highlightKinds = kindsOf(highlightType); -/** The title a source carries in the export, when it has one. */ export function sourceTitle(source: Source): string | undefined { return source.title?.trim() ? source.title diff --git a/connectors/readwise/src/pacing.ts b/connectors/readwise/src/pacing.ts index 64010708..43bc97e0 100644 --- a/connectors/readwise/src/pacing.ts +++ b/connectors/readwise/src/pacing.ts @@ -1,8 +1,6 @@ import { Pacer } from "@withmarfa/connector/pacer"; -/** Readwise's documented limits for one access token, a minute at a time: - * the default for the export and highlight detail, and Reader's own for - * listing, saving, updating and deleting documents. */ +// Readwise's documented limits for one access token, a minute at a time. const perMinute = { export: 240, list: 20, @@ -15,8 +13,6 @@ export type Budget = keyof typeof perMinute; const pacers = new Map(); -/** The pacer for one limit of one token, shared by every client of it, so - * that their requests count together and one `429` holds them all. */ export function pacerFor(token: string, budget: Budget): Pacer { const key = `${budget}\0${token}`; let pacer = pacers.get(key); diff --git a/connectors/readwise/src/policy.ts b/connectors/readwise/src/policy.ts index 9787dcf6..62ebaea0 100644 --- a/connectors/readwise/src/policy.ts +++ b/connectors/readwise/src/policy.ts @@ -14,15 +14,8 @@ export interface PolicyConfig { inboundOnly: boolean; } -/** - * With Reader off, nothing is carried. A row Reader does not manage is the - * export's. With Reader on, Reader owns its verified rows and explicit - * creates; the export still writes the rest, but only while writing or - * archiving one, so none of them is ever carried to Reader, and each of - * their fields mirrors the export. The exception is a row whose export entry - * came from Reader (`fromReader`), which Reader takes over: its fields Reader - * can edit keep a change made in Marfa, so Reader's takeover keeps it too. - */ +// With Reader on, Reader owns its verified rows and explicit creates; the export writes the rest only while writing or archiving one, never carried to Reader. +// A row whose export entry came from Reader takes over: its editable fields keep a change made in Marfa. export function rowPolicy( type: string, config: PolicyConfig | undefined, diff --git a/connectors/readwise/src/reader.ts b/connectors/readwise/src/reader.ts index 6e31abb8..4e214893 100644 --- a/connectors/readwise/src/reader.ts +++ b/connectors/readwise/src/reader.ts @@ -279,7 +279,7 @@ function mapped( enrichment: ReaderEnrichment, ): ReaderMapping { const canonical = readerIdentity(account, kind, row.id); - // Export-only fields survive Reader refreshes; old Reader fields are replaced below. + // Export-only fields survive Reader refreshes; Reader's own fields are replaced below. const old = enrichment.properties ?? {}; const kept = Object.fromEntries( Object.entries(old).filter( @@ -341,7 +341,6 @@ function mapped( textFiles: [], conditions: [], }; - // Reader's tags are the row's tags. result.entry.tags = Object.keys(row.tags ?? {}); if (kind === "document") Object.assign(values, { @@ -443,7 +442,7 @@ export function mapReaderHighlight( return mapped(account, row, "highlight", enrichment); } -/** Both connectors fingerprint the same content work, independent of fetch options. */ +// Both connectors fingerprint the same content work, independent of fetch options. export function readerContentRevision( document: ReaderDocument, notes: readonly ReaderDocument[] = [], diff --git a/connectors/readwise/src/reader/claims.ts b/connectors/readwise/src/reader/claims.ts index d63f17f9..d8f03be3 100644 --- a/connectors/readwise/src/reader/claims.ts +++ b/connectors/readwise/src/reader/claims.ts @@ -1,15 +1,10 @@ import type { OutboundIntent } from "@withmarfa/connector"; import { readerIdentity } from "../readwise.js"; -/** - * Reader objects a create made for a row that a trash or purge then - * overtook, by the row's ID. Marfa cannot link a row in the bin or keep a - * tombstone for a purged row that was never linked, so the connector keeps - * the claim itself: the import skips what is claimed, and a restored row - * takes its claimed object back instead of creating another. - */ +// Marfa cannot link a row in the bin or keep a tombstone for a purged row never linked, so the connector keeps the claim: +// the import skips what is claimed and a restored row takes its object back. export const claimsKey = "claims"; -/** Past this, the oldest settled claim is dropped. */ +// Past this, the oldest settled claim is dropped, so settling never waits on room. export const claimLimit = 1000; export function readClaims(value: unknown): Map { @@ -31,7 +26,6 @@ export function claimKind(type: string): "document" | "highlight" { return type === "readwise.highlight" ? "highlight" : "document"; } -/** The claim a pending settlement step records, before the sync keeps it. */ export function pendingClaim( intent: OutboundIntent, account: string, @@ -56,7 +50,6 @@ export function pendingClaim( ]; } -/** The Reader ID a claim names, if it is of this kind and account. */ export function claimedId( canonical: string | undefined, account: string, diff --git a/connectors/readwise/src/reader/identity.ts b/connectors/readwise/src/reader/identity.ts index a5c0dc02..ab51ad6e 100644 --- a/connectors/readwise/src/reader/identity.ts +++ b/connectors/readwise/src/reader/identity.ts @@ -313,11 +313,6 @@ export class ReaderIdentities { await result.keepClaims(); return result; } - /** - * Keeps the claims settling has made since, and drops those Marfa now - * holds itself: a row linked to the object, or a tombstone for it. At the - * limit the oldest settled claim goes, so settling never waits on room. - */ private async keepClaims(): Promise { const stored = readClaims(this.state.get(claimsKey)); const claims = new Map(stored); @@ -415,8 +410,7 @@ export class ReaderIdentities { const held = previous.filter(matching); if (held.length === 0) this.bridge.aliases[key] = [...previous, value]; else if (value.observed !== undefined) { - // Parent and status are observations, not identity. A later walk replaces - // old evidence; disagreeing observations in one walk remain a conflict. + // Parent and status are observations, not identity: a later walk replaces old evidence, and disagreeing observations in one walk stay a conflict. const current = held.filter((alias) => alias.observed === value.observed); const retained = previous.filter((alias) => !matching(alias)); this.bridge.aliases[key] = [ @@ -435,7 +429,6 @@ export class ReaderIdentities { } this.enriched.set(key, properties); } - /** Reads export evidence without preparing or saving anything. */ useClient(client: ExportClient): void { this.client = client; } @@ -729,8 +722,6 @@ export class ReaderIdentities { const type = kind === "highlight" ? "readwise.highlight" : "readwise.source"; const canonical = readerIdentity(this.account, kind, document.id); - // A claimed object belongs to a row in the bin or purged, as a tombstone - // would if Marfa could keep one for it. if (this.claimed.has(canonical)) return { canonical, diff --git a/connectors/readwise/src/reader/outbound.ts b/connectors/readwise/src/reader/outbound.ts index 5c487308..4a200b99 100644 --- a/connectors/readwise/src/reader/outbound.ts +++ b/connectors/readwise/src/reader/outbound.ts @@ -39,14 +39,9 @@ interface Plan { id: string; body: ReaderBody; updates: ReaderBody; - /** - * For a source-create-update: whether the create made the document, so a - * trash or purge that overtakes the rest claims it. One Reader held before - * is the person's. - */ + // Whether the create made the document, so a trash or purge that overtakes the rest claims it; one Reader held before is the person's. made?: boolean; } -/** The claim that settles a create a trash or purge overtook. */ interface Settlement { account: string; base: string; @@ -55,7 +50,6 @@ interface Settlement { body: ReaderBody; updates: ReaderBody; } -/** What a run's preflight approved, by the context the kit gives it and each change. */ const approved = new WeakMap< Context, { client: ReaderWriteClient; purges: Set } @@ -268,7 +262,7 @@ function validateBaseline( ) throw new Refused("invalid saved Reader create baseline"); } -/** No filtered or partial listing can prove a deletion cascade or a new identity. */ +// No filtered or partial listing can prove a deletion cascade or a new identity. export async function completeInventory( reader: ReaderReader, context?: Pick, @@ -400,9 +394,7 @@ function answer( // Reader does not hold, so the answer says Reader holds the other one and // the kit does not send it again while Marfa keeps it. if (change.favorite !== undefined) result.entry.favorite = !change.favorite; - // The answer is what the row holds, so it carries the thumbnail the row - // holds while the picture is the one it was made from, as an entry does, - // and none for another picture. + // The answer is what the row holds, so it carries the thumbnail the row holds while the picture is the one it was made from. const held = change.item.properties; const picture = result.entry.properties["image_url"]; const thumbnail = @@ -420,10 +412,7 @@ function answer( ); return result.entry; } -/** - * Reader's own tags with the change applied, one tag at a time, so a tag only - * Reader holds stays; undefined when Reader already holds the result. - */ +// One tag at a time, so a tag only Reader holds stays; undefined when Reader already holds the result. function tagsAfter( row: ReaderDocument, change: Change, @@ -447,7 +436,6 @@ function assertKind(change: Change, row: ReaderDocument): void { ) throw new Refused("Reader identity has a different document kind"); } -/** The saved step is the claim that settling journaled, if it is one. */ function settlement( value: unknown, config: ReaderConfig, @@ -483,7 +471,6 @@ function claimStep( baseline: null, }; } -/** New highlights of the passage a create sent; `exact` also matches its note and tags. */ function highlightMatches( rows: readonly ReaderDocument[], before: ReadonlySet, @@ -504,14 +491,8 @@ function highlightMatches( (!exact || equal(values(row, Object.keys(rest)), rest)), ); } -/** - * The Reader object a pending create made: one its answer or journal names, - * or the one new match for what it sent, unless Reader proved the request - * never applied. A document Reader held before the create is the person's, - * never the create's. A new highlight of the same passage whose note or tags - * differ may be the create's, edited in Reader, so it leaves the create - * uncertain rather than settled with nothing claimed. - */ +// A document Reader held before the create is the person's, never the create's. +// A same-passage highlight with another note or tags may be the create's, edited in Reader, so it leaves the create uncertain. async function madeBy( held: OutboundIntent, operation: Plan, @@ -551,12 +532,7 @@ async function madeBy( ); return matches[0]?.id; } -/** - * A trash or purge that overtakes a pending create never deletes at Reader: - * it claims what the create made for the row, so the import does not bring - * it back and a restore takes it again. The claim is kept by the next sync, - * so the step is acknowledged on the run after it. - */ +// A trash or purge that overtakes a pending create never deletes at Reader: it claims what the create made. The next sync keeps the claim, so the step is acknowledged on the run after it. async function settle( held: OutboundIntent, client: ReaderWriteClient, @@ -656,8 +632,7 @@ async function performChange( : "Reader does not own this row or its explicit create request", ); if (change.kind === "purged" && !config.propagatePurge) return; - // A change of tags or favorite alone comes outside a batch, so it has no - // preflight. It purges nothing, so a client with no purge approved serves. + // A change of tags or favorite alone comes outside a batch, so it has no preflight; it purges nothing, so a client with no purge approved serves. if ( approved.get(context) === undefined && change.kind === "updated" && @@ -693,8 +668,7 @@ async function performChange( } : { url: string(props["url"]) }; validateBody(request, highlight ? "highlight-create" : "source-create"); - // A row restored after its create was overtaken takes back the object - // it claimed, so nothing is made twice. + // A row restored after its create was overtaken takes back the object it claimed, so nothing is made twice. const adopted = claimed === undefined ? undefined : await client.document(claimed); if ( @@ -783,9 +757,8 @@ async function performChange( ? tagsAfter(before, change) : undefined; if (tags !== undefined) updates["tags"] = [...tags]; + // Nothing to send. A tag or favorite change is answered with what Reader holds, so the kit does not take it for done. if (change.kind !== "purged" && Object.keys(updates).length === 0) - // Nothing to send. A tag or favorite change is answered with what - // Reader holds, so the kit does not take it for done. return before !== undefined && (change.tags !== undefined || change.favorite !== undefined) ? answer(change, before, config) @@ -845,8 +818,7 @@ async function performChange( ); readerId = matches[0]?.id ?? ""; } else readerId = await client.save(operation.body); - // The answer is journaled, so a trash that overtakes what follows knows - // which highlight the create made. + // The answer is journaled, so a trash that overtakes what follows knows which highlight the create made. held = await context.outbound.advance(change.item.id, held.token, { request: json({ ...operation, id: readerId }), baseline: held.baseline, @@ -913,8 +885,7 @@ async function performChange( id: readerId, body: operation.updates, updates: {}, - // Not one Reader held before, nor one found after Reader proved the - // earlier save never applied. + // Not one Reader held before, nor one found after Reader proved the earlier save never applied. made: !object(previous) && Array.isArray(ids) && diff --git a/connectors/readwise/src/reader/policy.ts b/connectors/readwise/src/reader/policy.ts index 2fa2153a..b998d15d 100644 --- a/connectors/readwise/src/reader/policy.ts +++ b/connectors/readwise/src/reader/policy.ts @@ -34,8 +34,7 @@ export function readerPolicy( return { owned: true, firstAgreement: "hold", - // A row the export held keeps what was done to it then, such as an - // archive in Marfa, without carrying it to Reader. + // A row the export held keeps what was done to it then, such as an archive in Marfa, without carrying it to Reader. ...(incoming && item !== undefined && !managed && { adopt: true }), ...(inboundOnly && { fields: Object.fromEntries( diff --git a/connectors/readwise/src/reader/sync.ts b/connectors/readwise/src/reader/sync.ts index 6432555c..29886bc3 100644 --- a/connectors/readwise/src/reader/sync.ts +++ b/connectors/readwise/src/reader/sync.ts @@ -236,7 +236,6 @@ export async function sync( exportClient?: ExportClient; now?: () => number; maxPages?: number; - /** Picture work's fetch and clock; for tests. */ pictures?: Pick[3], "fetch" | "budget">; } = {}, ): Promise { @@ -298,7 +297,6 @@ export async function sync( context.signal, { waitUntil: (until) => context.waitUntil(until) }, ); - // Pictures are a kind of their own, which ships off. const pictures = context.written(readerPictureType.id).length > 0; const content: ContentWork = options.content ?? { enqueue: enqueueContent, @@ -433,7 +431,6 @@ export async function sync( document.category === "highlight" ? mapReaderHighlight(config.account, document, enrichment) : mapReaderSource(config.account, document, enrichment); - // The kit keeps this row for a Reader write not yet settled. if (waiting.entry(mapped.entry)) { pending.add(document.id); for (const note of notes.get(document.id) ?? []) pending.add(note.id); @@ -638,12 +635,12 @@ export async function sync( if (row?.state === "active" && scoped) { try { const answer = await get(idFromKey(config.account, key)); + // An answer means the item survives: it is out of scope, never a confirmed deletion. if (answer === undefined) current.confirmed.push(key); } catch (error) { contain(error, key); continue; } - // A surviving feed item is out of scope, never a confirmed deletion. } current.remaining = current.remaining.filter( (candidate) => candidate !== key, @@ -867,11 +864,7 @@ export async function sync( "Reader listing has more pages; the next run resumes its saved cursor", ); }; - /** - * A run a change in Marfa started reads each Reader document the kit named, - * so the kit can send what changed over what Reader holds, and saves no - * progress: the kit refuses it, and the scheduled run lists Reader whole. - */ + // Reads each Reader document the kit named, so the kit can send what changed over what Reader holds. It saves no progress: the kit refuses it, and the scheduled run lists Reader whole. const lookup = async (): Promise => { // Reading a highlight's export identity needs the export client, which // only the scheduled run's preparation hands over, and that saves. @@ -903,8 +896,7 @@ export async function sync( return; } await list(); - // Picture work has its own queue and limits, after the listing and - // content work. + // Picture work has its own queue and limits, after the listing and content work. if (pictures) await drainPictures(context, reader, pictureScope.state, { account: config.account, diff --git a/connectors/readwise/src/settings.ts b/connectors/readwise/src/settings.ts index b607e29a..e502eeb3 100644 --- a/connectors/readwise/src/settings.ts +++ b/connectors/readwise/src/settings.ts @@ -1,11 +1,6 @@ import type { SettingsDeclaration } from "@withmarfa/connector"; -/** - * The defaults are the addresses and the size the code falls back to where a - * setting is not set. Writes to Reader use the `readwise_reader_*` settings - * only while `readwise_reader` is on. The Reader API address is also used to - * refresh a row Reader managed before that setting was turned off. - */ +// Defaults are what the code falls back to where a setting is unset. The Reader API address also refreshes a row Reader managed before the setting was turned off. export const settings = [ { name: "readwise_account", diff --git a/connectors/readwise/src/sync.ts b/connectors/readwise/src/sync.ts index 4dfa9a35..5351d7b0 100644 --- a/connectors/readwise/src/sync.ts +++ b/connectors/readwise/src/sync.ts @@ -23,12 +23,7 @@ import { sync as readerSync, type ReaderContext } from "./reader/sync.js"; type Context = RunContext & ReadContext & ReaderContext; -/** - * Reads the export, then, with Reader on, Reader's documents. Reader reads - * even when the export fails, since the two answer from separate APIs, and - * the first failure is the run's. `fromReader` gains the source ID of each - * export entry from Reader, whose row Reader takes over. - */ +// Reader reads even when the export fails, since the two answer from separate APIs; the first failure is the run's. export async function sync( context: Context, fromReader?: Set, @@ -52,10 +47,7 @@ export async function sync( if (rows !== undefined) await thumbnailPass(context, rows); } -/** - * A thumbnail that cannot be made leaves the source without one and is no - * condition: the source is what it was. - */ +// A thumbnail that cannot be made leaves the source as it was and is no condition. async function thumbnailPass( context: Context, rows: SourceRows, @@ -81,11 +73,6 @@ async function thumbnailPass( } } -/** - * A scope refused its progress because the kit holds every entry of a type - * for a create whose answer was lost: say that, and how it settles, in place - * of the kit's reason. - */ function explained(context: Context, held: Held, error: unknown): unknown { if ( !held.unlinkedCreate || @@ -107,8 +94,6 @@ async function read( await exportSync(context, { held }); return; } - // Pictures are a kind of their own, which ships off: with it off none is - // listed, fetched or saved. const pictures = context.written(readerPictureType.id).length > 0 ? pictureListing(context.forScope("reader-pictures").state) diff --git a/connectors/readwise/src/thumbnails.ts b/connectors/readwise/src/thumbnails.ts index 3dabfc75..6086b905 100644 --- a/connectors/readwise/src/thumbnails.ts +++ b/connectors/readwise/src/thumbnails.ts @@ -15,49 +15,30 @@ import { } from "@withmarfa/connector/thumbnails"; import { sourceType } from "./types.js"; -/** The source's field the thumbnail is kept in: the media type's own. */ export const thumbnailField = "thumbnail"; -/** At most this many thumbnails are made in one run, so an account read for - * the first time fills in over a few runs. */ export const maxThumbnailsPerRun = 50; -/** No thumbnail is begun after the pass has run this long. A fetch that has - * begun may take up to 30 seconds more. */ +// A fetch that has begun may take up to 30 seconds more. export const maxThumbnailMs = 5 * 60 * 1000; type Context = Pick, "derive" | "signal">; export interface Thumbnailed { made: number; - /** Sources whose image is refused, now or in an earlier run, for a reason - * that recurs. */ refused: number; - /** Sources still without a thumbnail that the run did not reach. */ left: number; - /** The refusals to keep for the next run, by the source's `source_id`. */ refusals: ThumbnailRefusals; - /** The `source_id` of the last source given a turn, to keep for the next - * run to start after; the last run's when this one gave none. */ cursor?: string; } -/** What a source row holds that a write of the source and the thumbnail pass - * read. */ export interface SourceRow { - /** The row's `source_id`. */ readonly id: string; readonly canonical?: string; readonly state: string; - /** The `image_url` the row holds, and the thumbnail it holds. */ readonly image?: string; readonly thumbnail?: string; } -/** - * The run's one read of the source rows, each under its `source_id` and its - * `canonical_key`. `carrying` keeps it true for what the run writes and - * archives, so nothing reads the rows again. - */ export type SourceRows = Map; function keep(rows: SourceRows, row: SourceRow): void { @@ -70,7 +51,6 @@ function forget(rows: SourceRows, row: SourceRow): void { if (row.canonical !== undefined) rows.delete(row.canonical); } -/** The source rows, as a write of a source and the thumbnail pass read them. */ export async function heldSources( context: Pick, "held">, ): Promise { @@ -91,13 +71,7 @@ export async function heldSources( return rows; } -/** - * Brings `rows` to what the sources hold after a write of `written`, the - * entries as they were sent: a row has the image and thumbnail its entry - * carried, since a write clears what it leaves out, and a row the entry takes - * over from another key is held under the new one. A row in the bin stays - * there; one archived is restored by a write of its entry. - */ +// A write clears what it leaves out, so a row has the image and thumbnail its entry carried. A row in the bin stays there; one archived is restored by a write of its entry. function wrote(rows: SourceRows, written: readonly Entry[]): void { for (const entry of written) { const canonical = entry.properties["canonical_key"]; @@ -125,7 +99,6 @@ function wrote(rows: SourceRows, written: readonly Entry[]): void { } } -/** Marks the rows an archive names, by either key, as archived. */ function archived(rows: SourceRows, keys: readonly string[]): void { for (const key of keys) { const row = rows.get(key); @@ -133,11 +106,7 @@ function archived(rows: SourceRows, keys: readonly string[]): void { } } -/** - * The entry with the thumbnail its row holds, only while the entry's image is - * the address it was made from. Another address, or none, leaves it out, so - * the write clears it and the thumbnail pass makes a new one. - */ +// Another address, or none, leaves it out, so the write clears it and the pass makes a new one. export function withThumbnail< T extends { source_id?: string; properties: Record }, >(entry: T, rows: SourceRows): T { @@ -147,11 +116,6 @@ export function withThumbnail< return withHeldThumbnail(entry, held?.thumbnail); } -/** - * The context, with every write of a source through any of its scopes - * carrying the thumbnail its row holds, and `rows` kept true for each write - * and archive of a source. Everything else is the context's own. - */ export function carrying< C extends { forScope: ( @@ -185,27 +149,14 @@ export function carrying< return { ...context, forScope }; } -/** - * Gives each active source that has an image and no thumbnail one made from - * the image. `rows` is the run's read of the sources, as `heldSources` gives - * it and `carrying` has kept it, so the pass reads no row again; each - * thumbnail it makes is put in `rows`. A picture that cannot be fetched or - * made leaves the source without one and raises no condition; a refusal that - * will come again is kept in `refusals` until the source's image changes (or, - * for a host's answer, for a week, and for a failure that may pass, for half - * an hour). Pictures are fetched from public hosts only. - */ +// A refusal that will come again is kept until the source's image changes (a host's answer a week, a failure that may pass half an hour). Pictures are fetched from public hosts only. export async function makeThumbnails( context: Context, options: { rows: SourceRows; - /** The refusals kept by the last run. */ refusals: Readonly; - /** The cursor kept by the last run, if any. */ cursor?: unknown; - /** The clock the pass is timed by, in milliseconds; for tests. */ now?: () => number; - /** The thumbnail step; for tests. */ make?: typeof thumbnailFromAddress; }, ): Promise { @@ -219,17 +170,14 @@ export async function makeThumbnails( // Each row is held under two keys. const byId = new Map(); for (const row of options.rows.values()) byId.set(row.id, row); - // Each run starts after the source the last one ended on, so sources behind - // many that are refused still have their turn. + // Each run starts after the source the last one ended on, so sources behind many refused still have their turn. for (const id of thumbnailTurns(byId.keys(), options.cursor)) { const row = byId.get(id); if (row?.image === undefined) continue; const { image, thumbnail } = row; - // A row with its thumbnail has no refusal to keep. if (heldThumbnail(image, thumbnail) !== undefined) continue; seen.add(id); - // A refusal is kept for a source in the bin or archived too, which - // brings no new look when it comes back. + // A refusal is kept for a source in the bin or archived too, which brings no new look when it comes back. if (thumbnailRefused(id, image, refusals, now)) { result.refused += 1; continue; diff --git a/connectors/readwise/src/types.ts b/connectors/readwise/src/types.ts index ffe26ffa..3a655f00 100644 --- a/connectors/readwise/src/types.ts +++ b/connectors/readwise/src/types.ts @@ -3,12 +3,7 @@ import source from "./readwise.source.json" with { type: "json" }; import highlight from "./readwise.highlight.json" with { type: "json" }; export const sourceType = source as TypeDefinition; export const highlightType = highlight as TypeDefinition; -/** - * Fields the types still declare, since a published plugin never narrows, that - * the connector no longer writes. The `retired` entry that clears them from - * existing rows stays for as long as the type declares them. The tags and the - * favorite are Marfa's own tags now. - */ +// A published plugin never narrows, so the types still declare fields the connector no longer writes; `retired` clears them from existing rows. export const retiredSourceFields = ["tags"]; export const retiredHighlightFields = ["tags", "is_favorite", "title", "body"]; export const sourceFields = [ diff --git a/connectors/readwise/test/connector.test.ts b/connectors/readwise/test/connector.test.ts index 5e9f9029..42f063ea 100644 --- a/connectors/readwise/test/connector.test.ts +++ b/connectors/readwise/test/connector.test.ts @@ -35,7 +35,6 @@ describe("with Reader off", () => { describe("highlights written before the passage moved to text", () => { const picture = "![](https://readwise-assets.s3.amazonaws.com/media/picture.png)"; - /** What the earlier release left on a row: the passage as `body`, a title from it. */ function aged( marfa: Awaited>["marfa"], sourceId: string, @@ -187,7 +186,6 @@ describe("highlights as the earlier release wrote them", () => { parent_id: "doc-1", content: whole, }); - // A Reader highlight the export does not hold. vendor.documents.set("doc-r", { id: "doc-r", category: "article", @@ -208,7 +206,6 @@ describe("highlights as the earlier release wrote them", () => { files: marfa.row("primary:highlight:13").properties["reader_text_files"], fileRows: marfa.rows.filter((row) => row.type === "readwise.file").length, }; - // What the code before this change left on each row. const old = (sourceId: string, changes: Record) => Object.assign(marfa.row(sourceId).properties, changes); old("primary:highlight:11", { @@ -227,7 +224,6 @@ describe("highlights as the earlier release wrote them", () => { title: "Reader-only passage", body: "Reader-only passage", }); - // The next run is the first one of the new release. const state = marfa.connectorState?.["state"] as { export: { shape: string }; listing: { fingerprint: string }; @@ -354,11 +350,9 @@ describe("with Reader on", () => { expect(passage.properties["reader_id"]).toBe("hi-1"); expect(passage.properties["note"]).toBe("Marfa note"); expect(marfa.tags.get(passage.id)).toEqual(["marfa"]); - // Fields are never sent. A tag only Marfa holds is added to Reader's. expect(vendor.writes).toEqual([ { method: "PATCH", path: "/v3/update/hi-1/", body: { tags: ["marfa"] } }, ]); - // A row Reader cannot take keeps mirroring the export. expect(marfa.row("primary:source:2").properties["title"]).toBe("Book"); }); @@ -370,7 +364,6 @@ describe("with Reader on", () => { async (_, paused) => { const { marfa, vendor, once } = await adopted(); marfa.edit(marfa.row("primary:source:1").id, { title: "Marfa title" }); - // The answer is lost, and Reader does not hold the write after all. vendor.uncertain(); await once().catch(() => undefined); expect(vendor.writes).toHaveLength(1); @@ -514,8 +507,7 @@ describe("with Reader on", () => { marfa.purge("primary:highlight:21"); await once(); expect(vendor.writes).toEqual([]); - // The export mirrors its own rows, so it puts the title back, and it - // refuses no change, since none is ever offered to Reader. + // The export mirrors its own rows, so it puts the title back, and it refuses no change, since none is ever offered to Reader. expect( Object.keys(marfa.problems.get("readwise") ?? {}).map( (key) => key.split(":")[0], diff --git a/connectors/readwise/test/content-pictures.test.ts b/connectors/readwise/test/content-pictures.test.ts index f664f3a8..1f5773d3 100644 --- a/connectors/readwise/test/content-pictures.test.ts +++ b/connectors/readwise/test/content-pictures.test.ts @@ -45,11 +45,7 @@ const job = (id: string, revision = "r1"): ContentJob => ({ const pictureKey = (id: string, address: string) => `${key(id)}:content:${pictureResourceId(address)}`; -/** - * One Marfa and one connector, run with Reader on (`reader`) or off - * (`export`): both share its agreements and state, and a connection a run - * names lands only when the run ends. - */ +// A connection a run names lands only when the run ends. function marfa(documents: ReaderDocument[], tier: "feed" | "library" = "feed") { const rows = new Map(); const landed = new Map(); @@ -182,7 +178,6 @@ function marfa(documents: ReaderDocument[], tier: "feed" | "library" = "feed") { }, }), }); - /** A run of a connector, ending with its connections written. */ const run = async ( who: keyof typeof agreed, jobs: ContentJob[], diff --git a/connectors/readwise/test/content-restarts.test.ts b/connectors/readwise/test/content-restarts.test.ts index 04fd439d..0e0f3810 100644 --- a/connectors/readwise/test/content-restarts.test.ts +++ b/connectors/readwise/test/content-restarts.test.ts @@ -164,7 +164,6 @@ it.each(["same bytes", "changed bytes"])( content_key: digest(latest), blob_ref: `sha256:${digest(latest)}`, }); - // Fresh preservation still replaces the value held before. incoming = file("2026-01-03T00:00:00Z", "third"); await once(); expect(server.row(fileId).properties).toMatchObject({ diff --git a/connectors/readwise/test/content-scale.test.ts b/connectors/readwise/test/content-scale.test.ts index e5a87f59..fc856902 100644 --- a/connectors/readwise/test/content-scale.test.ts +++ b/connectors/readwise/test/content-scale.test.ts @@ -467,8 +467,7 @@ it("refreshes only managed identities and their known notes from a validated lis async function readerPendingFixture(size: number) { const f = fixture(size); - // Reader lists nothing, so a run retries what is pending and works the - // queue, and what it reads of a document is a lookup. + // Reader lists nothing, so a run retries what is pending and works the queue, and what it reads of a document is a lookup. const listed = f.reader.page.bind(f.reader); f.reader.page = (query) => query?.id diff --git a/connectors/readwise/test/lifecycle-adoption.test.ts b/connectors/readwise/test/lifecycle-adoption.test.ts index 0d0bd54c..4433ed18 100644 --- a/connectors/readwise/test/lifecycle-adoption.test.ts +++ b/connectors/readwise/test/lifecycle-adoption.test.ts @@ -145,7 +145,6 @@ it.each(["safe", "lone-holder", "unknown-parent", "reactivated"])( .filter((h) => !loneHolder || h.id === 41) .map((h) => { const entry = mapHighlight("sample", 7, h); - // The lone holder: Reader took this row over earlier. if (loneHolder) entry.properties = { ...entry.properties, diff --git a/connectors/readwise/test/look.test.ts b/connectors/readwise/test/look.test.ts index 35328a42..6786de73 100644 --- a/connectors/readwise/test/look.test.ts +++ b/connectors/readwise/test/look.test.ts @@ -33,8 +33,6 @@ beforeEach(async () => { }).start(); harness = new Harness(server); vendor = await readwiseVendor({ token }); - // One document saved in Reader, with one highlight, as both the export and - // Reader list it. vendor.sources.push({ user_book_id: 1, source: "reader", @@ -73,7 +71,6 @@ const settings = () => ({ readwise_reader: true, }); -/** The first runs take Reader's document over, as an owner's do. */ async function adopted(): Promise { const built = connector(); server.install(built); @@ -84,8 +81,6 @@ async function adopted(): Promise { ).toBe(0); } -/** Runs the connector on its schedule, makes `change` once the first run is - * over, and waits for the run the next look starts, which must succeed. */ async function looked(change: () => void): Promise { const exit = start( connector(), @@ -115,7 +110,6 @@ it("sends an edit made in Marfa within a look, which succeeds and keeps no read let requests = 0; await looked(() => { - // What the scheduled run that started the connector saved. before = progress(); requests = vendor.requests.length; // Something new in Reader, so a saved listing would differ. diff --git a/connectors/readwise/test/managed.test.ts b/connectors/readwise/test/managed.test.ts index d14c1e0b..4faebcbf 100644 --- a/connectors/readwise/test/managed.test.ts +++ b/connectors/readwise/test/managed.test.ts @@ -321,7 +321,6 @@ describe("export rows Reader manages", () => { }, }; } - // Each run reads the row the last run wrote, as the connector does. function runs(exportTitle: string | undefined) { const held = managedRow(); const f = setup([held]); diff --git a/connectors/readwise/test/reader/outbound.test.ts b/connectors/readwise/test/reader/outbound.test.ts index 70d31318..fc2537d7 100644 --- a/connectors/readwise/test/reader/outbound.test.ts +++ b/connectors/readwise/test/reader/outbound.test.ts @@ -292,14 +292,12 @@ function context(propagatePurge = false) { notApplied: () => { if (intent) intent = { ...intent, requestNotApplied: true }; }, - /** The row is restored: the create comes back as it was journaled. */ rewind: (saved: OutboundIntent) => { intent = structuredClone(saved); }, forget: () => { intent = undefined; }, - /** What the next sync keeps of a pending claim. */ sync: () => { const request = intent?.request as Record | undefined; if ( @@ -415,10 +413,8 @@ it("serves a tag change that comes outside a batch with the context it was given ).rejects.toThrow("batch preflight"); }); const cover = "https://example.com/cover.png"; -/** The thumbnail the source holds, made from its picture. */ const heldThumbnail = await thumbnailFrom(cover); -/** A change of the source that carries the picture and thumbnail it holds. */ function pictured(base: Change): Change { return { ...base, @@ -1094,7 +1090,6 @@ async function lostCreate( await expect(onChange(made, c.value)).rejects.toThrow(); loseCreate = false; } -/** A claim is acknowledged on the run after the sync keeps it. */ async function claims( c: ReturnType, over: Change, @@ -1297,8 +1292,7 @@ describe.each(["trashed", "purged"] as const)( source_url: "https://example.com/new", title: "Mine", }); - // A lost answer and a request never sent look the same at Reader, so - // the one new match is claimed; Reader keeps it either way. + // A lost answer and a request never sent look the same at Reader, so the one new match is claimed; Reader keeps it either way. await claims(c, overtaking(kind, made), "mine"); expect(writes).toHaveLength(0); expect(rows.get("mine")?.title).toBe("Mine"); diff --git a/connectors/readwise/test/reader/quiet-run.test.ts b/connectors/readwise/test/reader/quiet-run.test.ts index 2f280776..8e22c6b9 100644 --- a/connectors/readwise/test/reader/quiet-run.test.ts +++ b/connectors/readwise/test/reader/quiet-run.test.ts @@ -21,8 +21,7 @@ quietRun({ edges: ["excerpt-of", "references", "attached-to"], }).start(); const vendor = await readwiseVendor({ incremental: true }); - // Highlights of one document: a document's content is preserved a few - // at a time over many runs, and its listing waits while that work is full. + // Highlights of one document: a document's content is preserved a few at a time over many runs, and its listing waits while that work is full. vendor.documents.set("doc", { id: "doc", category: "article", diff --git a/connectors/readwise/test/reader/sync.test.ts b/connectors/readwise/test/reader/sync.test.ts index a9155bb5..a92e2018 100644 --- a/connectors/readwise/test/reader/sync.test.ts +++ b/connectors/readwise/test/reader/sync.test.ts @@ -415,7 +415,6 @@ describe("Reader upgrade to display fields and kinds", () => { unknown >; expect(listing["completed"]).toBeDefined(); - // The checkpoint and rows an earlier release left: its types hashed differently. f.states.get("reader-list")?.set("listing", { ...listing, fingerprint: "an earlier release", @@ -468,7 +467,6 @@ describe("Reader upgrade to display fields and kinds", () => { expect(written.get("one:reader-document:doc")).not.toHaveProperty( "reader_image_url", ); - // Without a type change, the next run reads only what changed. await f.run(); expect(f.requests.at(-1)?.updatedAfter).toBeDefined(); }); diff --git a/connectors/readwise/test/support.ts b/connectors/readwise/test/support.ts index f0aa8650..085dda11 100644 --- a/connectors/readwise/test/support.ts +++ b/connectors/readwise/test/support.ts @@ -31,8 +31,7 @@ export async function fixture( await marfa.stop(); await vendor.close(); }); - // One document saved in Reader, with one highlight, as both the export and - // Reader list it, and one book only the export knows. + // One document saved in Reader, with one highlight, as both the export and Reader list it, and one book only the export knows. vendor.sources.push( { user_book_id: 1, diff --git a/connectors/readwise/test/tags.test.ts b/connectors/readwise/test/tags.test.ts index 7ae9c8a4..6f0cee64 100644 --- a/connectors/readwise/test/tags.test.ts +++ b/connectors/readwise/test/tags.test.ts @@ -13,7 +13,6 @@ function raised(marfa: Fixture["marfa"], prefix: string): string[] { ); } -/** The export's first source, the Reader document, with its highlight 11. */ function readerBook(vendor: Fixture["vendor"]) { const [book] = vendor.sources; const [highlight] = book?.highlights ?? []; @@ -64,7 +63,6 @@ describe("tags and favorites from the export", () => { const { marfa, vendor, once, rows } = await fixture(); const { book, highlight } = readerBook(vendor); await once(); - // What the earlier release left: the tags and the flag as properties. book.book_tags = [{ name: "kept" }]; highlight.tags = [{ name: "kept" }]; highlight.is_favorite = true; @@ -91,7 +89,6 @@ describe("tags and favorites from the export", () => { await once(); expect(vendor.writes).toEqual([]); expect(tagsOf(marfa, "primary:highlight:11")).toEqual(["a", "mine"]); - // The vendor's own change still arrives beside it. highlight.tags = [{ name: "b" }]; await once(); expect(tagsOf(marfa, "primary:highlight:11")).toEqual(["b", "mine"]); @@ -143,7 +140,6 @@ describe("tags and favorites of rows Reader manages", () => { it("adds a tag set in Marfa to Reader's own list, leaving what only Reader holds", async () => { const { marfa, vendor, once } = await managed(); - // Reader gained a tag that Marfa has not read yet. const document = vendor.documents.get("hi-1"); if (document !== undefined) document.tags = { @@ -216,7 +212,6 @@ describe("tags and favorites of rows Reader manages", () => { it("keeps a favorite set in Marfa, since Reader has none, says so, and does not send it again", async () => { const { marfa, vendor, once } = await managed(); const passage = marfa.row("primary:highlight:11"); - // Unflag it, as Marfa's own change, then flag it again. marfa.setTags(passage.id, ["retained"]); await once(readerOn); expect(vendor.writes).toEqual([]); diff --git a/connectors/readwise/test/thumbnails.test.ts b/connectors/readwise/test/thumbnails.test.ts index 8e529651..4ebd692c 100644 --- a/connectors/readwise/test/thumbnails.test.ts +++ b/connectors/readwise/test/thumbnails.test.ts @@ -19,11 +19,9 @@ import { fixture, readerOn } from "./support.js"; type Make = NonNullable[1]["make"]>; type Held = Awaited[0]["held"]>>; -/** A thumbnail Marfa takes: a JPEG data URI of canonical base64. */ const uri = `data:image/jpeg;base64,${Buffer.from([0xff, 0xd8, 0xff, 0xe0]).toString("base64")}`; const cover = "https://127.0.0.1:9/cover.jpg"; -/** By address: a thumbnail made from it, as a row holds it. */ const from: Record = Object.fromEntries( await Promise.all( [ @@ -189,7 +187,6 @@ describe("the thumbnail pass", () => { "https://a.test/drop", ]); - // A new address for a refused source is tried. asked.length = 0; const other = await pass( [row("1", { image_url: "https://a.test/other" }), ...rows.slice(1)], @@ -467,8 +464,6 @@ describe("the rows a run keeps true for the thumbnail pass", () => { refusals: {}, make, }); - // The archived one is not made; the changed one is made anew; the kept - // one carried its thumbnail through the write. expect(done.made).toBe(1); expect(run.derived).toEqual([ { keys: ["primary:source:changed"], values: { thumbnail: uri } }, @@ -490,7 +485,6 @@ describe("a run with thumbnails", () => { await made.once(); const source = made.marfa.row("primary:source:1"); expect(source.properties["image_url"]).toBe(cover); - // As the pass of an earlier run left it. source.properties["thumbnail"] = from[cover]; return { ...made, book }; } @@ -609,7 +603,6 @@ describe("the turns of the thumbnail pass", () => { ...Array.from({ length: refused }, (_, n) => row(String(n), { image_url: `https://a.test/${String(n)}.svg` }), ), - // A new source lands at the end. row("good", { image_url: good }), ]; const { context, derived, sources } = await pass(held, make); @@ -700,7 +693,6 @@ describe("a thumbnail and the picture it was made from", () => { height: 3, }); }; - // A person changed the image in Marfa after the thumbnail was made. const { context, sources } = await pass( [row("1", { image_url: now, thumbnail: stale })], make, diff --git a/connectors/rss/src/definition.ts b/connectors/rss/src/definition.ts index 076eb483..d6d101ba 100644 --- a/connectors/rss/src/definition.ts +++ b/connectors/rss/src/definition.ts @@ -42,38 +42,25 @@ import { makeThumbnails } from "./thumbnails.js"; interface FeedState { validators?: Validators; - /** The key of the address the validators belong to. */ address?: string; - /** The key the feed's rows were last written under. */ key?: string; - /** Keys its rows were written under before, newest first: a row in the bin - * or purged stays under one, so every read names them. */ + // A row in the bin or purged stays under an earlier key, so every read names them. was?: string[]; - /** Earlier keys another saved feed also wrote under, whose rows are left - * where they are rather than handed to either. */ shared?: string[]; unkeyed?: number; dropped?: number; unconverted?: number; substituted?: number; late?: number; - /** The `renderVersion` its entries were last written under: validators - * from an older one are not sent, so the feed is read whole. */ + // Validators from an older `renderVersion` are not sent, so the feed is read whole. render?: number; declared?: string; - /** When it left rss_feeds, for a feed kept only so its earlier keys are - * named again if it returns. */ left?: string; - /** Set when its address answered 410: it is not read again while its - * `address` stays the one that answered. */ + // Its address answered 410: it is not read again while `address` stays the one that answered. gone?: true; - /** Set when its address answers with a permanent redirect, which is - * followed. */ moved?: true; } -/** Feeds kept after leaving the list, newest first; one leaves only by the - * owner's edit, so this holds a long history of them. */ const maxDeparted = 100; const thumbnailField = "thumbnail"; @@ -105,8 +92,6 @@ function refusal(error: unknown): string | undefined { return undefined; } -/** The connector for the settings a run reads, which the kit builds again at - * the start of each run. */ export function connector() { return defineConnector({ name: "rss", @@ -122,10 +107,8 @@ export function connector() { { name: "entry", direction: "in", - // Imported JSON widens every string, so its field types read as - // `string` here; the check on start holds the file to the server's. + // Imported JSON widens every string; the check on start holds the file to the server's. type: rssEntry as TypeDefinition, - // The thumbnail is the core bookmark's own, which the entry inherits. fields: [...entryFields, manifestField, thumbnailField], readOnly: [manifestField, thumbnailField], derived: [manifestField, thumbnailField], @@ -168,10 +151,7 @@ export function connector() { } } - // A feed renamed, or named for the first time, in the same edit finds - // its rows by its address; one moved under its name keeps its key. A - // feed that left the list is found again by its key alone: another - // account can be read at the same address. + // A feed renamed in the same edit finds its rows by its address; one that left the list is found again by its key alone, since another account can be read at the same address. const previous = (feed: Feed): { held: FeedState; id?: string } => { const own = known[feed.key]; if (own !== undefined) { @@ -198,9 +178,7 @@ export function connector() { }; const records = new Map(feeds.map((feed) => [feed, previous(feed)])); - // Rows are moved from an earlier key only when this feed alone held it: - // never from a key another listed feed now owns, nor one another saved - // feed also wrote under. + // Rows move from an earlier key only when this feed alone held it. const sharedWith = (key: string, id: string | undefined): boolean => configured.has(key) || [...(holders.get(key) ?? [])].some((holder) => holder !== id); @@ -439,9 +417,7 @@ export function connector() { kept[feed.key] = now; raise(feed, now); signal.throwIfAborted(); - // Each feed is a scope of its own, so its reading progress is saved - // once its entries are acknowledged and a refused entry in one feed - // holds back that feed alone. + // Each feed is a scope of its own, so a refused entry in one feed holds back that feed alone. const written = carrying( was.length === 0 ? parsed.entries @@ -476,8 +452,7 @@ export function connector() { } state.set("feeds", { ...kept, ...Object.fromEntries(departed) }); if (thumbnails) { - // A thumbnail that cannot be made leaves the entry without one, and - // is no condition: the entry is what it was. + // A thumbnail that cannot be made leaves the entry as it was and is no condition. try { const done = await makeThumbnails(context, { privateHosts: allowed, diff --git a/connectors/rss/src/feeds.ts b/connectors/rss/src/feeds.ts index 50def76a..8ab1dd44 100644 --- a/connectors/rss/src/feeds.ts +++ b/connectors/rss/src/feeds.ts @@ -11,22 +11,15 @@ import { parseFeed, parseJsonFeed } from "feedsmith"; import { DomUtils, ElementType, parseDocument } from "htmlparser2"; import { getFeed } from "./fetch.js"; -/** Past it a feed is skipped: its entries would be a run's worth of writes. */ export const maxFeedEntries = 5000; -/** Parsing holds an object per element, so their count, more than the - * bytes, sets the memory a feed takes; the largest real feeds hold about - * 200,000. */ +// Parsing holds an object per element, so their count, more than the bytes, sets the memory a feed takes; the largest real feeds hold about 200,000. export const maxFeedElements = 300_000; -/** Parsing holds an object per attribute as well, and a feed of few elements - * can carry millions of them, so their count is bounded too; the largest real - * feeds hold well under a third of it. */ +// Parsing holds an object per attribute too, and a feed of few elements can carry millions of them; the largest real feeds hold well under a third of this. export const maxFeedAttributes = 1_000_000; -/** What a read may hand back, serialized: about three times the largest real - * feed checked. A value every entry repeats, such as the feed's title, - * counts once per entry, as it is written once per row. */ +// What a read may hand back, serialized: about three times the largest real feed checked. A value every entry repeats, such as the feed's title, counts once per entry. export const maxResultChars = 32 * 1024 * 1024; export class TooManyEntries extends Error { @@ -41,16 +34,7 @@ export class TooManyAttributes extends Error { override name = "TooManyAttributes"; } -/** - * A cheap refusal before the parse: counts each `<` that opens an element or a - * `]*/y; const tagEnd = /["'>]/g; @@ -124,14 +108,9 @@ function countTags(text: string): void { } export interface Feed { - /** Its place in rss_feeds, counted from 1, by which a condition names it - * where its address may not go. */ position: number; url: string; - /** What its entries are keyed by: its name in rss_feeds, else its address. - * Owned by the configuration, never by what the feed says of itself. */ key: string; - /** The key of its address, which its validators belong to. */ address: string; } @@ -162,11 +141,6 @@ function isAddress(value: string): boolean { } } -/** - * Each entry is an address, or `name=address`: a feed named keeps its - * entries when its address moves or a token in it rotates. Two spellings of - * one unnamed address are one feed, read once. - */ export function feedList(value: string): Feed[] { const parts = value.split(/\s+/).filter((part) => part !== ""); const read = parts.map((part, at) => { @@ -265,7 +239,6 @@ export function decodeFeed( return new TextDecoder("utf-8").decode(bytes); } -/** Hosts the owner allows to resolve to this machine or a private network, from `rss_private_hosts`. */ export function privateHosts(value: string | undefined): Set { return privateHostSet(value, "rss_private_hosts"); } @@ -450,15 +423,11 @@ type Picture = ReturnType[number]; interface Reading { plain: string | undefined; - /** Whether it holds an element, so is HTML and not text. */ marked: boolean; - /** Whether it shows nothing: no text, and no element but tracking pixels - * and wrappers that hold nothing. */ empty: boolean; pictures: Picture[]; } -// Elements that show nothing of their own. const wrappers = new Set(["br", "div", "p", "span", "wbr"]); function readingOf(markup: string | undefined): Reading | undefined { @@ -508,13 +477,10 @@ function isTiny(picture: Picture): boolean { interface Counted { url: string; - /** What the picture says of itself: its title, else its alt. */ caption: string | undefined; } -// The first picture whose address is an http or https link once resolved -// against the entry's base, so a data: URI or a link relative to the fetch -// path is passed over, and which does not declare itself a pixel. +// The first picture whose address is an http or https link once resolved against the entry's base: one relative to the fetch path, where a private feed may carry its token, is passed over. function countedPicture( reading: Reading | undefined, base: Base, @@ -531,10 +497,8 @@ function countedPicture( } interface Summary { - /** What the feed's summary or description says, in HTML or plain text. */ value: string | undefined; - /** Whether the value may hold markup: an Atom summary of type `text` may - * not, and an RSS description may. */ + // An Atom summary of type `text` may not hold markup, and an RSS description may. html: boolean; } @@ -545,10 +509,7 @@ interface Written { } interface Images { - /** An image the entry names as its own: an enclosure, or a JSON Feed's - * `image`. */ enclosure: string | undefined; - /** What `media:thumbnail` offers, used where nothing else gives a picture. */ thumbnail: string | undefined; } @@ -561,9 +522,6 @@ interface Media extends Thumbnails { groups?: (Thumbnails & { contents?: Thumbnails[] })[]; } -// The first `media:thumbnail` that is an http or https link once resolved -// and does not declare itself a pixel, looked for where the entry names one, -// then in its media groups and media contents. function thumbnailOf(media: Media | undefined, base: Base): string | undefined { const places = [ media, @@ -583,18 +541,10 @@ function thumbnailOf(media: Media | undefined, base: Base): string | undefined { return undefined; } -/** - * What this connector writes for an entry's markup. Raise it when a change - * to how `body` is rendered should reach entries already stored: a feed is - * then read whole once, though its server says it has not changed. - */ +// Raise it when a change to how `body` is rendered should reach entries already stored: a feed is then read whole once, though its server says it has not changed. export const renderVersion = 1; -/** What a feed's conversions may take, added up. One conversion is bounded by - * the kit's limits on length, elements and depth, so this holds a feed of - * many large entries to a share of the time its parse may take. Once it is - * spent, an entry with markup is not written this run, so the next run reads - * the feed again, and the rest of the feed is read. */ +// Added up over a feed's conversions, so a feed of many large entries is held to a share of the time its parse may take. Once spent, an entry with markup is not written this run and the next run reads the feed again. export const conversionBudgetMs = 12_000; interface Converting { @@ -602,20 +552,12 @@ interface Converting { readonly budget: number; } -/** What converting one piece of markup came to: its Markdown, or why there is - * none. */ interface Converted { readonly markdown: string | undefined; readonly failure: "refused" | "late" | undefined; } -/** - * Converts markup to the Markdown a body holds. Links and pictures resolve - * against the entry's base, so one relative to the fetch path, where a - * private feed may carry its token, is left out as the entry's other links - * are. Markup the converter refuses has no Markdown, and markup that comes - * after the feed's budget is spent is not converted at all. - */ +// Links and pictures resolve against the entry's base, so one relative to the fetch path, where a private feed may carry its token, is left out. function markdownOf( markup: string | undefined, base: Base, @@ -643,14 +585,6 @@ function markdownOf( } } -/** - * A feed's content is its content element where it has one, else its - * summary where that holds markup. Both are written as Markdown where they - * are HTML, and as they are where they are text. The description is the - * summary as plain text, or for a summary that is only a picture, that - * picture's caption. Returns `"late"` for an entry whose markup came after - * the feed's budget was spent. - */ function contentOf( summary: Summary, content: string | undefined, @@ -710,25 +644,16 @@ interface Counts { late: number; } -/** Marfa's default cap on a string property: a longer one is refused, and - * the entry with it. */ +// Marfa's default cap on a string property: a longer one is refused, and the entry with it. export const maxFieldLength = 100_000; export interface Read { entries: Entry[]; unkeyed: number; - /** Values longer than Marfa takes, left out of their entries. */ dropped: number; - /** Entries whose markup could not be converted, so they have no body. */ unconverted: number; - /** Entries whose markup could not be converted, so they have the plain text - * of their content for a body instead. */ substituted: number; - /** Entries not written because the feed's conversion budget was spent - * before their markup was reached. */ late: number; - /** A hash of the id an Atom feed declares for itself, which identifies - * nothing here and is compared only to say two feeds claim one id. */ declared: string | undefined; } @@ -748,8 +673,7 @@ export const entryFields = [ "feed_hash", ] as const; -/** The `xml:base` on an RSS 2.0 ``, which feedsmith does not read, - * taken from that start tag alone rather than a second parse of the feed. */ +// Taken from the start tag alone rather than a second parse of the feed. function channelBaseOf(text: string): string | undefined { const start = /]*>/.exec(text)?.[0]; if (start === undefined) return undefined; diff --git a/connectors/rss/src/fetch.ts b/connectors/rss/src/fetch.ts index 060be7ea..e57d4394 100644 --- a/connectors/rss/src/fetch.ts +++ b/connectors/rss/src/fetch.ts @@ -13,15 +13,11 @@ import { createBrotliDecompress, createGunzip, createInflate } from "node:zlib"; const fetchTimeoutMs = 60_000; -/** Applied to the bytes on the wire and again to the bytes they decompress - * to, so a compressed bomb stops where a plain body would. Large podcast - * feeds run to about 20 MiB. */ +// Applied to the bytes on the wire and to the decompressed bytes, so a compressed bomb stops where a plain body would. Large podcast feeds run to about 20 MiB. export const maxFeedBytes = 24 * 1024 * 1024; export const maxRedirects = 5; -/** A product token and where to read about it, as sites ask of a crawler. - * It carries no version: a version exists only as a git tag. */ export const userAgent = "MarfaRSS (+https://github.com/withmarfa/plugins)"; export class TooLarge extends Error { @@ -50,10 +46,7 @@ const plainly: Record = { "its certificate is not one this machine trusts", }; -/** - * Why a feed could not be fetched, in plain words, from the error's code, - * never its message, which a transport may write the address into. - */ +// From the error's code, never its message, which a transport may write the address into. export function failureOf(error: unknown): string { for ( let at: unknown = error, depth = 0; @@ -154,24 +147,15 @@ async function bodyOf( export interface Answer { status: number; headers: IncomingMessage["headers"]; - /** Only on a 200. */ bytes?: Uint8Array; - /** Where the answer came from, after any redirects. */ url: string; - /** Whether the feed's own address answered with a permanent redirect. */ moved: boolean; } const redirects = new Set([301, 302, 303, 307, 308]); const permanent = new Set([301, 308]); -/** - * Follows redirects by hand, checking every hop, the first among them: a host - * that resolves to this machine or a private network is refused unless the - * owner named it in `privateHosts`, or listed the feed by a private address - * itself. The credentials a listed address carries go to its own origin - * alone. - */ +// Follows redirects by hand so every hop, the first included, is checked against the private hosts; the credentials a listed address carries go to its own origin alone. export async function getFeed( configured: string, headers: Readonly>, @@ -180,7 +164,6 @@ export async function getFeed( ): Promise { const signal = AbortSignal.any([outer, AbortSignal.timeout(fetchTimeoutMs)]); const start = new URL(configured); - // Sent as the Basic authorization the address's userinfo stands for. const credentials = start.username !== "" || start.password !== "" ? `Basic ${Buffer.from(`${decodeURIComponent(start.username)}:${decodeURIComponent(start.password)}`).toString("base64")}` diff --git a/connectors/rss/src/parse.ts b/connectors/rss/src/parse.ts index 30abc32f..4369c0ff 100644 --- a/connectors/rss/src/parse.ts +++ b/connectors/rss/src/parse.ts @@ -23,9 +23,6 @@ export interface ParseInput { documentUrl: string; } -/** Whether a read comes to no more than `maxResultChars` once serialized, - * counted entry by entry so a value every entry shares is paid for once per - * entry and never copied out past the cap. */ function withinCap(read: Read): boolean { const { entries, ...rest } = read; let length = JSON.stringify(rest).length; @@ -36,12 +33,6 @@ function withinCap(read: Read): boolean { return true; } -/** - * Decodes and reads a feed. What bounds it is its size, which the fetch - * limits, the counts `readFeed` refuses past (elements, attributes and - * entries) and the cap on what it reads to; the process's heap limit - * (`host/src/permission-flags.ts`) stands above all of them. - */ export function readDocument(input: ParseInput, signal: AbortSignal): Read { signal.throwIfAborted(); let read: Read; diff --git a/connectors/rss/src/pictures.ts b/connectors/rss/src/pictures.ts index 784c6a42..aade3874 100644 --- a/connectors/rss/src/pictures.ts +++ b/connectors/rss/src/pictures.ts @@ -15,8 +15,6 @@ import { heldThumbnail } from "@withmarfa/connector/thumbnails"; import rssEntry from "./rss.entry.json" with { type: "json" }; import rssPicture from "./rss.picture.json" with { type: "json" }; -/** A picture's type, the entry's property that accounts for its pictures, - * and the connection that attaches one to the other. */ export const pictureTypeId = rssPicture.id; export const manifestField = "rss_pictures"; export const attachedTo: ConnectionDefinition = { @@ -27,8 +25,6 @@ export const attachedTo: ConnectionDefinition = { to_type_constraints: [rssEntry.id], }; -/** The kind ships off: it saves no picture and fetches none until the owner - * turns it on in the mapping. */ export const pictureKind: Kind = { name: "picture", direction: "in", @@ -37,36 +33,19 @@ export const pictureKind: Kind = { fields: ["title", "source_url", "blob_ref", "mime_type"], }; -/** At most this many distinct picture addresses are read from one entry's - * image and text, in the order they come; the rest are only counted. */ export const maxPicturesPerEntry = 20; -/** At most this many pictures are fetched in one run. */ export const maxPicturesPerRun = 100; -/** A picture that would take the bytes saved in one run past this is left - * for the next run. */ export const maxBytesPerRun = 200 * 1024 * 1024; -/** No picture is fetched after the pass has run this long. The pictures it - * did not reach stay pending for the next run. A fetch that has begun may - * take up to 30 seconds more. */ +// A fetch that has begun may take up to 30 seconds more. export const maxPassMs = 10 * 60 * 1000; -/** A picture whose fetch fails in a way that may pass is asked for this many - * times, a run at a time, before it is not kept. */ export const maxAttempts = 3; -/** A longer address is not read from an entry's text. */ export const maxAddressLength = 2048; -/** Why a picture was left out, beside the reasons the kit's fetch gives. */ export type Reason = "removed" | "not_https"; -/** Failures that may pass, which are asked for again in a later run. */ const transient = new Set(["timed_out", "fetch_failed", "upload_failed"]); -/** - * Whether a refused picture may be fetched later. A failure of the transfer - * may pass. So may an answer that asks a client to wait or try again: 408, - * 425, 429 and any 5xx. Any other status, such as a 404 or a 403, is a - * host's answer about this picture and stays refused. - */ +// 408, 425, 429 and any 5xx ask a client to wait or retry; any other status is the host's answer about this picture. export function mayPass(reason: string, status?: number): boolean { if (transient.has(reason)) return true; return ( @@ -77,17 +56,11 @@ export function mayPass(reason: string, status?: number): boolean { } export interface Manifest { - /** A hash of the text the addresses were read from. */ text: string; - /** Addresses whose pictures are held. */ saved: string[]; - /** Addresses to try again in the next run. */ pending: string[]; - /** Addresses given up on, each with the reason, until the text changes. */ not_kept: Record; - /** How many runs a pending address has failed in. */ attempts?: Record; - /** How many addresses past the limit for one entry were not read. */ over?: number; } @@ -102,7 +75,6 @@ const strings = (value: unknown): string[] | undefined => ? value : undefined; -/** A manifest as the entry holds it, or `undefined` for anything else. */ export function manifestOf(value: unknown): Manifest | undefined { const at = object(value); const saved = strings(at["saved"]); @@ -130,7 +102,6 @@ export function manifestOf(value: unknown): Manifest | undefined { const sha256 = (text: string | Uint8Array): string => createHash("sha256").update(text).digest("hex"); -/** The hash of the text a manifest was read from. */ export function textHash(body: unknown, image: unknown): string { return sha256( JSON.stringify([ @@ -140,17 +111,10 @@ export function textHash(body: unknown, image: unknown): string { ); } -// A Markdown image: its label, then its destination, which the converter -// writes without spaces, parentheses or angle brackets, and an optional title. +// A Markdown image: its label, then its destination, which the converter writes without spaces, parentheses or angle brackets, and an optional title. const markdownImage = /!\[(?:\\.|[^\]\\])*\]\(\s*]+)>?(?:\s+(?:"[^"]*"|'[^']*'))?\s*\)/g; -/** - * The web addresses of an entry's pictures: its image, then the Markdown - * images in its body, each once. Only `http` and `https` addresses count; - * another scheme, a relative address and one over `maxAddressLength` are not - * addresses to save. - */ export function addressesOf( body: unknown, image: unknown, @@ -182,14 +146,10 @@ const extensions: Record = { "image/heic": "heic", }; -/** A picture's `source_id`: the id of its entry's row, which holds when a - * feed's key changes and its entries are moved to new ones, a number sign, - * and a hash of the address. */ export function pictureId(entryRow: string, address: string): string { return `${entryRow}#${sha256(address).slice(0, 32)}`; } -/** The id of the entry row a picture was saved for. */ export function entryOf(pictureId: string): string { return pictureId.slice(0, pictureId.lastIndexOf("#")); } @@ -203,13 +163,7 @@ type Context = Pick< "held" | "archive" | "derive" | "upsert" | "inspect" | "signal" | "log" >; -/** - * The hosts a picture of an entry may be fetched from although they resolve to - * this machine or a private network: the host the owner listed, and only when - * it is also the host of the entry's own feed. The owner's leave is for the - * feed it was given for, so a feed's text cannot send the connector to an - * internal host that is listed for another. - */ +// The owner's leave is for the feed it was given for, so a feed's text cannot send the connector to an internal host listed for another. export function privateHostsFor( listed: ReadonlySet, feedOrigin: unknown, @@ -224,8 +178,6 @@ export function privateHostsFor( : new Set(); } -/** Whether a picture row, read with its edges, holds an `attached-to` - * connection to the entry row. */ function isAttached(picture: Item, entryRow: string): boolean { return ( picture.edges?.[attachedTo.id]?.data.some( @@ -234,23 +186,14 @@ function isAttached(picture: Item, entryRow: string): boolean { ); } -/** What an entry's row holds that the connector sets after the read, and a - * write of the entry would clear, with what the thumbnail pass reads of it. */ export interface Kept { readonly manifest?: Manifest; - /** The address of the entry's image, and the thumbnail the row holds. */ readonly image?: string; readonly thumbnail?: string; - /** The row's state; a row the run wrote first is active. */ readonly state?: string; - /** The `feed_origin` the row holds. */ readonly origin?: unknown; } -/** - * What the entries hold of it, by `source_id`, for a read to carry. It is the - * run's one read of the rows: `wrote` keeps it true for what the run writes. - */ export async function keptBy( context: Pick, ): Promise> { @@ -271,12 +214,6 @@ export async function keptBy( return kept; } -/** - * Brings `kept` to what the rows hold after a write of `written`, the entries - * as they were sent: each row has the image, thumbnail and manifest the entry - * carried, since a write clears what it leaves out, and a row moved from - * another key is held under the new one. - */ export function wrote( kept: Map, written: readonly Entry[], @@ -300,12 +237,7 @@ export function wrote( } } -/** - * The entries with what their rows hold, so that a write of the entry does - * not clear what accounts for its pictures or its thumbnail. The thumbnail - * goes only to an entry whose image is the address it was made from: another - * address leaves it out, and the thumbnail pass makes a new one. - */ +// A write of an entry clears what it leaves out, so each entry carries what its row holds. The thumbnail goes only to an entry whose image is the address it was made from. export function carrying( entries: readonly Entry[], kept: ReadonlyMap, @@ -342,19 +274,11 @@ export interface Saved { revived: number; } -/** - * One pass over the entries: archives the pictures of - * entries that are no longer active, brings back those of entries that are - * active again, and for each entry whose pictures are not all accounted for, - * saves what it can and records the rest. - */ export async function savePictures( context: Context, options: { privateHosts: ReadonlySet; - /** The clock the pass is timed by, in milliseconds; for tests. */ now?: () => number; - /** The picture fetch; for tests. */ fetch?: typeof fetchPicture; }, ): Promise { @@ -371,11 +295,7 @@ export async function savePictures( }; const entries = await context.held(rssEntry.id, { state: "any" }); const states = new Map(entries.map((row) => [row.id, row])); - // The connector's pictures are read in pages of up to 500, each row with - // the connections it holds, so that whether a picture is attached to its - // entry is known without asking about each entry. The first read comes - // before anything is fetched or written, so when it fails the next run - // starts from what this one found. + // The first read comes before anything is fetched or written, so when it fails the next run starts from what this one found. const pictures = new Map(); const readPictures = async (): Promise => { for (const row of await context.held(pictureTypeId, { @@ -387,11 +307,7 @@ export async function savePictures( }; await readPictures(); - // A picture follows its entry out of use: an attached picture goes into the - // bin with its entry, and one still active whose entry is archived, trashed - // or gone, such as one saved before its connection was written, is archived. - // The kit leaves a row a person has restored since, so what was archived is - // read back rather than assumed. + // A picture follows its entry out of use; the kit leaves a row a person has restored since, so what was archived is read back rather than assumed. const gone = [...pictures] .filter( ([id, row]) => @@ -406,9 +322,7 @@ export async function savePictures( ).length; } - // Pictures of an active entry that are archived: the kit brings back the - // ones this connector archived when the entry is written again, and leaves - // the ones a person or anything else archived. + // The kit brings back the pictures this connector archived when the entry is written again, and leaves the ones a person or anything else archived. const revival: string[] = []; let limit: string | undefined; let bytes = 0; @@ -427,11 +341,7 @@ export async function savePictures( if (prior === undefined && addresses.length === 0) continue; const same = prior?.text === text ? prior : undefined; - // An entry is left alone while its manifest still tells the truth: the - // text is the one it was read from, nothing waits, and each picture it - // lists is held, active and attached to it. A run that stopped after a - // picture was saved leaves the picture without its connection, since - // connections are written when a run ends. + // An entry is left alone while its manifest tells the truth. A run that stopped after a picture was saved leaves it without its connection, which is written when a run ends. if ( same?.pending.length === 0 && same.saved.every((address) => { @@ -453,8 +363,7 @@ export async function savePictures( } else open.push(address); } - // A picture removed in Marfa is not saved again for this entry, and one - // already held is not fetched again. + // A picture removed in Marfa is not saved again for this entry, and one already held is not fetched again. const ids = new Map(open.map((a) => [a, pictureId(entry.id, a)])); const missing = [...ids.values()].filter((id) => !pictures.has(id)); const purged = new Set( @@ -480,7 +389,6 @@ export async function savePictures( next.saved.push(address); const archived = held.state === "archived"; if (archived || !isAttached(held, entry.id)) { - // The row as it is, written again with its connection. repairs.push({ source_id: id, properties: Object.fromEntries( diff --git a/connectors/rss/src/thumbnails.ts b/connectors/rss/src/thumbnails.ts index 41249a98..36ec77cd 100644 --- a/connectors/rss/src/thumbnails.ts +++ b/connectors/rss/src/thumbnails.ts @@ -11,53 +11,29 @@ import { import { privateHostsFor, type Kept } from "./pictures.js"; import rssEntry from "./rss.entry.json" with { type: "json" }; -/** At most this many thumbnails are made in one run, so a feed read for the - * first time fills in over a few runs. */ export const maxThumbnailsPerRun = 50; -/** No thumbnail is begun after the pass has run this long. A fetch that has - * begun may take up to 30 seconds more. */ +// A fetch that has begun may take up to 30 seconds more. export const maxThumbnailMs = 5 * 60 * 1000; type Context = Pick, "derive" | "signal">; export interface Thumbnailed { made: number; - /** Entries whose image is refused, now or in an earlier run, for a reason - * that recurs. */ refused: number; - /** Entries still without a thumbnail that the run did not reach. */ left: number; - /** The refusals to keep for the next run, by the entry's `source_id`. */ refusals: ThumbnailRefusals; - /** The `source_id` of the last entry given a turn, to keep for the next - * run to start after; the last run's when this one gave none. */ cursor?: string; } -/** - * Gives each active entry that has an image and no thumbnail one made from - * the image. `rows` is the run's read of the entries, as `keptBy` gives it - * and `wrote` has kept it, so the pass reads no row again. Each thumbnail it - * makes is put in `rows`, and written only to an entry that still holds the - * image it was made from. A thumbnail is kept while the image's address is - * the one it was made from, since each write of an entry carries it only - * then. A picture - * that cannot be fetched or made leaves the entry without one and raises no - * condition; a refusal that will come again is kept in `refusals` until the - * entry's image changes (or, for a host's answer, for a week). - */ +// A thumbnail is kept while the image's address is the one it was made from, since each write of an entry carries it only then. export async function makeThumbnails( context: Context, options: { privateHosts: ReadonlySet; rows: Map; - /** The refusals kept by the last run. */ refusals: Readonly; - /** The cursor kept by the last run, if any. */ cursor?: unknown; - /** The clock the pass is timed by, in milliseconds; for tests. */ now?: () => number; - /** The thumbnail step; for tests. */ make?: typeof thumbnailFromAddress; }, ): Promise { @@ -68,17 +44,14 @@ export async function makeThumbnails( if (typeof options.cursor === "string") result.cursor = options.cursor; const seen = new Set(); let attempted = 0; - // Each run starts after the entry the last one ended on, so entries behind - // many that are refused still have their turn. + // Each run starts after the entry the last one ended on, so entries behind many refused still have their turn. for (const id of thumbnailTurns(options.rows.keys(), options.cursor)) { const held = options.rows.get(id); const image = held?.image; if (held === undefined || image === undefined) continue; - // A row with its thumbnail has no refusal to keep. if (heldThumbnail(image, held.thumbnail) !== undefined) continue; seen.add(id); - // A refusal is kept for an entry in the bin or archived too, which - // brings no new look when it comes back. + // A refusal is kept for an entry in the bin or archived too, which brings no new look when it comes back. if (thumbnailRefused(id, image, refusals, now)) { result.refused += 1; continue; diff --git a/connectors/rss/test/fixtures/documents.js b/connectors/rss/test/fixtures/documents.js index 3806d945..ff50a85b 100644 --- a/connectors/rss/test/fixtures/documents.js +++ b/connectors/rss/test/fixtures/documents.js @@ -3,8 +3,7 @@ const rss = (channel) => `${channel}`; -/** Few elements, each with thousands of attributes: under the element and - * entry counts, and far over the attribute count. */ +// Few elements, each with thousands of attributes: under the element and entry counts, far over the attribute count. export function heavyDocument() { const attributes = Array.from({ length: 4000 }, (_, at) => `a${at}="v"`).join( " ", @@ -15,8 +14,7 @@ export function heavyDocument() { ); } -/** A channel title under the field cap, which every one of thousands of small - * entries carries. */ +// A channel title under the field cap, which every one of thousands of small entries carries. export function sharedDocument() { const items = Array.from( { length: 4000 }, @@ -25,8 +23,6 @@ export function sharedDocument() { return rss(`${"t".repeat(90000)}${items}`); } -/** As many attributes as the count allows, in few elements: the most that a - * feed of this shape asks of a read. */ export function attributeDocument() { const attributes = Array.from({ length: 4000 }, (_, at) => `a${at}="v"`).join( " ", @@ -35,19 +31,16 @@ export function attributeDocument() { return rss(`T${item.repeat(249)}`); } -/** As many elements as the count allows, each with a few attributes. */ export function wideDocument() { return rss(`T${''.repeat(299_000)}`); } const names = (count) => Array.from({ length: count }, (_, at) => `a${at}`); -/** Millions of attributes with no value, in one element. */ export function bareAttributesDocument() { return rss(`T`); } -/** Millions of attributes with an unquoted value, in one element. */ export function unquotedAttributesDocument() { return rss( `T `Ttg`, ); -/** One entry whose markup holds millions of elements. */ export function manyElementsDocument() { return withDescription("x".repeat(2_500_000)); } -/** One entry whose markup nests millions of elements deep. */ export function nestedElementsDocument() { return withDescription("
".repeat(3_000_000)); } diff --git a/connectors/rss/test/fixtures/measure.js b/connectors/rss/test/fixtures/measure.js index 283b71a2..64b51445 100644 --- a/connectors/rss/test/fixtures/measure.js +++ b/connectors/rss/test/fixtures/measure.js @@ -1,6 +1,4 @@ -// Reads one strained document through the built connector's read in a -// process of its own, whose high-water marks start clean, and prints how it -// ended and how much the process grew. +// Reads one strained document in a process of its own, whose high-water marks start clean, and prints how it ended and how much the process grew. /* global process, TextEncoder, AbortSignal, console */ import { resolve } from "node:path"; import { diff --git a/connectors/rss/test/pictures.test.ts b/connectors/rss/test/pictures.test.ts index c089994b..840b38e4 100644 --- a/connectors/rss/test/pictures.test.ts +++ b/connectors/rss/test/pictures.test.ts @@ -34,8 +34,6 @@ import { const run = promisify(execFile); const built = resolve(import.meta.dirname, "../dist/main.js"); -// ---- A picture with the smallest header the kit's reader needs. ---- - function png(seed: number, padding = 0): Buffer { const u32 = (n: number): Buffer => { const b = Buffer.alloc(4); @@ -57,8 +55,6 @@ function png(seed: number, padding = 0): Buffer { const sha = (text: string | Buffer): string => createHash("sha256").update(text).digest("hex"); -// ---- A local HTTPS server, with a certificate made for the run. ---- - const directory = mkdtempSync(join(tmpdir(), "rss-pictures-")); execFileSync( "openssl", @@ -125,8 +121,6 @@ afterAll(async () => { rmSync(directory, { recursive: true }); }); -// ---- The connector, run as a process, reading JSON Feeds. ---- - interface Item { id: string; title?: string; @@ -252,7 +246,6 @@ describe("the pictures an entry points to", () => { expect(marfa.rows.filter((row) => row.type === "rss.picture")).toEqual([]); expect(marfa.uploads).toBe(0); - // Turned on, the entries it already holds are looked at. marfa.mapping.kinds["picture"] = { enabled: true }; marfa.mapping.version = 3; asked = []; @@ -265,7 +258,6 @@ describe("the pictures an entry points to", () => { documents["/one.json"] = [{ id: "e1", title: "One" }]; expect((await once()).code).toBe(0); - // A key for the entry type alone. await marfa.stop(); marfa = await new ScriptedServer("rss", { types: ["rss.entry"] }).start(); const narrow = await once(); @@ -308,7 +300,6 @@ describe("the pictures an entry points to", () => { expect(held.pending).toEqual([]); expect(held.not_kept).toEqual({}); expect(held.text).toMatch(/^[0-9a-f]{64}$/); - // The entry's text is not rewritten. expect(entry("e1").properties["body"]).toContain(at("/a.png")); }); @@ -332,8 +323,6 @@ describe("the pictures an entry points to", () => { expect(filesOf("e1")[0]?.version).toBe(fileVersion); expect(entry("e1").version).toBe(version); - // The feed changes the title only: the entry is written again, and the - // write does not clear the manifest. documents["/one.json"] = [ { id: "e1", title: "One, renamed", content_html: img(at("/a.png")) }, ]; @@ -372,8 +361,6 @@ describe("the pictures an entry points to", () => { expect((await once()).code).toBe(0); expect(asked).toEqual([]); - // A change to the text is a reason to ask again: the address that was - // gone is back, and it is saved. pictures["/missing.png"] = { body: png(4) }; documents["/one.json"] = [ { @@ -435,7 +422,6 @@ describe("the pictures an entry points to", () => { expect((await once()).code).toBe(0); expect(asked).toEqual([]); - // A picture that comes back before the last attempt is saved. documents["/one.json"] = [ { id: "e2", title: "Two", content_html: img(at("/later.png")) }, ]; @@ -634,7 +620,6 @@ describe("the pictures an entry points to", () => { 2, ); - // Settled: another run changes nothing. const version = filesOf("e1")[0]?.version; expect((await once()).code).toBe(0); expect(filesOf("e1")[0]?.version).toBe(version); @@ -656,7 +641,6 @@ describe("the pictures an entry points to", () => { marfa.transition(first?.id ?? "", "archived"); marfa.trash(second?.id ?? ""); - // The entry goes out and comes back, so the sweep archives the third. marfa.transition(entry("e1").id, "archived"); expect((await once()).code).toBe(0); marfa.transition(entry("e1").id, "active"); @@ -679,7 +663,6 @@ describe("the pictures an entry points to", () => { marfa.transition(entry("e1").id, "archived"); expect((await once()).output).toContain("1 archived with their entries"); - // A person restores the picture while its entry is still archived. marfa.transition(filesOf("e1")[0]?.id ?? "", "active"); const again = await once(); expect(again.code).toBe(0); @@ -722,14 +705,12 @@ describe("the pictures an entry points to", () => { pictures["/b.png"] = { body: png(2) }; asked = []; expect((await once()).code).toBe(0); - // The stopped run kept no mark of the entry's thumbnail, so it is asked - // for again before the picture. + // The stopped run kept no mark of the entry's thumbnail, so it is asked for again before the picture. expect(asked).toEqual(["/a.png", "/b.png"]); expect(rows()).toHaveLength(2); expect(filesOf("e1")).toHaveLength(2); expect(manifest("e1").saved).toHaveLength(2); - // A settled entry is left alone. const versions = rows().map((row) => row.version); expect((await once()).code).toBe(0); expect(rows().map((row) => row.version)).toEqual(versions); @@ -808,7 +789,6 @@ describe("the pictures an entry points to", () => { return img(at(path)); }).join(""), })); - // A run saves at most 100 pictures: three runs save all 220. for (let runs = 0; runs < 3; runs += 1) { expect((await once()).code).toBe(0); } @@ -855,12 +835,11 @@ describe("the pictures an entry points to", () => { expect(held).toHaveLength(1); const versions = held.map((row) => row.version); - // The server says to slow down when the connector reads its pictures, - // and a second entry comes into the feed. documents["/one.json"] = [ { id: "e1", title: "One", content_html: img(at("/a.png")) }, { id: "e2", title: "Two", content_html: img(at("/b.png")) }, ]; + // The server says to slow down when the connector reads its pictures. marfa.refuseWhere( "GET /items", (request) => request.query.get("type") === "rss.picture", @@ -869,8 +848,7 @@ describe("the pictures an entry points to", () => { ); asked = []; const refused = await once(); - // The feeds are not failed, the new entry is written, and no picture is - // fetched or changed; the new entry's thumbnail is the one ask. + // The feeds are not failed, the new entry is written, and no picture is fetched or changed; the new entry's thumbnail is the one ask. expect(refused.code).toBe(0); expect(refused.output).toContain( "the pictures could not be saved this run", @@ -920,7 +898,6 @@ describe("the pictures an entry points to", () => { it("fetches a picture from a private host only when the host is its own feed's", async () => { pictures["/a.png"] = { body: png(1) }; pictures["/b.png"] = { body: png(2) }; - // The first feed is at the listed host, and the second at its address. documents["/one.json"] = [ { id: "e1", title: "One", content_html: img(at("/a.png")) }, ]; @@ -936,8 +913,7 @@ describe("the pictures an entry points to", () => { expect(manifest("e2").not_kept).toEqual({ [at("/b.png")]: "private_address", }); - // The first feed's thumbnail and picture; the second feed's host is not - // one it may fetch from, so nothing of it is asked for. + // The first feed's thumbnail and picture; the second feed's host is not one it may fetch from, so nothing of it is asked for. expect(asked).toEqual(["/a.png", "/a.png"]); }); }); diff --git a/connectors/rss/test/rss.test.ts b/connectors/rss/test/rss.test.ts index 0d2ba7bf..0a290416 100644 --- a/connectors/rss/test/rss.test.ts +++ b/connectors/rss/test/rss.test.ts @@ -27,8 +27,6 @@ import { import { isPrivate } from "@withmarfa/connector/network"; import { getFeed, maxFeedBytes, TooLarge } from "../src/fetch.js"; -/** Few elements, each with thousands of attributes: under the element and - * entry counts, and over the attribute count. */ function heavyFeed(bytes: number): string { const attributes = Array.from( { length: 4000 }, @@ -1123,7 +1121,6 @@ describe("an entry's content and image", () => { }); describe("hostile bodies", () => { - /** An item whose content is built to cost the converter the most. */ const item = (id: string, content: string): string => `${id}${id}`; const good = "

A good body.

"; @@ -1508,7 +1505,6 @@ describe("feeds as they are found in the wild", () => { "https://imgs.example.org/comics/accelerator_energies.png", "https://imgs.example.org/comics/pixel_counter.png", ]); - // The picture's title text, else its alt text, and none where it has neither. expect(entries.map((entry) => property(entry, "description"))).toEqual([ `Rumor has it that they're finally auctioning off the airship bands, but everyone is worried about the "scary" captains.`, "Fans get extra excited.", @@ -1679,7 +1675,6 @@ describe("feeds as they are found in the wild", () => { "messy-2", "messy-3", ]); - // Entities it knows are decoded; those it does not are left as written. expect(property(entries[0], "title")).toBe( "Café & crème … AT&T ’s &unknown; &#xZZ;", ); @@ -1807,8 +1802,6 @@ describe("fetching a feed", () => { rss(``.repeat(maxFeedAttributes / 4 + 1)), ), ).toThrow(TooManyAttributes); - // A name with no value, a value with no quotes and values with no space - // between them are attributes all the same. const joined = (count: number): string => ` `a${String(at)}="1"`).join("")}/>`; expect(read(rss(joined(maxFeedAttributes + 1)))).toThrow(TooManyAttributes); @@ -1917,8 +1910,7 @@ describe("fetching a feed", () => { } }); - /** Runs a read in a fresh process, whose high-water marks start clean, - * and answers how it ended and how much it grew. */ + // A fresh process, so its high-water marks start clean. async function measured(document: string): Promise<{ outcome: string; rssMiB: number; @@ -1995,9 +1987,7 @@ interface Served { body: string | Buffer; authorization?: string; redirect?: string; - /** What a redirect answers with; 301 where not given. */ redirectStatus?: number; - /** Answers with this alone, whatever the request. */ status?: number; encoding?: string; contentType?: string; diff --git a/connectors/rss/test/thumbnail-turns.test.ts b/connectors/rss/test/thumbnail-turns.test.ts index 45331028..fa7b23cd 100644 --- a/connectors/rss/test/thumbnail-turns.test.ts +++ b/connectors/rss/test/thumbnail-turns.test.ts @@ -9,7 +9,6 @@ import { makeThumbnails, maxThumbnailsPerRun } from "../src/thumbnails.js"; type Make = NonNullable[1]["make"]>; -/** A thumbnail Marfa takes: a JPEG data URI of canonical base64. */ const uri = `data:image/jpeg;base64,${Buffer.from([0xff, 0xd8, 0xff, 0xe0]).toString("base64")}`; const good = "https://img.example/good.jpg"; @@ -41,7 +40,6 @@ describe("the turns of the thumbnail pass", () => { image: `https://img.example/${String(n)}.svg`, state: "active", }); - // New entries land at the end. rows.set("entry-good", { image: good, state: "active" }); const derived: string[] = []; const context = { @@ -77,7 +75,6 @@ describe("the turns of the thumbnail pass", () => { } expect(derived).toEqual(["entry-good"]); expect(rows.get("entry-good")?.thumbnail).toBe(uri); - // What the cursor adds to the state is one key. expect(state.cursor).toMatch(/^entry-/); }, 60_000, diff --git a/connectors/rss/test/thumbnails.test.ts b/connectors/rss/test/thumbnails.test.ts index 5611e3d2..48f8e857 100644 --- a/connectors/rss/test/thumbnails.test.ts +++ b/connectors/rss/test/thumbnails.test.ts @@ -22,7 +22,6 @@ import { maxThumbnailsPerRun } from "../src/thumbnails.js"; const run = promisify(execFile); const built = resolve(import.meta.dirname, "../dist/main.js"); -/** A picture the kit can make a thumbnail of, and one it cannot decode. */ const picture = (width: number): Buffer => Buffer.from(jpeg(scene(width, Math.round(width * 0.75)))); const notDecodable = Buffer.concat([ @@ -30,9 +29,6 @@ const notDecodable = Buffer.concat([ Buffer.alloc(60, 1), ]); -// ---- A local HTTPS server for the pictures, with a certificate made for -// the run. ---- - const directory = mkdtempSync(join(tmpdir(), "rss-thumbnails-")); execFileSync( "openssl", @@ -174,7 +170,6 @@ describe("the thumbnail of an entry", () => { }; const thumbnailOf = (entryId: string): unknown => entry(entryId).properties["thumbnail"]; - /** A condition a run raised: a warning in its output. */ const warnings = (output: string): string[] => output.split("\n").filter((line) => line.includes(" warn ")); @@ -321,7 +316,6 @@ describe("the thumbnail of an entry", () => { expect(asked).toEqual([]); expect(thumbnailOf("e1")).toBeUndefined(); - // A new address is tried. pictures["/better.jpg"] = { body: picture(900) }; documents["/one.json"] = [ { id: "e1", title: "One", image: at("/better.jpg") }, @@ -375,7 +369,6 @@ describe("the thumbnail of an entry", () => { expect(asked).toEqual([]); expect(thumbnailOf("e1")).toBeUndefined(); - // A new address is tried at once. pictures["/new.jpg"] = { body: picture(700) }; documents["/one.json"] = [ { id: "e1", title: "One", image: at("/new.jpg") }, diff --git a/connectors/todoist/src/definition.ts b/connectors/todoist/src/definition.ts index 78e18a5e..1627f911 100644 --- a/connectors/todoist/src/definition.ts +++ b/connectors/todoist/src/definition.ts @@ -43,12 +43,10 @@ export function connector() { { name: "task", direction: "both", - // Imported JSON widens every string, so its field types read as - // `string` here; the check on start holds the file to the server's. + // Imported JSON widens every string; the check on start holds the file to the server's. type: todoistTask as TypeDefinition, fields: taskFields, - // The labels are Marfa tags now; `labels` stays declared, as a - // published type never narrows, and is cleared on the next write. + // `labels` stays declared, as a published type never narrows, and is cleared on the next write. retired: ["labels"], tags: true, readOnly: ["url", "parent_id", "child_order", "recurrence"], @@ -120,10 +118,7 @@ export function connector() { answer = { ...full, items: [...byId.values()], - // The delta's token, older than the full sync's: a change that - // landed between the two requests comes back in the next delta - // rather than being skipped, and what comes back again is unchanged. - // A completion landing between the two comes back in the next delta. + // The delta's token is older than the full sync's: a change that landed between the two requests comes back in the next delta. sync_token: answer.sync_token, }; } @@ -210,7 +205,7 @@ export function connector() { ); state.set("account", account); if (named !== undefined) state.set("timezone", named); - // The user comes with a delta only when it changed. + // Todoist sends the user with a delta only when it changed. if (answer.user !== undefined) state.set("lang", langOf(answer.user)); // A run a change started, with the state lost, archives only what it was // handed: the next scheduled run syncs in full again. @@ -353,7 +348,7 @@ function unanswered( /** Well inside Todoist's 1000 requests in 15 minutes. */ const asksPerRun = 200; const writtenEvery = 50; -/** Well inside what the instance keeps as a connector's state. */ +// Well inside what the instance keeps as a connector's state. const heldAtMost = 2000; interface Unheard { @@ -380,7 +375,6 @@ function unansweredOf(value: unknown): Unheard[] { : []; } -/** The ids not asked about, and those Todoist did not answer. */ async function askAbout( ids: readonly string[], context: { diff --git a/connectors/todoist/src/outbound.ts b/connectors/todoist/src/outbound.ts index 9ee5e7e3..3a758010 100644 --- a/connectors/todoist/src/outbound.ts +++ b/connectors/todoist/src/outbound.ts @@ -73,8 +73,7 @@ export interface TaskArgs { description: string; priority: number; due: Due | null; - // Absent where the row holds none; null in a diff where the row ended it. - // Todoist takes it as the due's text, never as a field of its own. + // Absent where the row holds none; null in a diff where the row ended it. Todoist takes it as the due's text, never as a field of its own. recurrence_text?: string | null; } @@ -85,15 +84,14 @@ interface Due { timezone?: string; } -/** A due as sent: a recurrence sent alone is dated by Todoist. */ +// A recurrence sent alone is dated by Todoist. type SentDue = Omit & { date?: string }; export function argsOf(item: Item, timeZone: string): TaskArgs { const p = item.properties; return { content: typeof p["title"] === "string" ? p["title"] : "", - // An empty description clears Todoist's, as an absent one on the row - // is a description the row does not have. + // An empty description clears Todoist's. description: typeof p["description"] === "string" ? p["description"] : "", priority: priorityFor(p["priority"]), due: dueFor(p["due_at"], p["precision"], timeZone), @@ -141,8 +139,7 @@ export function differing( return out; } -// A date Todoist holds, as `dueFor` words one: Todoist answers a time with -// fractions of a second, which a date sent never carries. +// Todoist answers a time with fractions of a second, which a date sent never carries. function heldDue(due: TodoistItem["due"]): Due | null { if (typeof due?.date !== "string") return null; return { @@ -151,9 +148,7 @@ function heldDue(due: TodoistItem["due"]): Due | null { }; } -// Todoist reads a recurrence's text on the date sent with it as its next -// occurrence, and a date alone as a task due once (seen live in October -// 2026), so an ended recurrence leaves the task due once on its date. +// Todoist reads a recurrence's text on the date sent with it as its next occurrence, and a date alone as a task due once (observed October 2026). function recurring( due: SentDue | null, recurrence_text: string | null, @@ -171,8 +166,6 @@ function recurring( }; } -// What `item_add` and `item_update` take: the recurrence goes as the due's -// text. function sendable( { recurrence_text, ...args }: Partial, lang: string | undefined, @@ -195,11 +188,7 @@ function placeOf(value: unknown): string | undefined { return typeof value === "string" && value !== "" ? value : undefined; } -// The one place `item_move` takes: the section when the row changed it and -// names one, whose project the task takes; else a project, whose root the -// task goes to, from a changed project or from a cleared section in the -// project the task is in. A project the row does not change is the task's -// own, so a stale one on the row never moves it back. +// `item_move` takes the section when the row changed it, else a project, whose root the task goes to. A project the row does not change is the task's own, so a stale one never moves it back. export function destination( item: Item, task: TodoistItem, @@ -237,7 +226,6 @@ function userFor( return asked; } -/** Asked only for a recurrence the row sets, from the sync where it can be. */ type Lang = () => Promise; function langFor(context: WatchContext, todoist: Door): Lang { @@ -387,7 +375,7 @@ async function carried( const lang = langFor(context, todoist); let taskId = linkOf(item); - // A create's tags go with it, as its labels. + // A create carries its tags in its own command, as its labels. if (change.tags !== undefined && kind !== "created") { if (taskId !== undefined) await tagged(item, kind, change.tags, taskId, todoist); @@ -463,11 +451,6 @@ async function carried( ); } -/** - * Applies the tags added and removed in Marfa to the labels the task holds - * now, one at a time, so a label a person gave the task in Todoist since is - * kept. Nothing is sent where the task already holds the result. - */ async function tagged( item: Item, kind: Change["kind"], @@ -598,7 +581,6 @@ function shelved(change: Change, message: string): Error { : new Refused(message); } -// The project's name where Todoist still answers for it, else its id. async function archivedProject( projectId: string, todoist: Door, @@ -628,8 +610,7 @@ async function held( throw new Refused(unreached(taskId, task)); } if (task === "deleted") { - // An archive owes a deleted task nothing; the sync that brings the - // deletion archives the row of any other change. + // An archive owes a deleted task nothing; the sync that brings the deletion archives the row of any other change. if (kind === "archived") return undefined; throw new Refused(`Todoist deleted task ${taskId}`); } diff --git a/connectors/todoist/src/projects.ts b/connectors/todoist/src/projects.ts index 7e1b24f1..20b77856 100644 --- a/connectors/todoist/src/projects.ts +++ b/connectors/todoist/src/projects.ts @@ -1,7 +1,6 @@ import type { Log } from "@withmarfa/connector"; import { inUse, isGone, type SyncAnswer, type TodoistItem } from "./todoist.js"; -/** Whether a task's project is in use, where that is known. */ export function placedIn( kept: ReadonlySet | undefined, ): (item: TodoistItem) => boolean { @@ -12,23 +11,15 @@ export function placedIn( } export interface Followed { - /** The projects in use, or `undefined` where no whole list was ever read. */ inUse: Set | undefined; - /** Projects archived or deleted since the last run, or no longer listed. */ gone: Set; - /** Projects in use now that were not at the last run. */ back: string[]; - /** The first whole list: every row in a project it leaves out is gone. */ firstList: boolean; } const unlisted = "Todoist's list of projects named no Inbox, so it was not taken as whole, and no row was archived for its project"; -/** - * The projects a set of tasks may be placed in: those held, or, where a task - * names a project not held, the whole list read afresh. - */ export async function knowing( items: readonly TodoistItem[], kept: ReadonlySet | undefined, @@ -62,8 +53,7 @@ export async function followProjects( if (prior.has(project.id)) gone.add(project.id); } else now.add(project.id); } - // A task of a project the delta did not name and the run does not hold - // is in one the account joined or made without a record of it here. + // A task of a project the delta did not name and the run does not hold is in one the account joined or made without a record here. const strays = answer.items.some( (item) => item.is_deleted !== true && diff --git a/connectors/todoist/src/recurrence.ts b/connectors/todoist/src/recurrence.ts index 5771ee49..6d9a9bef 100644 --- a/connectors/todoist/src/recurrence.ts +++ b/connectors/todoist/src/recurrence.ts @@ -23,8 +23,7 @@ const dayNames: ReadonlyMap = new Map([ ["saturday", 6], ]); -/** Separates named weekdays in a due string whose whitespace is already one - * space wide, so no alternative repeats and each position costs a constant. */ +// Applied to whitespace already one space wide, so no alternative repeats and each position costs a constant. const dayBreak = / ?, ?| and | ?& ?/; interface Wall { @@ -65,9 +64,7 @@ function wallIn(at: number, timeZone: string): Wall | undefined { } } -/** Whether the zone keeps one offset from UTC across the year of the instant - * and the next, sampled on the first of every month, so a rule that advances - * in UTC keeps the wall time. */ +// Whether the zone keeps one offset from UTC, so a rule that advances in UTC keeps the wall time. function steady(at: number, timeZone: string): boolean { const year = new Date(at).getUTCFullYear(); const offsets = new Set(); @@ -81,7 +78,6 @@ function steady(at: number, timeZone: string): boolean { return offsets.size === 1; } -/** The minutes after midnight a trailing `at 2pm` or `at 14:00` names. */ function clock( hour: string, minute: string | undefined, @@ -109,20 +105,8 @@ function weekdays(list: string): number[] | undefined { return new Set(found).size === found.length ? found : undefined; } -/** - * A recurring due as the RFC 5545 lines of a task's `recurrence`, where they - * state the repeat exactly, and `undefined` where they cannot. - * - * A task's rule starts at its `due_at` and advances in UTC, so a repeat is - * stated only when the due's wall-clock time and day hold in UTC: the zone it - * is said in keeps one offset from UTC, and a rule naming a weekday or a day - * of the month falls on that day in UTC as it does there. Todoist words the - * repeat in the account's language, and only English is read, in the forms - * Todoist writes most: every day, N days, weekday, week, N weeks, named - * weekdays, month, N months, the Nth or last day of the month, year, N years, - * each with an optional `at` time. A repeat counted from completion (`every!`), - * one with a start or an end, and any other wording is not stated. - */ +// Stated only when the due's wall-clock time and day hold in UTC, since a task's rule starts at its `due_at` and advances in UTC. +// Todoist words the repeat in the account's language and only English is read. export function recurrenceRules( due: TodoistItem["due"], dueAt: string | undefined, @@ -161,7 +145,6 @@ export function recurrenceRules( words = words.slice(0, atIndex); } } - // The day a wall-clock day falls on in UTC: -1, 0 or 1 days earlier or later. const shift = Math.round( (Date.UTC(utc.year, utc.month - 1, utc.day) - Date.UTC(wall.year, wall.month - 1, wall.day)) / diff --git a/connectors/todoist/src/todoist.ts b/connectors/todoist/src/todoist.ts index 35376f0d..7f87cc89 100644 --- a/connectors/todoist/src/todoist.ts +++ b/connectors/todoist/src/todoist.ts @@ -2,11 +2,7 @@ import { recurrenceRules } from "./recurrence.js"; import { createHash } from "node:crypto"; import type { Entry } from "@withmarfa/connector"; -/** - * A task as the Sync API answers it. The API sends every item whole, a - * delta included, so a field an item leaves out is one the task does not - * have, and is cleared. - */ +// The Sync API sends every item whole, a delta included, so a field an item leaves out is one the task does not have, and is cleared. export interface TodoistItem { id: string; content: string; @@ -41,7 +37,7 @@ export interface TodoistProject { export interface SyncAnswer { sync_token: string; - /** Todoist may answer a delta with every active task, deletions left out. */ + // Todoist may answer a delta with every active task, deletions left out. full_sync?: boolean; items: TodoistItem[]; projects?: TodoistProject[]; @@ -62,11 +58,6 @@ const rateLimitWaits = 5; const serverErrorRetries = 3; const commandResends = 5; -/** - * Todoist did not answer in a way that holds: no answer, a server error - * past its retries, or a wait longer than a run holds. Sending again later - * may land. - */ export class Unanswered extends Error { override name = "Unanswered"; } @@ -196,7 +187,6 @@ export async function sync( return (await response.json()) as SyncAnswer; } -/** Every project the account holds, from a full sync of projects alone. */ export async function projects( base: string, token: string, @@ -221,10 +211,6 @@ export async function projects( return ((await response.json()) as SyncAnswer).projects; } -/** - * The project ids a full list names as in use, or `undefined` for a list - * that cannot be whole: every account has its Inbox. - */ export function inUse( list: readonly TodoistProject[] | undefined, ): Set | undefined { @@ -287,10 +273,7 @@ export async function user( return ((await response.json()) as SyncAnswer).user; } -/** - * Todoist takes a window of up to three months on its completed tasks; - * twelve weeks fits inside any three months. - */ +// Todoist takes a window of up to three months on its completed tasks; twelve weeks fits inside any three months. const completedWindowMs = 84 * 86_400_000; export async function completed( @@ -359,7 +342,7 @@ export function describeError(error: CommandError): string { return `${error.error ?? "an error without a message"}${code}`; } -// A resent batch is safe: Todoist runs a command uuid it has seen only once. +// A resent batch reuses its command uuids: do not give a resend fresh ones. export async function send( base: string, token: string, @@ -435,7 +418,6 @@ export async function getTask( return found.is_deleted === true ? "deleted" : found; } -// Laid out as a UUID, the form Todoist's documentation shows for command ids. export function uuidFor(...parts: readonly string[]): string { const digest = createHash("sha1").update(parts.join("\u0000")).digest("hex"); const variant = ((parseInt(digest[16] ?? "0", 16) & 0x3) | 0x8).toString(16); @@ -492,11 +474,6 @@ function wallTimeAt(at: number, timeZone: string): string { return `${read["year"] ?? ""}-${read["month"] ?? ""}-${read["day"] ?? ""}T${read["hour"] ?? ""}:${read["minute"] ?? ""}:${read["second"] ?? ""}`; } -/** - * An instant as the floating time Todoist writes, the wall time it shows in - * the zone, or `undefined` where the clocks going back show that wall time - * twice, so a floating time could not say which. - */ export function floatingTime( instant: string, timeZone: string, @@ -516,11 +493,7 @@ export function floatingTime( return wall; } -/** - * The account a token belongs to, from the Sync API's own `user`. Not an - * item's `user_id`, which names the task's owner, who in a shared project - * need not be this account. - */ +// From the Sync API's `user`, not an item's `user_id`, which names the task's owner, who in a shared project need not be this account. export function accountOf(user: SyncAnswer["user"]): string | undefined { const id = user?.id; if (typeof id !== "string") return undefined; @@ -568,21 +541,12 @@ const dueLangs: ReadonlyMap = new Map([ ["zh_TW", "tw"], ]); -/** - * The `lang` to send a due's text with: the language the account sets for - * date recognition, else its own, worded as a due words it. None where a due - * has no word for it, so Todoist reads the text by the account's settings. - */ export function langOf(user: SyncAnswer["user"]): string | undefined { const set = user?.features?.dateist_lang; const lang = typeof set === "string" && set !== "" ? set : user?.lang; return typeof lang === "string" ? dueLangs.get(lang) : undefined; } -/** - * A recurring due's own words. Todoist words a one-off's date too, and keeps - * text it could not read as a recurrence on a one-off. - */ export function recurrenceTextOf(due: TodoistItem["due"]): string | undefined { return due?.is_recurring === true && typeof due.string === "string" && @@ -745,13 +709,7 @@ export const taskFields = [ "recurrence_text", ] as const; -/** - * Names what a sync reads and the kit writes, so a run that reads or writes a - * new field or resource syncs in full once and fills the rows it already - * holds. The fields written are those declared less any the kit leaves out - * while the key may not add them to the type, so lifting that narrowing - * changes the shape. - */ +// A run that reads or writes a new field or resource syncs in full once and fills the rows it already holds. export function readShape(written: readonly string[]): string { return createHash("sha256") .update(JSON.stringify({ fields: written, resources: syncResources })) diff --git a/connectors/todoist/test/outbound.test.ts b/connectors/todoist/test/outbound.test.ts index 52109511..f67208ca 100644 --- a/connectors/todoist/test/outbound.test.ts +++ b/connectors/todoist/test/outbound.test.ts @@ -51,8 +51,7 @@ beforeEach(async () => { afterEach(async () => { const sent = todoist.commands(); for (const command of sent) expect(command.uuid).toMatch(uuidShape); - // Args are left out: a create replayed after a failed run carries the row as - // it is by then. + // Args are left out: a create replayed after a failed run carries the row as it is by then. const what = (c: (typeof sent)[number]): string => JSON.stringify([c.type, c.temp_id, c.args["id"]]); const byUuid = new Map(sent.map((c) => [c.uuid, what(c)])); @@ -296,16 +295,12 @@ describe("the mapping back", () => { project_id: "p-work", }); expect(move({}, "section_id")).toEqual({ project_id: "p-work" }); - // A project changed to none and a section cleared agree with a section - // cleared alone: the task goes to the root of the project it is in. expect(move({}, "project_id", "section_id")).toEqual({ project_id: "p-work", }); expect(move({ project_id: "p-work" }, "project_id", "section_id")).toEqual({ project_id: "p-work", }); - // Already where the row says, or the row names no project, or nothing - // about the placing changed: no command. expect( move( { project_id: "p-work", section_id: "s-later" }, @@ -1885,8 +1880,6 @@ describe("labels, project and section changed in Marfa", () => { expect(todoist.tasks.get("a")?.labels).toEqual(["Home", "Work"]); expect(todoist.commands("item_move")).toEqual([]); - // A label a person gave the task in Todoist since is kept, not replaced - // by the list Marfa holds. todoist.edit("a", { labels: ["Home", "Work", "Errand"] }); marfa.setTags(row.id, ["Work"]); await landed(); @@ -1894,11 +1887,8 @@ describe("labels, project and section changed in Marfa", () => { id: "a", labels: ["Work", "Errand"], }); - // Todoist keeps its labels in order. expect(todoist.tasks.get("a")?.labels).toEqual(["Errand", "Work"]); - // A label added again after it was removed is a command of its own, not - // the first one's answer. marfa.setTags(row.id, ["Work", "Errand", "Home"]); await landed(); expect(todoist.tasks.get("a")?.labels).toEqual(["Errand", "Home", "Work"]); @@ -1916,7 +1906,6 @@ describe("labels, project and section changed in Marfa", () => { }); expect(todoist.tasks.get("a")?.labels).toEqual([]); - // Todoist already dropped the label a person removed in Marfa. const other = await placed("b", { labels: ["Home"] }); todoist.edit("b", { labels: [] }); marfa.setTags(other.id, []); @@ -1985,8 +1974,6 @@ describe("labels, project and section changed in Marfa", () => { project_id: "p-work", section_id: "s-later", }); - // The row keeps naming the section it held, which is not in the new - // project, so the task goes to the project's root. marfa.edit(row.id, { project_id: "p-home" }); await landed(); expect(todoist.commands().map((c) => [c.type, c.args])).toEqual([ @@ -2167,7 +2154,6 @@ describe("labels, project and section changed in Marfa", () => { todoist.edit("a", { labels: ["Home", "Old", "Work"] }); marfa.setTags(row.id, ["Old", "Errand"]); await landed(); - // Marfa removed Home and added Errand; Todoist added Work. expect(todoist.commands("item_update").map((c) => c.args)).toEqual([ { id: "a", labels: ["Old", "Work", "Errand"] }, ]); @@ -2246,8 +2232,7 @@ describe("labels, project and section changed in Marfa", () => { project_id: "p-work", content: "Task a, filed", }); - // The edit is settled by now, so the change that remains is the move - // alone, tried once more; the refusal then stands. + // The edit is settled by now, so the change that remains is the move alone, tried once more; the refusal then stands. await landed(); await landed(); expect(todoist.commands("item_move")).toHaveLength(2); @@ -2636,8 +2621,6 @@ describe("a recurrence", () => { }); it("is kept on a row that does not hold it yet when another field changes", async () => { - // As a row read before the field existed: Todoist's task repeats, the row - // has never held it, and only its title changes. const row = await placed("r", { due: { ...daily, string: "Oct 5", is_recurring: false }, }); @@ -2787,7 +2770,6 @@ describe("a recurrence", () => { const row = await placed("r", { due: { ...daily, string: "Oct 5", is_recurring: false }, }); - // As a state kept before the connector held them. const stored = structuredClone(marfa.states.get("todoist") ?? {}); const kept = stored["state"] as Record; delete kept["lang"]; @@ -2832,8 +2814,6 @@ describe("a recurrence", () => { expect(summary()).toContain( `the change to ${row.id} was refused, so it waits until the row changes in Marfa: Todoist could not read the recurrence "zzqx blorp", so task r keeps repeating "every day"`, ); - // The row keeps the words the person gave, named by the condition, and the - // next reads send nothing more. await landed(); await landed(); expect(todoist.commands("item_update")).toHaveLength(2); @@ -3112,7 +3092,6 @@ describe("a row made in Marfa", () => { expect(todoist.tasks.get(madeId)?.labels).toEqual(["Home"]); await landed(); await landed(); - // Made with them, so no label change follows. expect(todoist.commands("item_update")).toEqual([]); expect(todoist.tasks.get(madeId)?.labels).toEqual(["Home"]); expect(marfa.tags.get(row.id)).toEqual(["Home"]); diff --git a/connectors/todoist/test/recurrence.test.ts b/connectors/todoist/test/recurrence.test.ts index 594aa1e9..ddbe0ad5 100644 --- a/connectors/todoist/test/recurrence.test.ts +++ b/connectors/todoist/test/recurrence.test.ts @@ -62,7 +62,6 @@ describe("a recurring due as RFC 5545 lines", () => { }); it("moves a weekday to the day it falls on in UTC", () => { - // 07:00 on a Monday in Tokyo is 22:00 on the Sunday before, in UTC. expect( rules("every monday at 7am", "2026-10-04T22:00:00.000Z", "Asia/Tokyo"), ).toEqual(["RRULE:FREQ=WEEKLY;BYDAY=SU"]); @@ -70,23 +69,17 @@ describe("a recurring due as RFC 5545 lines", () => { it("states nothing it cannot state exactly", () => { const at = "2026-10-05T14:00:00.000Z"; - // Counted from completion, not from the calendar. expect(rules("every! day", at)).toBeUndefined(); - // A start or an end. expect(rules("every day starting oct 7", at)).toBeUndefined(); expect(rules("every day until dec 1", at)).toBeUndefined(); - // A clock time the date does not carry. expect(rules("every day at 9am", at)).toBeUndefined(); - // Words it does not read. expect(rules("every flibbertigibbet", at)).toBeUndefined(); expect(rules("jeden Tag", at, "UTC", { lang: "de" })).toBeUndefined(); - // A day of the month that not every month has. expect(rules("every 31st", "2026-10-31T14:00:00.000Z")).toBeUndefined(); // A zone whose offset changes in the year: the wall time would drift in UTC. expect( rules("every day at 3pm", "2026-10-05T14:00:00.000Z", "Europe/London"), ).toBeUndefined(); - // Not a repeat. expect( rules("every day", at, "UTC", { is_recurring: false }), ).toBeUndefined(); diff --git a/connectors/todoist/test/todoist.test.ts b/connectors/todoist/test/todoist.test.ts index 8846418c..cf571412 100644 --- a/connectors/todoist/test/todoist.test.ts +++ b/connectors/todoist/test/todoist.test.ts @@ -76,7 +76,6 @@ function task(id: string, overrides: Partial = {}): TodoistItem { }; } -/** What a run writes of a task: its fields and the tags the mapping carries. */ const written = [...taskFields, "@tags"]; const inbox: TodoistProject = { id: "p1", name: "Inbox", inbox_project: true }; @@ -162,8 +161,7 @@ beforeEach(async () => { res.writeHead(body).end(); return; } - // A full sync lists the Inbox, where every task here is, unless an - // answer names its own projects; a delta names none that changed. + // A full sync lists the Inbox, where every task here is, unless an answer names its own projects; a delta names none that changed. const whole = syncToken === "*" || body.full_sync === true; res.writeHead(200, { "Content-Type": "application/json" }); res.end( @@ -372,7 +370,6 @@ describe("the mapping", () => { const { properties } = entryOf("1", "UTC", odd); expect(properties["title"]).toBe("Task a"); expect(properties).not.toHaveProperty("labels"); - // A task Todoist sends no list of labels for leaves the row's tags alone. expect(entryOf("1", "UTC", odd)).not.toHaveProperty("tags"); expect(properties["due_at"]).toBeUndefined(); }); @@ -469,8 +466,6 @@ describe("the mapping", () => { is_recurring: true, }), ).toBe("jeden Tag"); - // Todoist words a one-off's date too, and keeps text it could not read - // as a recurrence on a one-off (seen live in October 2026). expect(recurrence(wholeDaySent)).toBeUndefined(); expect( recurrence({ @@ -541,7 +536,6 @@ describe("the mapping", () => { langOf({ lang, features: { dateist_lang } }); expect(set("fr")).toBe("fr"); expect(set("zh_TW", "de")).toBe("tw"); - // No words for it: not the account's language, which it overrides. expect(set("tr", "de")).toBeUndefined(); expect(set(null, "de")).toBe("de"); expect(set("", "de")).toBe("de"); @@ -907,8 +901,6 @@ describe("the connector, run as a process", () => { }); it("syncs in full once when it reads tasks in a new shape, so rows held from before gain the new fields", async () => { - // Each full sync words the recurrence anew, which no delta brings: only a - // full sync puts it on the row. const worded = [undefined, "every day at 2pm", "every weekday at 2pm"]; let fulls = 0; let deltas = 0; @@ -951,8 +943,6 @@ describe("the connector, run as a process", () => { ).toBeUndefined(); const shape = readShape(written); expect(state()["read_shape"]).toBe(shape); - // As a connector that read fewer fields left it: the state names no - // shape, or another one. for (const held of [undefined, "an older shape"]) { const stored = structuredClone(marfa.states.get("todoist") ?? {}); const kept = stored["state"] as Record; @@ -978,8 +968,6 @@ describe("the connector, run as a process", () => { expect(marfa.row("2671355:a").properties["recurrence_text"]).toBe( "every weekday at 2pm", ); - // The delta's deletion and completion are kept beside the full sync, as - // for a moved zone. expect(marfa.row("2671355:b").state).toBe("archived"); expect(marfa.row("2671355:c").properties).toMatchObject({ status: "completed", @@ -989,10 +977,6 @@ describe("the connector, run as a process", () => { }); it("syncs in full once when a narrowing lifts, so rows held without recurrence gain it", async () => { - // The kit runs without a field the key may not add to the type, and - // writes it once the type has it: the fields the connector declares are - // the same throughout, but what it writes is not, and a delta brings a - // recurring task only when it changes in Todoist. marfa.types.set("todoist.task", { ...served, fields: Object.fromEntries( @@ -1023,7 +1007,6 @@ describe("the connector, run as a process", () => { ).toBeUndefined(); const narrowed = state()["read_shape"]; - // Still narrowed: nothing about what is written has changed. expect((await once()).code).toBe(0); expect(state()["read_shape"]).toBe(narrowed); expect(received.map((request) => request.syncToken)).toEqual([ @@ -1045,7 +1028,6 @@ describe("the connector, run as a process", () => { expect(state()["read_shape"]).not.toBe(narrowed); expect(state()["read_shape"]).toBe(readShape(written)); - // One full sync only. expect((await once()).code).toBe(0); expect(received.map((request) => request.syncToken).slice(4)).toEqual([ "t-delta-2", @@ -1578,7 +1560,6 @@ describe("a project that goes", () => { expect((await once()).code).toBe(0); expect(marfa.row("2671355:a").state).toBe("active"); expect(marfa.runs.at(-1)?.summary).toContain("is archived"); - // A rename of an archived project sends its record again. delta([{ ...work, name: "Work, renamed", is_archived: true }]); expect((await once()).code).toBe(0); expect(marfa.row("2671355:a").state).toBe("active");