From 90c680e150d7448a476103f386368cfdcb41ceee Mon Sep 17 00:00:00 2001 From: kzoeps Date: Tue, 10 Nov 2026 13:06:50 +0600 Subject: [PATCH 1/2] sdk/social: add follows, likes and reposts --- .agents/skills/hypercerts-org-sdk/SKILL.md | 15 +- .../hypercerts-org-sdk/references/social.md | 90 ++++++ .changeset/social-follows-likes-reposts.md | 7 + packages/sdk/package.json | 4 + .../sdk/src/internal/submit-writes.test.ts | 35 +++ packages/sdk/src/internal/submit-writes.ts | 60 +++- packages/sdk/src/social/action.ts | 169 ++++++++++ packages/sdk/src/social/create.test.ts | 203 ++++++++++++ packages/sdk/src/social/feed.ts | 221 +++++++++++++ packages/sdk/src/social/graph.ts | 252 +++++++++++++++ packages/sdk/src/social/index.ts | 21 ++ packages/sdk/src/social/list-collection.ts | 113 +++++++ packages/sdk/src/social/run-action.ts | 90 ++++++ packages/sdk/src/social/undo.test.ts | 295 ++++++++++++++++++ .../sdk/src/test-utils/fake-collection.ts | 107 +++++++ packages/sdk/src/test-utils/fake-repo.ts | 10 + 16 files changed, 1685 insertions(+), 7 deletions(-) create mode 100644 .agents/skills/hypercerts-org-sdk/references/social.md create mode 100644 .changeset/social-follows-likes-reposts.md create mode 100644 packages/sdk/src/social/action.ts create mode 100644 packages/sdk/src/social/create.test.ts create mode 100644 packages/sdk/src/social/feed.ts create mode 100644 packages/sdk/src/social/graph.ts create mode 100644 packages/sdk/src/social/index.ts create mode 100644 packages/sdk/src/social/list-collection.ts create mode 100644 packages/sdk/src/social/run-action.ts create mode 100644 packages/sdk/src/social/undo.test.ts create mode 100644 packages/sdk/src/test-utils/fake-collection.ts diff --git a/.agents/skills/hypercerts-org-sdk/SKILL.md b/.agents/skills/hypercerts-org-sdk/SKILL.md index a0624f9..f2572d5 100644 --- a/.agents/skills/hypercerts-org-sdk/SKILL.md +++ b/.agents/skills/hypercerts-org-sdk/SKILL.md @@ -3,7 +3,7 @@ name: hypercerts-org-sdk description: "Write Hypercerts and Certified records (org.hypercerts.*, app.certified.*) to a PDS from an app with @hypercerts-org/sdk: setting up the SDK context from an authenticated @atproto/lex Client, choosing the right operation and subpath, uploading blobs, and handling write errors without duplicates. Use when app code imports @hypercerts-org/sdk, or the user wants to create, link or write hypercert-related records from an app. Not for changing the SDK's own source." metadata: author: hypercerts-org - version: "4" + version: "5" --- # @hypercerts-org/sdk @@ -51,6 +51,7 @@ Make a new context when the signed-in account changes. Records are always writte | `@hypercerts-org/sdk/tag` | `createVocabularyTag`, `createWorkScopeTag`, `RecordAlreadyExistsError`, the same `Write*` errors, input/result types | | `@hypercerts-org/sdk/feature` | `createFeature`, `RecordAlreadyExistsError`, the same `Write*` errors, `FeatureInput`, `CreateFeatureResult`, `LeafletDocument` | | `@hypercerts-org/sdk/organization` | `createOrganization`, `OrganizationAlreadyExistsError`, `RecordAlreadyExistsError`, the same `Write*` errors, `OrganizationInput`, `CreateOrganizationInput`, `CreateOrganizationResult`, `LeafletDocument` | +| `@hypercerts-org/sdk/social` | `followAccount`, `followEntity`, `like`, `repost`, `unfollowAccount`, `unfollowEntity`, `unlike`, `unrepost`, the `Write*` errors, `UndoResult` and input types | | `@hypercerts-org/sdk/blob` | `uploadBlob` | | `@hypercerts-org/sdk/collection` | `createCollection`, `createActivityInCollection`, `RecordAlreadyExistsError`, `WriteError`, `WriteRejectedError`, `WriteOutcomeUnknownError`, `WriteResultMismatchError`, input/result types | @@ -69,12 +70,14 @@ Operations are grouped by domain, each under its own subpath. Read the domain's | Feature (`org.hypercerts.entity.feature`, with its tags and locations) | `@hypercerts-org/sdk/feature` | [references/feature.md](references/feature.md) | | Collection (create a Collection with items; add a new Activity to an existing Collection) | `@hypercerts-org/sdk/collection` | [references/collection.md](references/collection.md) | | Organization (`app.certified.actor.organization`, with its profile and locations) | `@hypercerts-org/sdk/organization` | [references/organization.md](references/organization.md) | +| Social (follow accounts and records, like, repost, and undo them) | `@hypercerts-org/sdk/social` | [references/social.md](references/social.md) | -Three things to know before opening a reference: +Things to know before opening a reference: - `createProfile` needs an OAuth scope with both `create` and `update` on `app.certified.actor.profile`. With only `create` it fails with `WriteRejectedError` (403). - `location: { uri }` inside a location is a link to external data; a whole location given as `{ uri }` in `createActivity` reuses an existing record. - `createOrganization` takes the name, avatar, banner and website in `profileIfMissing`, not in `organization`, and an existing location as `{ uri }`, never a bare string. +- Social functions take the **target** of the action: `{ targetDid }` for an account, `{ targetUri }` (a full record URI) for a record. Undo functions return `UndoResult` (`deleted`, `not-found` or `ambiguous`), not `void`. ## 5. Images and files @@ -107,13 +110,13 @@ Uploads happen before the write and are not rolled back, so a call that throws c Order of work: validate input → read `{ uri }` records → upload blobs → validate against lexicons → one write. The SDK never retries. -The three write errors are exported from `@hypercerts-org/sdk/activity`, `/actor`, `/location`, `/tag`, `/feature`, `/collection` and `/organization` and extend `WriteError`. Every `WriteError` has `attempted`: the URI and CID of every record in the request, in request order: for `createActivity` the Activity is last; for `createActivityInCollection` the Collection is last and the Activity is just before it; for `createCollection` the Collection is last, after the records it points at; for `createOrganization` the organization is last. `instanceof WriteError` catches all three. +The three write errors are exported from `@hypercerts-org/sdk/activity`, `/actor`, `/location`, `/tag`, `/feature`, `/collection`, `/organization` and `/social` and extend `WriteError`. Every `WriteError` has `attempted`: the URI and CID of every record in the request, in request order: for `createActivity` the Activity is last; for `createActivityInCollection` the Collection is last and the Activity is just before it; for `createCollection` the Collection is last, after the records it points at; for `createOrganization` the organization is last. `instanceof WriteError` catches all three. | Error | Meaning | What to do | | -------------------------- | ---------------------------------------------------------------------------------------------- | --------------------------------------------- | | `TypeError` | Bad input. The message names the field (e.g. `contributors[1].weight`). Nothing written. | Fix the input. | | `Error` | Not authenticated, a `{ uri }` record could not be read, or an upload failed. Nothing written. | Fix auth or the URI, then retry. | -| `WriteRejectedError` | PDS answered 4xx. Nothing created or changed. `status`, `code`. | Safe to fix and retry. `InvalidSwap`: see [Concurrent changes](#concurrent-changes-invalidswap). | +| `WriteRejectedError` | PDS answered 4xx. Nothing created or changed. `status`, `code`. | Safe to fix and retry. `InvalidSwap`: see [Concurrent changes](#concurrent-changes-invalidswap); undo functions also return it when the record changed after it was read, and calling again is safe. | | `RecordAlreadyExistsError` | A key you chose is taken (a `WriteRejectedError`). `uri` names the record. Nothing written. | Use it as `{ uri }`, or choose another key. | | `WriteOutcomeUnknownError` | Network error, timeout or 5xx. The records may exist. `attempted` lists every URI. | Check before retrying. | | `WriteResultMismatchError` | Created, but the PDS reported other URIs/CIDs (`reported` vs `attempted`). | Do not retry. Log it and inspect the records. | @@ -179,7 +182,7 @@ try { - `createSDKContext({ client: session })` or passing an `@atproto/api` `Agent` throws. Wrap it: `new Client(session)`. - Passing an `uploadBlob` result as `image` throws. Pass the `Blob`/`File`. -- Retrying blindly after `WriteOutcomeUnknownError` duplicates every record under new keys. The exception is a call whose records all have a fixed key and are only created if absent: `createProfile` and `createVocabularyTag`. `createOrganization` is also safe to repeat: the organization exists at most once, so a second call creates it or throws `OrganizationAlreadyExistsError`. `createFeature`, `createCollection` and `createWorkScopeTag` are not safe to repeat. +- Retrying blindly after `WriteOutcomeUnknownError` duplicates every record under new keys. The exception is a call whose records all have a fixed key and are only created if absent: `createProfile` and `createVocabularyTag`. `createOrganization` is also safe to repeat: the organization exists at most once, so a second call creates it or throws `OrganizationAlreadyExistsError`. Undo functions are safe to repeat too. `createFeature`, `createCollection`, `createWorkScopeTag`, `followAccount`, `followEntity`, `like` and `repost` are not safe to repeat. - An item of `createCollection` is `{ activity }`, `{ feature }`, `{ collection }` or `{ uri }`, never a bare Activity input; `{ uri }` must be an Activity, Feature or Collection. - A vocabulary tag's key is `.` exactly as you pass it. A dot in either part throws a `TypeError`; the SDK does not normalise the parts. - A work-scope tag URI is not a vocabulary tag URI: each field accepts one collection, and a `{ uri }` of another throws a `TypeError`. @@ -188,6 +191,6 @@ try { ## Verify -1. Imports come only from `@hypercerts-org/sdk`, `.../activity`, `.../actor`, `.../collection`, `.../feature`, `.../location`, `.../organization`, `.../tag` or `.../blob`. +1. Imports come only from `@hypercerts-org/sdk`, `.../activity`, `.../actor`, `.../collection`, `.../feature`, `.../location`, `.../organization`, `.../social`, `.../tag` or `.../blob`. 2. `tsc --noEmit` passes. The input types catch wrong field names and shapes. 3. `com.atproto.repo.getRecord` on each returned `uri` returns the record, and any references it holds match the URIs and CIDs the SDK returned. diff --git a/.agents/skills/hypercerts-org-sdk/references/social.md b/.agents/skills/hypercerts-org-sdk/references/social.md new file mode 100644 index 0000000..71004d2 --- /dev/null +++ b/.agents/skills/hypercerts-org-sdk/references/social.md @@ -0,0 +1,90 @@ +# Social domain (`@hypercerts-org/sdk/social`) + +Read [../SKILL.md](../SKILL.md) first for setup and error handling. Every example assumes `context` from `createSDKContext`. + +The subpath covers `app.certified.graph.*` (follows) and `app.certified.feed.*` (likes, reposts). Each action has a create function and an undo function; all of them act on the signed-in account's own repo. + +| Create | Undo | Record | Target | Stored `subject` | +| ------------------------------------- | --------------------------------------- | ----------------------------------- | --------------------------- | --------------------------------------------------- | +| `followAccount(context, { targetDid })` | `unfollowAccount(context, { targetDid })` | `app.certified.graph.follow` | an account's **DID** | the DID | +| `followEntity(context, { targetUri })` | `unfollowEntity(context, { targetUri })` | `app.certified.graph.entityFollow` | a **record URI** | the URI only, no CID: survives edits of the record | +| `like(context, { targetUri })` | `unlike(context, { targetUri })` | `app.certified.feed.like` | a **record URI** | URI and the CID the SDK read: pins that version | +| `repost(context, { targetUri })` | `unrepost(context, { targetUri })` | `app.certified.feed.repost` | a **record URI** | URI and the CID the SDK read: pins that version | + +Create functions return `{ uri, cid }` of the **new social record**, not of the target. Callers never build a strong reference: pass the URI and the SDK reads the CID. + +## Targets + +- `targetDid` is an account **DID** (`did:plc:...`, `did:web:...`), typed `DidString`. A handle, a record URI or an object fails to compile in TypeScript, and throws `TypeError` at runtime for JavaScript callers or after a cast. Resolve a handle to a DID yourself first. +- A DID held as a plain `string` (a form field, a JSON response) does not compile either. Narrow it with `isDidString(did)` from `@atproto/lex` (`if (!isDidString(did)) throw ...`); do not cast. +- `targetUri` is a **full record URI**: `at:////`, with a DID as the authority. A bare DID, a handle authority (`at://alice.bsky.social/...`) or a partial URI (no record key) throws `TypeError`. The record may be of any Lexicon. +- To follow an account use `followAccount`, not `followEntity`: `followEntity({ targetUri: "did:plc:..." })` throws. + +```ts +import { followAccount, followEntity, like, repost } from "@hypercerts-org/sdk/social"; + +const activity = "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e8"; + +await followAccount(context, { targetDid: "did:plc:abc123" }); // looks nothing up +await followEntity(context, { targetUri: activity }); // does not read the record, stores no CID +const liked = await like(context, { targetUri: activity }); // reads the record, pins its current CID +await repost(context, { targetUri: activity }); // same +console.log(liked.uri); // at:///app.certified.feed.like/ +``` + +A like is social feedback only. It is not an evaluation, an acknowledgement or proof of endorsement; do not present it as one. + +## Options + +Create functions also take `createdAt` (ISO 8601, default: now) and `via`: + +```ts +await like(context, { + targetUri: activity, + via: "at://did:plc:def456/app.certified.feed.repost/3k2a4b5c6d7e9", // how you came across it +}); +``` + +`via` is the URI of the record through which the target was found (a repost, a starter pack, ...). The SDK reads it and stores a strong reference; it may be a record of any Lexicon. A `via` that cannot be read fails the call and nothing is written. + +## Nothing is deduplicated + +Each create call writes a new record under a new TID. Calling `like` twice for the same record creates two likes; the SDK does not look for an existing one and does not toggle. Check your own state first if the app must not create two. + +## Undo and `UndoResult` + +Undo functions return `UndoResult`, not `void`: + +```ts +import { unlike } from "@hypercerts-org/sdk/social"; + +const result = await unlike(context, { targetUri: activity }); +switch (result.status) { + case "deleted": // exactly one matching like existed and is gone + break; + case "not-found": // no matching like; nothing was deleted + break; + case "ambiguous": // result.matchCount likes match; NOTHING was deleted + // The account liked it more than once. Delete the extras yourself (com.atproto.repo.deleteRecord), then call again. + break; +} +``` + +- The SDK lists **all** records of that collection in your own repo (every page, from your PDS, no indexer) and matches by subject: DID for follows, record URI for entity follows, likes and reposts. The CID a like or repost pinned is ignored, so a like of an older version of an edited record is found. +- The target is **not** read, so a deleted or edited target does not stop you removing the like or follow. +- Exactly one match is deleted with a CID guard. If that record changed in between, the PDS refuses: `WriteRejectedError` with `code === "InvalidSwap"`, nothing deleted. The SDK never retries or deletes without the guard; call again to scan afresh. +- A page that fails to load or looks wrong throws `Error`. It is never treated as "not found". +- The scan is a snapshot. It cannot stop another writer creating a matching record meanwhile, so `deleted` does not promise that none remains. +- `WriteOutcomeUnknownError` from an undo: `attempted` is the record the SDK tried to delete. Calling the undo again is safe: it either deletes the record or returns `not-found`. +- The session needs permission to **delete** the collection (`app.certified.graph.follow`, `...graph.entityFollow`, `...feed.like`, `...feed.repost`) to undo, and to create it to create. + +## Input fields + +| Field | Used by | Type | Notes | +| ------------ | -------------------------------------------- | -------- | --------------------------------------------------------------------------------------- | +| `targetDid` | `followAccount`, `unfollowAccount` | `DidString` (from `@atproto/lex`) | Required. A DID, not a handle. | +| `targetUri` | `followEntity`, `like`, `repost` and their undo functions | `string` | Required. Full record URI with a DID authority. | +| `createdAt` | create functions | `string` | Optional. ISO 8601 date-time. Default: time of the call. | +| `via` | create functions | `string` | Optional. Record URI, read and pinned by the SDK. Any Lexicon. | + +Unknown fields throw `TypeError`. Undo functions accept only the target. diff --git a/.changeset/social-follows-likes-reposts.md b/.changeset/social-follows-likes-reposts.md new file mode 100644 index 0000000..0a5e874 --- /dev/null +++ b/.changeset/social-follows-likes-reposts.md @@ -0,0 +1,7 @@ +--- +"@hypercerts-org/sdk": minor +--- + +- Add `followAccount`, `followEntity`, `like` and `repost` at `@hypercerts-org/sdk/social`, with an optional `via` record URI that the SDK pins. +- Add `unfollowAccount`, `unfollowEntity`, `unlike` and `unrepost`. They scan the account's own repository and return `UndoResult` (`deleted`, `not-found` or `ambiguous`); with several matching records nothing is deleted. +- Deletions are guarded by the record's CID; a concurrent change throws `WriteRejectedError` with `code` `"InvalidSwap"`. diff --git a/packages/sdk/package.json b/packages/sdk/package.json index e5c1ae2..c50bfd0 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -43,6 +43,10 @@ "types": "./dist/organization/index.d.ts", "default": "./dist/organization/index.js" }, + "./social": { + "types": "./dist/social/index.d.ts", + "default": "./dist/social/index.js" + }, "./tag": { "types": "./dist/tag/index.d.ts", "default": "./dist/tag/index.js" diff --git a/packages/sdk/src/internal/submit-writes.test.ts b/packages/sdk/src/internal/submit-writes.test.ts index 3fcb7c1..3602a9a 100644 --- a/packages/sdk/src/internal/submit-writes.test.ts +++ b/packages/sdk/src/internal/submit-writes.test.ts @@ -6,6 +6,7 @@ import { fakeRepo, HEAD, methods } from "../test-utils/fake-repo.js"; import { prepareRecord, prepareUpdate } from "./prepare-record.js"; import { submitCreateOnly, + submitDelete, submitWrites, WriteOutcomeUnknownError, WriteRejectedError, @@ -183,3 +184,37 @@ describe("submitCreateOnly", () => { expect(error.reported).toEqual([{ uri: record.ref.uri, cid: CID }]); }); }); + +describe("submitDelete", () => { + const ref = { uri: `at://${DID}/app.certified.feed.like/3k2a4b5c6d7e8` as const, cid: CID }; + + it("treats an HTTP 4xx other than a conflict as a definite rejection, naming what was not deleted", async () => { + const { context } = fakeRepo({ + deleteRecord: () => json(403, { error: "Forbidden", message: "no delete permission" }), + }); + + const error = await submitDelete(context, DID, ref, "op").catch((e) => e); + + expect(error).toBeInstanceOf(WriteRejectedError); + expect(error).toMatchObject({ status: 403, code: "Forbidden", attempted: [ref] }); + expect(error.message).toContain(`${ref.uri} was not deleted`); + }); + + it.each([ + ["HTTP 408", () => json(408, { error: "RequestTimeout", message: "slow" })], + [ + "a network failure", + () => { + throw new TypeError("fetch failed"); + }, + ], + ])("treats %s as an unknown outcome", async (_, deleteRecord) => { + const { context } = fakeRepo({ deleteRecord }); + + const error = await submitDelete(context, DID, ref, "op").catch((e) => e); + + expect(error).toBeInstanceOf(WriteOutcomeUnknownError); + expect(error.attempted).toEqual([ref]); + expect(error.message).toContain(`whether ${ref.uri} was deleted`); + }); +}); diff --git a/packages/sdk/src/internal/submit-writes.ts b/packages/sdk/src/internal/submit-writes.ts index 153fead..d3e27aa 100644 --- a/packages/sdk/src/internal/submit-writes.ts +++ b/packages/sdk/src/internal/submit-writes.ts @@ -2,7 +2,7 @@ import type { CidString, DidString, NsidString, TypedLexMap } from "@atproto/lex import type { SDKContext } from "../context.js"; import { describeError } from "./describe.js"; import type { PreparedRecord } from "./prepare-record.js"; -import type { StrongRef } from "./resolve-record-ref.js"; +import { parseRecordUri, type StrongRef } from "./resolve-record-ref.js"; /** * Base class of the errors thrown when the single request that writes records did not succeed. @@ -312,6 +312,64 @@ function alreadyExists( ); } +/** + * Deletes one record from `did`'s repo, only if it still has the CID in `ref`, with + * `com.atproto.repo.deleteRecord` and `swapRecord: ref.cid`. + * + * Internal. Boundaries: + * - Never retries, and never deletes without the CID guard: if the record changed since the caller + * read it, the PDS refuses and nothing is deleted. + * - Classifies a failure as the other write functions do: definite only when the PDS answered with + * an HTTP 4xx other than 408 (and then nothing was deleted), outcome-unknown otherwise. + * - Has no reported result to compare: `deleteRecord` answers with a commit, not with references. + * A PDS that treats an already-missing record as a no-op answers success, which is + * indistinguishable from this call having deleted it. + * + * Throws WriteRejectedError (with `code` `InvalidSwap` when the record no longer has the CID in + * `ref`, so it was not deleted) or WriteOutcomeUnknownError. In both, `attempted` is `[ref]`: for a + * delete it holds the record the request tried to delete, with the CID it had. Throws TypeError + * when `ref.uri` is not a record URI. + */ +export async function submitDelete( + context: SDKContext, + did: DidString, + ref: StrongRef, + operation: string, +): Promise { + const { collection, rkey } = parseRecordUri(ref.uri, operation); + try { + await context.client.deleteRecord(collection, rkey, { repo: did, swapRecord: ref.cid }); + } catch (error) { + throw classifyDeleteFailure(operation, error, ref); + } +} + +function classifyDeleteFailure(operation: string, error: unknown, ref: StrongRef) { + const status = property(error, "status"); + const reason = describeError(error); + // As in `classifyFailure`: definite only for an HTTP 4xx other than 408. + const rejected = typeof status === "number" && status >= 400 && status < 500 && status !== 408; + if (!rejected) { + return new WriteOutcomeUnknownError( + `${operation}: no usable answer from the PDS (${reason}), so it is not known whether ${ref.uri} was deleted. ` + + `The SDK does not retry. Check whether it still exists (for example with com.atproto.repo.getRecord) before trying again.`, + [ref], + { cause: error }, + ); + } + const code = property(error, "error"); + const message = + code === "InvalidSwap" + ? `${operation}: ${ref.uri} no longer has the version (CID ${ref.cid}) that was read, so the PDS refused to delete it (HTTP ${status}: ${reason}). It was not deleted: something changed or replaced it in between. The SDK neither retries nor deletes without that check. Call ${operation} again to read the repository afresh.` + : `${operation}: the PDS rejected the request (HTTP ${status}: ${reason}), so ${ref.uri} was not deleted. Fix the cause (for example the session's permissions or a rate limit) and call again.`; + return new WriteRejectedError( + message, + [ref], + { status, code: typeof code === "string" ? code : undefined }, + { cause: error }, + ); +} + // Sends one write request and checks what it reports. `send` resolves to the PDS's results, one // per record in request order, or `undefined` if the PDS reported none. `retrySafe` says whether // calling again after an unknown outcome cannot duplicate records; it only changes the advice in diff --git a/packages/sdk/src/social/action.ts b/packages/sdk/src/social/action.ts new file mode 100644 index 0000000..2dd4ee3 --- /dev/null +++ b/packages/sdk/src/social/action.ts @@ -0,0 +1,169 @@ +import { type DidString, isDidString, l } from "@atproto/lex"; +import type { SDKContext } from "../context.js"; +import { strictObject } from "../internal/input.js"; +import { parseRecordUri, resolveRecordRef } from "../internal/resolve-record-ref.js"; + +/** Options every operation that creates a social record accepts besides its target. */ +export interface ActionOptions { + /** An ISO 8601 date-time. Defaults to the time of the call. */ + createdAt?: string | undefined; + /** + * The record through which the target was found, for example a starter pack or a repost, as a + * record URI: `at:////`. The SDK reads the record to pin its current + * version and stores it as a strong reference, so callers never build one. It may be a record of + * any Lexicon and of any account if it is public. A handle in place of the DID is rejected, and + * so is a record that cannot be read: nothing is written then. + */ + via?: string | undefined; +} + +/** + * What an undo operation ({@link unfollowAccount}, {@link unfollowEntity}, {@link unlike} and + * {@link unrepost}) did. + * + * @remarks + * - `deleted`: the account's repository held exactly one matching record, and it was deleted. + * - `not-found`: no matching record was found; nothing was deleted. This does not say whether the + * action never existed or was removed earlier. + * - `ambiguous`: `matchCount` matching records were found (always more than one, because the + * account created the same action repeatedly); nothing was deleted. The SDK cannot tell which + * one is meant, and deleting all of them would be a decision for the caller. Delete the extra + * records yourself (for example with `com.atproto.repo.deleteRecord`) and call again. + * + * The outcome reflects the records the scan saw. A matching record created by another writer after + * the scan is not seen, so `deleted` does not promise that no matching record remains, and + * `not-found` does not promise that none exists a moment later. + */ +export type UndoResult = + | { status: "deleted" } + | { status: "not-found" } + | { status: "ambiguous"; matchCount: number }; + +/** The input of {@link followAccount}. */ +export interface FollowAccountInput extends ActionOptions { + /** + * The account to follow, as a DID (`did:plc:...` or `did:web:...`). A handle, a record URI or an + * object is rejected. + */ + targetDid: DidString; +} + +/** The input of {@link unfollowAccount}. */ +export interface UnfollowAccountInput { + /** The account to stop following, as a DID. A handle, a record URI or an object is rejected. */ + targetDid: DidString; +} + +/** The input of {@link followEntity}, {@link like} and {@link repost}. */ +export interface RecordActionInput extends ActionOptions { + /** + * The record the action is about, as a full record URI: `at:////`, with a + * DID (not a handle) as the authority. A bare DID or a URI without a collection and record key is + * rejected; to follow an account, use {@link followAccount}. The record may be of any Lexicon. + */ + targetUri: string; +} + +/** The input of {@link unfollowEntity}, {@link unlike} and {@link unrepost}. */ +export interface RecordTargetInput { + /** + * The record to undo the action for, as the full record URI it was done with. For a like or a + * repost, the version the record pinned does not matter. + */ + targetUri: string; +} + +/** A function that removes one kind of social record, as {@link unfollowAccount} does. */ +export type UndoFunction = (context: SDKContext, input: TInput) => Promise; + +/** + * What differs between the four social actions. The shared create and undo logic is driven by one + * of these (see `createAction` and `undoAction`). + * + * Internal. `TUndo` is the input that names the target, `{ targetDid }` or `{ targetUri }`; + * `TCreate` adds {@link ActionOptions}. + */ +export interface SocialAction { + /** The public functions' names, for error messages. */ + readonly names: { readonly create: string; readonly undo: string }; + /** The lexicon's record schema; its NSID is the only collection the action touches. */ + readonly schema: l.RecordSchema; + /** Validates the input of the create function. */ + readonly createInput: l.Schema; + /** Validates the input of the undo function: the target alone. */ + readonly targetInput: l.Schema; + /** The value stored in the record's `subject` for `target`. */ + readonly subject: (context: SDKContext, target: TUndo) => unknown; + /** Whether the `subject` a stored record holds is `target`. */ + readonly isSubject: (stored: unknown, target: TUndo) => boolean; +} + +const options = { + createdAt: l.optional(l.string()), + via: l.optional( + l.custom( + isRecordUri, + "must be a record URI, at:////, with a DID (not a handle) as the authority", + ), + ), +}; + +const accountDid = l.custom( + isDidString, + "must be an account DID such as did:plc:abc123, not a handle, a record URI or an object", +); + +const recordUri = l.custom( + isRecordUri, + "must be a full record URI, at:////, with a DID (not a handle) as the authority; a bare DID or a URI without a collection and record key is not accepted", +); + +/** The input schemas of an action whose target is an account: `{ targetDid }`. */ +export const accountTarget = { + createInput: strictObject({ targetDid: accountDid, ...options }), + targetInput: strictObject({ targetDid: accountDid }), +}; + +/** The input schemas of an action whose target is a record: `{ targetUri }`. */ +export const recordTarget = { + createInput: strictObject({ targetUri: recordUri, ...options }), + targetInput: strictObject({ targetUri: recordUri }), +}; + +// `parseRecordUri` is the one definition of a record URI; it reports by throwing. +function isRecordUri(value: unknown): value is string { + if (typeof value !== "string") return false; + try { + parseRecordUri(value, "isRecordUri"); + return true; + } catch { + return false; + } +} + +/** + * The URI in a stored `subject`, whether it is a strong reference or a record subject, or + * `undefined` for a value that has none. The CID, when there is one, is not looked at. + */ +export function uriOf(stored: unknown): string | undefined { + if (typeof stored !== "object" || stored === null || !("uri" in stored)) return undefined; + return typeof stored.uri === "string" ? stored.uri : undefined; +} + +/** + * The action of a record whose `subject` is a strong reference to the target: a like or a repost. + * Creating one pins the version of the target current at the time; undoing one matches the + * target's URI whatever version the stored reference pins. + */ +export function recordRefAction( + names: SocialAction["names"], + schema: l.RecordSchema, +): SocialAction { + return { + names, + schema, + ...recordTarget, + subject: (context, { targetUri }) => resolveRecordRef(context, targetUri), + isSubject: (stored, { targetUri }) => uriOf(stored) === targetUri, + }; +} diff --git a/packages/sdk/src/social/create.test.ts b/packages/sdk/src/social/create.test.ts new file mode 100644 index 0000000..32d9406 --- /dev/null +++ b/packages/sdk/src/social/create.test.ts @@ -0,0 +1,203 @@ +import { describe, expect, it } from "vitest"; +import { CID, DID, json } from "../test-utils/fake-pds.js"; +import { fakeRepo, methods, refTo, writeOf } from "../test-utils/fake-repo.js"; +import { followAccount, followEntity, like, repost, WriteOutcomeUnknownError } from "./index.js"; + +const ACCOUNT = "did:plc:abc123"; +const TARGET = `at://${DID}/org.hypercerts.claim.activity/3k2a4b5c6d7e8`; +const VIA = `at://${DID}/app.certified.feed.repost/3k2a4b5c6d7e9`; +const TARGET_CID = CID; +// CIDv1 (raw, sha-256) of the bytes "head". +const VIA_CID = "bafkreie7fzwthi3rp3ucmnj2ibf2iymndlxlnb4226jwxtuo2x2gqfesju"; +const TID = /^[2-7a-z]{13}$/; + +const FOLLOW = "app.certified.graph.follow"; +const ENTITY_FOLLOW = "app.certified.graph.entityFollow"; +const LIKE = "app.certified.feed.like"; +const REPOST = "app.certified.feed.repost"; + +// Each create function with what it must store as `subject`, and the requests it needs for it. +const actions = [ + { + name: "followAccount", + collection: FOLLOW, + create: (context: Parameters[0], options: object) => + followAccount(context, { targetDid: ACCOUNT, ...options }), + subject: ACCOUNT, + reads: [], + }, + { + name: "followEntity", + collection: ENTITY_FOLLOW, + create: (context: Parameters[0], options: object) => + followEntity(context, { targetUri: TARGET, ...options }), + // The URI only: no CID, and the target is not read. + subject: { $type: "app.certified.defs#recordSubject", uri: TARGET }, + reads: [], + }, + { + name: "like", + collection: LIKE, + create: (context: Parameters[0], options: object) => + like(context, { targetUri: TARGET, ...options }), + subject: { uri: TARGET, cid: TARGET_CID }, + reads: ["com.atproto.repo.getRecord"], + }, + { + name: "repost", + collection: REPOST, + create: (context: Parameters[0], options: object) => + repost(context, { targetUri: TARGET, ...options }), + subject: { uri: TARGET, cid: TARGET_CID }, + reads: ["com.atproto.repo.getRecord"], + }, +]; + +// The target and the `via` record exist in the account's repo, except for `followEntity`'s target, +// which must not be needed. +const existing = { [TARGET]: TARGET_CID, [VIA]: VIA_CID }; + +describe.each(actions)("$name", ({ collection, create, subject, reads }) => { + it("writes one record with a TID key and the right subject, and returns its URI and CID", async () => { + const { context, requests, creates } = fakeRepo({ existing }); + const before = Date.now(); + + const ref = await create(context, {}); + + expect(methods(requests)).toEqual([...reads, "com.atproto.repo.applyWrites"]); + const [[write, ...rest] = []] = creates; + expect(rest).toEqual([]); + expect(write).toMatchObject({ collection, value: { $type: collection, subject } }); + expect(write?.rkey).toMatch(TID); + expect(write?.value).not.toHaveProperty("via"); + expect(Date.parse(String(write?.value.createdAt))).toBeGreaterThanOrEqual(before); + expect(ref).toEqual(write && refTo(write)); + }); + + it("pins `via` as a strong reference and keeps `createdAt`", async () => { + const { context, creates } = fakeRepo({ existing }); + + await create(context, { via: VIA, createdAt: "2024-01-01T00:00:00.000Z" }); + + expect(writeOf(creates[0] ?? [], collection).value).toMatchObject({ + createdAt: "2024-01-01T00:00:00.000Z", + via: { uri: VIA, cid: VIA_CID }, + }); + }); +}); + +describe("creating", () => { + it("writes nothing when `via` cannot be read", async () => { + const { context, requests } = fakeRepo(); + + await expect(followAccount(context, { targetDid: ACCOUNT, via: VIA })).rejects.toThrow( + /cannot resolve .*the record was not found/, + ); + + expect(methods(requests)).toEqual(["com.atproto.repo.getRecord"]); + }); + + it("does not look for an existing record: calling again creates another", async () => { + const { context, requests, creates } = fakeRepo({ existing }); + + await like(context, { targetUri: TARGET }); + await like(context, { targetUri: TARGET }); + + expect(methods(requests)).not.toContain("com.atproto.repo.listRecords"); + expect(creates.map(([write]) => write?.rkey)).toHaveLength(2); + expect(creates[0]?.[0]?.rkey).not.toEqual(creates[1]?.[0]?.rkey); + }); + + it("rejects a createdAt the lexicon does not accept before writing", async () => { + const { context, requests } = fakeRepo({ existing }); + + await expect( + followEntity(context, { targetUri: TARGET, createdAt: "yesterday" }), + ).rejects.toThrow( + `followEntity: input is not a valid ${ENTITY_FOLLOW} record: Invalid datetime (got "yesterday") at $.createdAt.`, + ); + + expect(requests).toHaveLength(0); + }); + + it("writes nothing when a like's target does not exist", async () => { + const { context, requests } = fakeRepo(); + + await expect(like(context, { targetUri: TARGET })).rejects.toThrow( + /cannot resolve .*the record was not found/, + ); + + expect(methods(requests)).toEqual(["com.atproto.repo.getRecord"]); + }); +}); + +describe("target validation", () => { + it.each([ + ["a handle", "alice.bsky.social"], + ["a record URI", TARGET], + ["a handle-form URI", "at://alice.bsky.social"], + ["an object", { did: ACCOUNT }], + ["nothing", undefined], + ])("followAccount rejects %s as targetDid", async (_, targetDid) => { + const { context, requests } = fakeRepo(); + + await expect(followAccount(context, { targetDid } as never)).rejects.toThrow( + /^followAccount: invalid input: must be an account DID.*\$\.targetDid/, + ); + + expect(requests).toHaveLength(0); + }); + + it.each([ + ["followEntity", followEntity], + ["like", like], + ["repost", repost], + ])("%s rejects a target that is not a full record URI", async (name, run) => { + const { context, requests } = fakeRepo({ existing }); + const invalid = [ + ACCOUNT, // a bare DID + `at://alice.bsky.social/org.hypercerts.claim.activity/3k2a4b5c6d7e8`, // handle authority + `at://${DID}/org.hypercerts.claim.activity`, // no record key + `at://${DID}`, + "https://example.org/record", + { uri: TARGET }, + ]; + + for (const targetUri of invalid) { + await expect(run(context, { targetUri } as never)).rejects.toThrow( + new RegExp(`^${name}: invalid input: must be a full record URI.*\\$\\.targetUri`), + ); + } + + expect(requests).toHaveLength(0); + }); + + it("rejects a `via` that is not a record URI, and fields the SDK does not know", async () => { + const { context, requests } = fakeRepo({ existing }); + + await expect(like(context, { targetUri: TARGET, via: ACCOUNT })).rejects.toThrow( + /must be a record URI.*\$\.via/, + ); + await expect( + followAccount(context, { targetDid: ACCOUNT, targetUri: TARGET } as never), + ).rejects.toThrow(/field the SDK does not know/); + + expect(requests).toHaveLength(0); + }); +}); + +describe("write failures", () => { + it("reports an unusable answer as WriteOutcomeUnknownError naming the record, without retrying", async () => { + const { context, requests } = fakeRepo({ + applyWrites: () => json(500, { error: "InternalServerError", message: "boom" }), + }); + + const error = await followAccount(context, { targetDid: ACCOUNT }).catch((e) => e); + + expect(error).toBeInstanceOf(WriteOutcomeUnknownError); + expect(error.attempted).toHaveLength(1); + expect(error.attempted[0].uri).toMatch(new RegExp(`^at://${DID}/${FOLLOW}/`)); + expect(error.message).toContain(error.attempted[0].uri); + expect(methods(requests)).toEqual(["com.atproto.repo.applyWrites"]); + }); +}); diff --git a/packages/sdk/src/social/feed.ts b/packages/sdk/src/social/feed.ts new file mode 100644 index 0000000..a75287c --- /dev/null +++ b/packages/sdk/src/social/feed.ts @@ -0,0 +1,221 @@ +import * as likeRecord from "@hypercerts-org/lexicon/app/certified/feed/like"; +import * as repostRecord from "@hypercerts-org/lexicon/app/certified/feed/repost"; +import { recordRefAction } from "./action.js"; +import { createAction, undoAction } from "./run-action.js"; + +const likeAction = recordRefAction({ create: "like", undo: "unlike" }, likeRecord.main); +const repostAction = recordRefAction({ create: "repost", undo: "unrepost" }, repostRecord.main); + +/** + * Likes a record: creates an `app.certified.feed.like` record in the authenticated account's repo. + * + * @remarks + * A like is social feedback and nothing more. It carries no protocol meaning about its target: it is + * not an evaluation, an acknowledgement or proof of endorsement, and applications should not read + * it as one. + * + * The SDK reads the target from the PDS that hosts it (public records of other accounts resolve + * too) and pins the version it finds: the like stores the target's URI and its CID at that moment, + * so a later edit of the target does not change which version was liked. If the target cannot be + * read, nothing is written. The target is never modified or created. The record key is a new TID + * chosen by the SDK, and `createdAt` defaults to the time of the call. + * + * Nothing is deduplicated: calling this again for the same record creates a second like, and a later + * {@link unlike} then does nothing until the duplicate is removed (see {@link UndoResult}). + * + * `via` is optional: the URI of the record through which the target was encountered, typically a + * repost. The SDK reads it the same way. See {@link ActionOptions}. + * + * @param context - The shared context from {@link createSDKContext}. Its client must be + * authenticated. + * @param input - The record to like and optional `createdAt` and `via`. See + * {@link RecordActionInput}. + * @returns The new like's URI and CID (not the target's). + * @throws {@link TypeError} If `input` has an unknown field, a `targetUri` that is not a full record + * URI (a bare DID, a handle authority or a partial URI), a `via` that is not a record URI, or a + * `createdAt` the lexicon rejects. Nothing was written. + * @throws {@link Error} If the client is not authenticated, or the target or the `via` record cannot + * be read (missing, or the PDS cannot be reached). Nothing was written. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). Nothing was created. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the like + * may or may not exist. It carries the URI to check. The SDK does not retry, because a retry would + * create a second like with a new key if the first attempt had succeeded. + * @throws {@link WriteResultMismatchError} If the PDS reported a different URI or CID than the SDK + * computed. + * + * @example + * ```ts + * import { like } from "@hypercerts-org/sdk/social"; + * + * // `context` comes from createSDKContext. + * const liked = await like(context, { + * targetUri: "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e8", + * }); + * console.log(liked.uri); // at:///app.certified.feed.like/ + * ``` + * + * @example Liking something found through a repost + * ```ts + * import { like } from "@hypercerts-org/sdk/social"; + * + * await like(context, { + * targetUri: "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e8", + * via: "at://did:plc:def456/app.certified.feed.repost/3k2a4b5c6d7e9", // read and pinned for you + * }); + * ``` + */ +export const like = createAction(likeAction); + +/** + * Removes a like: deletes the authenticated account's one `app.certified.feed.like` record for + * `targetUri`. + * + * @remarks + * The SDK lists the account's own likes (all pages, from its own PDS; no indexer) and matches them + * by the URI of the record they like, whatever CID they pin, so a like of an earlier version of an + * edited target is found too. With no match it returns `not-found`. With exactly one it deletes that + * record, only if it still has the CID the scan saw, and returns `deleted`. With several it deletes + * nothing and returns `ambiguous` with the number of matches: the record was liked more than once, + * and the SDK does not choose which like to remove. See {@link UndoResult}. + * + * The target is not read, so it does not have to exist any more. The scan is a snapshot: it cannot + * stop another writer creating a like of the same record while it runs or after it, so `deleted` + * does not promise that no like of `targetUri` remains. + * + * The session needs permission to delete `app.certified.feed.like` records. + * + * @param context - The shared context from {@link createSDKContext}. Its client must be + * authenticated; only that account's repository is scanned. + * @param input - The record to unlike. See {@link RecordTargetInput}. + * @returns `deleted`, `not-found` or `ambiguous` with `matchCount`. See {@link UndoResult}. + * @throws {@link TypeError} If `input` has an unknown field or a `targetUri` that is not a full + * record URI. Nothing was changed. + * @throws {@link Error} If the client is not authenticated, or the likes cannot be read in full (a + * failed or malformed page). A partial read is never treated as "not found". Nothing was changed. + * @throws {@link WriteRejectedError} If the PDS refused the deletion (HTTP 4xx). With `code` + * `"InvalidSwap"` the like changed after the scan, so it was not deleted; nothing is retried or + * deleted without that check, and calling again scans afresh. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the like + * may or may not be deleted. It carries the like's URI and CID. The SDK does not retry; calling + * again is safe and either deletes the like or returns `not-found`. + * + * @example + * ```ts + * import { unlike } from "@hypercerts-org/sdk/social"; + * + * // `context` comes from createSDKContext. + * const result = await unlike(context, { + * targetUri: "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e8", + * }); + * if (result.status === "ambiguous") { + * // Liked more than once, so nothing was deleted: remove the extra likes yourself. + * } + * ``` + */ +export const unlike = undoAction(likeAction); + +/** + * Reposts a record: creates an `app.certified.feed.repost` record in the authenticated account's + * repo, surfacing the target to the account's followers. + * + * @remarks + * The SDK reads the target from the PDS that hosts it (public records of other accounts resolve + * too) and pins the version it finds: the repost stores the target's URI and its CID at that + * moment, so a later edit of the target does not change which version was reposted. If the target + * cannot be read, nothing is written. The target is never modified or created. The record key is a + * new TID chosen by the SDK, and `createdAt` defaults to the time of the call. + * + * Nothing is deduplicated: calling this again for the same record creates a second repost, and a + * later {@link unrepost} then does nothing until the duplicate is removed (see {@link UndoResult}). + * + * `via` is optional: the URI of the record through which the target was encountered, typically + * another repost. The SDK reads it the same way. See {@link ActionOptions}. + * + * @param context - The shared context from {@link createSDKContext}. Its client must be + * authenticated. + * @param input - The record to repost and optional `createdAt` and `via`. See + * {@link RecordActionInput}. + * @returns The new repost's URI and CID (not the target's). + * @throws {@link TypeError} If `input` has an unknown field, a `targetUri` that is not a full record + * URI (a bare DID, a handle authority or a partial URI), a `via` that is not a record URI, or a + * `createdAt` the lexicon rejects. Nothing was written. + * @throws {@link Error} If the client is not authenticated, or the target or the `via` record cannot + * be read (missing, or the PDS cannot be reached). Nothing was written. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). Nothing was created. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the + * repost may or may not exist. It carries the URI to check. The SDK does not retry, because a retry + * would create a second repost with a new key if the first attempt had succeeded. + * @throws {@link WriteResultMismatchError} If the PDS reported a different URI or CID than the SDK + * computed. + * + * @example + * ```ts + * import { repost } from "@hypercerts-org/sdk/social"; + * + * // `context` comes from createSDKContext. + * const reposted = await repost(context, { + * targetUri: "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e8", + * }); + * console.log(reposted.uri); // at:///app.certified.feed.repost/ + * ``` + * + * @example Reposting something found through another repost + * ```ts + * import { repost } from "@hypercerts-org/sdk/social"; + * + * await repost(context, { + * targetUri: "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e8", + * via: "at://did:plc:def456/app.certified.feed.repost/3k2a4b5c6d7e9", // read and pinned for you + * }); + * ``` + */ +export const repost = createAction(repostAction); + +/** + * Removes a repost: deletes the authenticated account's one `app.certified.feed.repost` record for + * `targetUri`. + * + * @remarks + * The SDK lists the account's own reposts (all pages, from its own PDS; no indexer) and matches + * them by the URI of the record they repost, whatever CID they pin, so a repost of an earlier + * version of an edited target is found too. With no match it returns `not-found`. With exactly one + * it deletes that record, only if it still has the CID the scan saw, and returns `deleted`. With + * several it deletes nothing and returns `ambiguous` with the number of matches: the record was + * reposted more than once, and the SDK does not choose which repost to remove. See + * {@link UndoResult}. + * + * The target is not read, so it does not have to exist any more. The scan is a snapshot: it cannot + * stop another writer creating a repost of the same record while it runs or after it, so `deleted` + * does not promise that no repost of `targetUri` remains. + * + * The session needs permission to delete `app.certified.feed.repost` records. + * + * @param context - The shared context from {@link createSDKContext}. Its client must be + * authenticated; only that account's repository is scanned. + * @param input - The record to unrepost. See {@link RecordTargetInput}. + * @returns `deleted`, `not-found` or `ambiguous` with `matchCount`. See {@link UndoResult}. + * @throws {@link TypeError} If `input` has an unknown field or a `targetUri` that is not a full + * record URI. Nothing was changed. + * @throws {@link Error} If the client is not authenticated, or the reposts cannot be read in full (a + * failed or malformed page). A partial read is never treated as "not found". Nothing was changed. + * @throws {@link WriteRejectedError} If the PDS refused the deletion (HTTP 4xx). With `code` + * `"InvalidSwap"` the repost changed after the scan, so it was not deleted; nothing is retried or + * deleted without that check, and calling again scans afresh. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the repost + * may or may not be deleted. It carries the repost's URI and CID. The SDK does not retry; calling + * again is safe and either deletes the repost or returns `not-found`. + * + * @example + * ```ts + * import { unrepost } from "@hypercerts-org/sdk/social"; + * + * // `context` comes from createSDKContext. + * const result = await unrepost(context, { + * targetUri: "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e8", + * }); + * if (result.status === "ambiguous") { + * // Reposted more than once, so nothing was deleted: remove the extra reposts yourself. + * } + * ``` + */ +export const unrepost = undoAction(repostAction); diff --git a/packages/sdk/src/social/graph.ts b/packages/sdk/src/social/graph.ts new file mode 100644 index 0000000..0d0f244 --- /dev/null +++ b/packages/sdk/src/social/graph.ts @@ -0,0 +1,252 @@ +import { asAtUriString } from "@atproto/lex"; +import * as defs from "@hypercerts-org/lexicon/app/certified/defs"; +import * as entityFollow from "@hypercerts-org/lexicon/app/certified/graph/entityFollow"; +import * as follow from "@hypercerts-org/lexicon/app/certified/graph/follow"; +import { + accountTarget, + type FollowAccountInput, + type RecordActionInput, + type RecordTargetInput, + recordTarget, + type SocialAction, + type UnfollowAccountInput, + uriOf, +} from "./action.js"; +import { createAction, undoAction } from "./run-action.js"; + +const followAccountAction: SocialAction = { + names: { create: "followAccount", undo: "unfollowAccount" }, + schema: follow.main, + ...accountTarget, + subject: (_context, { targetDid }) => targetDid, + isSubject: (stored, { targetDid }) => stored === targetDid, +}; + +const followEntityAction: SocialAction = { + names: { create: "followEntity", undo: "unfollowEntity" }, + schema: entityFollow.main, + ...recordTarget, + // The URI only: no CID, so the follow keeps pointing at the record when it is updated. + subject: (_context, { targetUri }) => defs.recordSubject.build({ uri: asAtUriString(targetUri) }), + isSubject: (stored, { targetUri }) => + typeof stored === "object" && + stored !== null && + "$type" in stored && + stored.$type === defs.recordSubject.$type && + uriOf(stored) === targetUri, +}; + +/** + * Follows an account: creates an `app.certified.graph.follow` record in the authenticated + * account's repo. + * + * @remarks + * `targetDid` is the account being followed. Nothing about it is looked up: the SDK does not check + * that the account exists or has a Certified profile. The record key is a new TID chosen by the + * SDK, and `createdAt` defaults to the time of the call. + * + * Nothing is deduplicated: calling this again for an account that is already followed creates a + * second follow record, and a later {@link unfollowAccount} then does nothing until the duplicate is + * removed (see {@link UndoResult}). + * + * `via` is optional: the URI of a record through which the account was found (a starter pack, for + * example). The SDK reads it to pin its current version. See {@link ActionOptions}. + * + * @param context - The shared context from {@link createSDKContext}. Its client must be + * authenticated. + * @param input - The account to follow and optional `createdAt` and `via`. See + * {@link FollowAccountInput}. + * @returns The new record's URI and CID. + * @throws {@link TypeError} If `input` has an unknown field, a `targetDid` that is not a DID (a + * handle, for example), a `via` that is not a record URI, or a `createdAt` the lexicon rejects. + * Nothing was written. + * @throws {@link Error} If the client is not authenticated, or the `via` record cannot be read. + * Nothing was written. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx), for example because + * the session may not create `app.certified.graph.follow` records. Nothing was created. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the + * record may or may not exist. It carries the URI to check. The SDK does not retry, because a retry + * would create a second follow with a new key if the first attempt had succeeded. + * @throws {@link WriteResultMismatchError} If the PDS reported a different URI or CID than the SDK + * computed. + * + * @example + * ```ts + * import { followAccount } from "@hypercerts-org/sdk/social"; + * + * // `context` comes from createSDKContext. + * const follow = await followAccount(context, { targetDid: "did:plc:abc123" }); + * console.log(follow.uri); // at:///app.certified.graph.follow/ + * ``` + * + * @example A handle is not an account identifier here + * ```ts + * import { followAccount } from "@hypercerts-org/sdk/social"; + * + * // Does not compile: `targetDid` is a `DidString`. A JavaScript caller, or a cast, gets a + * // TypeError at runtime. Resolve the handle to a DID yourself first. + * await followAccount(context, { targetDid: "alice.bsky.social" }); + * ``` + * + * @example A DID that arrives as a plain string + * ```ts + * import { isDidString } from "@atproto/lex"; + * import { followAccount } from "@hypercerts-org/sdk/social"; + * + * // `did` is a string, for example from a form field. `isDidString` checks it and narrows the type. + * if (!isDidString(did)) throw new Error(`${did} is not a DID`); + * await followAccount(context, { targetDid: did }); + * ``` + */ +export const followAccount = createAction(followAccountAction); + +/** + * Stops following an account: deletes the authenticated account's one + * `app.certified.graph.follow` record for `targetDid`. + * + * @remarks + * The SDK lists the account's own follow records (all pages, from its own PDS; no indexer), and + * matches them by the DID they follow. With no match it returns `not-found`. With exactly one it + * deletes that record, only if it still has the CID the scan saw, and returns `deleted`. With + * several it deletes nothing and returns `ambiguous` with the number of matches: the account + * followed the same DID more than once, and the SDK does not choose which record to remove. See + * {@link UndoResult}. + * + * The scan is a snapshot. It cannot stop another writer creating a follow of the same account while + * it runs or after it, so a result of `deleted` does not promise that no follow of `targetDid` + * remains. The account being followed does not have to exist any more. + * + * The session needs permission to delete `app.certified.graph.follow` records. + * + * @param context - The shared context from {@link createSDKContext}. Its client must be + * authenticated; only that account's repository is scanned. + * @param input - The account to stop following. See {@link UnfollowAccountInput}. + * @returns `deleted`, `not-found` or `ambiguous` with `matchCount`. See {@link UndoResult}. + * @throws {@link TypeError} If `input` has an unknown field or a `targetDid` that is not a DID. + * Nothing was changed. + * @throws {@link Error} If the client is not authenticated, or the follow records cannot be read in + * full (a failed or malformed page). A partial read is never treated as "not found". Nothing was + * changed. + * @throws {@link WriteRejectedError} If the PDS refused the deletion (HTTP 4xx). With `code` + * `"InvalidSwap"` the record changed after the scan, so it was not deleted; nothing is retried or + * deleted without that check, and calling again scans afresh. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the record + * may or may not be deleted. It carries the record's URI and CID. The SDK does not retry; calling + * again is safe and either deletes the record or returns `not-found`. + * + * @example + * ```ts + * import { unfollowAccount } from "@hypercerts-org/sdk/social"; + * + * // `context` comes from createSDKContext. + * const result = await unfollowAccount(context, { targetDid: "did:plc:abc123" }); + * if (result.status === "ambiguous") { + * // Followed more than once, so nothing was deleted: remove the extra follow records yourself. + * console.log(`${result.matchCount} follow records for this account`); + * } + * ``` + */ +export const unfollowAccount = undoAction(followAccountAction); + +/** + * Follows a record's identity: creates an `app.certified.graph.entityFollow` record in the + * authenticated account's repo. + * + * @remarks + * The follow stores the target's URI as a `app.certified.defs#recordSubject` and no CID, so it + * keeps pointing at the record through later updates. The target is not read: the SDK does not + * check that it exists, so a follow of a record that is missing, private or of an unknown Lexicon + * is created all the same. (A like or a repost differs: see {@link like}, which pins the version it + * read.) The record key is a new TID chosen by the SDK, and `createdAt` defaults to the time of the + * call. + * + * Nothing is deduplicated: calling this again for the same record creates a second follow, and a + * later {@link unfollowEntity} then does nothing until the duplicate is removed (see + * {@link UndoResult}). + * + * `via` is optional: the URI of a record through which the target was found. The SDK reads it to + * pin its current version. See {@link ActionOptions}. + * + * @param context - The shared context from {@link createSDKContext}. Its client must be + * authenticated. + * @param input - The record to follow and optional `createdAt` and `via`. See + * {@link RecordActionInput}. + * @returns The new record's URI and CID. + * @throws {@link TypeError} If `input` has an unknown field, a `targetUri` that is not a full record + * URI (a bare DID, a handle authority or a partial URI), a `via` that is not a record URI, or a + * `createdAt` the lexicon rejects. Nothing was written. + * @throws {@link Error} If the client is not authenticated, or the `via` record cannot be read. + * Nothing was written. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). Nothing was created. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the + * record may or may not exist. It carries the URI to check. The SDK does not retry, because a retry + * would create a second follow with a new key if the first attempt had succeeded. + * @throws {@link WriteResultMismatchError} If the PDS reported a different URI or CID than the SDK + * computed. + * + * @example + * ```ts + * import { followEntity } from "@hypercerts-org/sdk/social"; + * + * // `context` comes from createSDKContext. + * const follow = await followEntity(context, { + * targetUri: "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e8", + * }); + * ``` + * + * @example An account is not a record + * ```ts + * import { followAccount, followEntity } from "@hypercerts-org/sdk/social"; + * + * await followEntity(context, { targetUri: "did:plc:abc123" }); // TypeError + * await followAccount(context, { targetDid: "did:plc:abc123" }); // follow an account like this + * ``` + */ +export const followEntity = createAction(followEntityAction); + +/** + * Stops following a record: deletes the authenticated account's one + * `app.certified.graph.entityFollow` record for `targetUri`. + * + * @remarks + * The SDK lists the account's own entity follows (all pages, from its own PDS; no indexer), and + * matches them by the record URI they follow. With no match it returns `not-found`. With exactly one + * it deletes that record, only if it still has the CID the scan saw, and returns `deleted`. With + * several it deletes nothing and returns `ambiguous` with the number of matches: the record was + * followed more than once, and the SDK does not choose which follow to remove. See + * {@link UndoResult}. + * + * The target is not read, so it does not have to exist any more. The scan is a snapshot: it cannot + * stop another writer creating a follow of the same record while it runs or after it, so `deleted` + * does not promise that no follow of `targetUri` remains. + * + * The session needs permission to delete `app.certified.graph.entityFollow` records. + * + * @param context - The shared context from {@link createSDKContext}. Its client must be + * authenticated; only that account's repository is scanned. + * @param input - The record to stop following. See {@link RecordTargetInput}. + * @returns `deleted`, `not-found` or `ambiguous` with `matchCount`. See {@link UndoResult}. + * @throws {@link TypeError} If `input` has an unknown field or a `targetUri` that is not a full + * record URI. Nothing was changed. + * @throws {@link Error} If the client is not authenticated, or the entity follows cannot be read in + * full (a failed or malformed page). A partial read is never treated as "not found". Nothing was + * changed. + * @throws {@link WriteRejectedError} If the PDS refused the deletion (HTTP 4xx). With `code` + * `"InvalidSwap"` the record changed after the scan, so it was not deleted; nothing is retried or + * deleted without that check, and calling again scans afresh. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the record + * may or may not be deleted. It carries the record's URI and CID. The SDK does not retry; calling + * again is safe and either deletes the record or returns `not-found`. + * + * @example + * ```ts + * import { unfollowEntity } from "@hypercerts-org/sdk/social"; + * + * // `context` comes from createSDKContext. + * const result = await unfollowEntity(context, { + * targetUri: "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e8", + * }); + * console.log(result.status); // "deleted", "not-found" or "ambiguous" + * ``` + */ +export const unfollowEntity = undoAction(followEntityAction); diff --git a/packages/sdk/src/social/index.ts b/packages/sdk/src/social/index.ts new file mode 100644 index 0000000..6d8eeb3 --- /dev/null +++ b/packages/sdk/src/social/index.ts @@ -0,0 +1,21 @@ +// Entry point for @hypercerts-org/sdk/social. +// +// Covers the social graph and feed records: follows and entity follows (`app.certified.graph.*`) +// and likes and reposts (`app.certified.feed.*`), with the operations that undo them. +export type { StrongRef } from "../internal/resolve-record-ref.js"; +export { + WriteError, + WriteOutcomeUnknownError, + WriteRejectedError, + WriteResultMismatchError, +} from "../internal/submit-writes.js"; +export type { + ActionOptions, + FollowAccountInput, + RecordActionInput, + RecordTargetInput, + UndoResult, + UnfollowAccountInput, +} from "./action.js"; +export { like, repost, unlike, unrepost } from "./feed.js"; +export { followAccount, followEntity, unfollowAccount, unfollowEntity } from "./graph.js"; diff --git a/packages/sdk/src/social/list-collection.ts b/packages/sdk/src/social/list-collection.ts new file mode 100644 index 0000000..14622b1 --- /dev/null +++ b/packages/sdk/src/social/list-collection.ts @@ -0,0 +1,113 @@ +import type { DidString, NsidString } from "@atproto/lex"; +import * as strongRef from "@hypercerts-org/lexicon/com/atproto/repo/strongRef"; +import type { SDKContext } from "../context.js"; +import { describeError } from "../internal/describe.js"; +import type { StoredRecord } from "../internal/resolve-record-ref.js"; + +// The most `com.atproto.repo.listRecords` returns in one page. +const PAGE_SIZE = 100; + +/** + * Reads every record of `collection` in `did`'s repo, page after page, with + * `com.atproto.repo.listRecords` through the client. + * + * Internal. Boundaries: + * - The client's own repository, read from its own PDS: the typed record methods never go through + * an AppView, and no indexer is consulted. + * - A page that cannot be read or does not look like a page of that collection is an error, never + * the end of the list: a caller that treats "no match" as "nothing to do" must not be fooled by + * an incomplete read. So is a cursor the PDS repeats, which would never end. + * - The result is a snapshot: records written while the pages are read may or may not be in it. + * + * Throws Error, naming `operation`, when a page cannot be read or is malformed. + */ +export async function listCollection( + context: SDKContext, + did: DidString, + collection: NsidString, + operation: string, +): Promise { + const records: StoredRecord[] = []; + const seen = new Set(); + let cursor: string | undefined; + do { + const page = await readPage(context, { did, collection, cursor, operation }); + records.push(...page.records); + cursor = page.cursor; + if (cursor !== undefined) { + if (seen.has(cursor)) { + throw incomplete( + { did, collection, operation }, + `the PDS returned the cursor ${JSON.stringify(cursor)} twice`, + ); + } + seen.add(cursor); + } + } while (cursor !== undefined); + return records; +} + +interface Read { + readonly did: DidString; + readonly collection: NsidString; + readonly operation: string; +} + +async function readPage( + context: SDKContext, + read: Read & { readonly cursor: string | undefined }, +): Promise<{ records: StoredRecord[]; cursor: string | undefined }> { + const { did, collection, cursor } = read; + let body: unknown; + try { + const response = await context.client.listRecords(collection, { + repo: did, + limit: PAGE_SIZE, + ...(cursor === undefined ? {} : { cursor }), + }); + body = response.body; + } catch (error) { + throw incomplete(read, `the read failed (${describeError(error)})`, error); + } + return toPage(read, body); +} + +function toPage( + read: Read, + body: unknown, +): { records: StoredRecord[]; cursor: string | undefined } { + const { records, cursor } = (typeof body === "object" && body !== null ? body : {}) as { + records?: unknown; + cursor?: unknown; + }; + if (!Array.isArray(records)) throw incomplete(read, "the PDS returned no list of records"); + if (cursor !== undefined && typeof cursor !== "string") { + throw incomplete(read, "the PDS returned a cursor that is not a string"); + } + return { records: records.map((entry) => toRecord(read, entry)), cursor }; +} + +// Checked here as well as by the client, because an application can turn off the client's +// response validation. A record the account does not own, or from another collection, is not +// deleted on the strength of a listing that claims it is one. +function toRecord(read: Read, entry: unknown): StoredRecord { + if (!strongRef.main.matches(entry)) { + throw incomplete(read, "a record has no valid URI and CID"); + } + const { value } = entry as { value?: unknown }; + if (typeof value !== "object" || value === null || Array.isArray(value)) { + throw incomplete(read, `${entry.uri} has no value`); + } + const { did, collection } = read; + if (!entry.uri.startsWith(`at://${did}/${collection}/`)) { + throw incomplete(read, `${entry.uri} is not a ${collection} record of ${did}`); + } + return { ref: { uri: entry.uri, cid: entry.cid }, value: value as StoredRecord["value"] }; +} + +function incomplete({ did, collection, operation }: Read, reason: string, cause?: unknown): Error { + return new Error( + `${operation}: cannot read all ${collection} records of ${did}: ${reason}, so it is not known whether the account has a matching record. Nothing was changed. Call again; if it keeps failing, check the session and the PDS.`, + cause === undefined ? undefined : { cause }, + ); +} diff --git a/packages/sdk/src/social/run-action.ts b/packages/sdk/src/social/run-action.ts new file mode 100644 index 0000000..d2fc70c --- /dev/null +++ b/packages/sdk/src/social/run-action.ts @@ -0,0 +1,90 @@ +import type { l } from "@atproto/lex"; +import type { SDKContext } from "../context.js"; +import { + type BuildContext, + createBuildContext, + parseInput, + prepareChecked, +} from "../internal/build-context.js"; +import type { StandaloneCreator } from "../internal/create-record.js"; +import { compact } from "../internal/input.js"; +import { resolveRecordRef } from "../internal/resolve-record-ref.js"; +import { submitDelete, submitWrites } from "../internal/submit-writes.js"; +import type { ActionOptions, SocialAction, UndoFunction } from "./action.js"; +import { listCollection } from "./list-collection.js"; + +/** + * The function that creates one social record (a follow, an entity follow, a like or a repost) in + * the client's repo: validates the input, reads the records it must point at, builds the record and + * writes it. + * + * Internal. Boundaries: + * - Writes with a new TID key each call, and looks for nothing that exists already, so calling it + * again for the same target creates another record. + * - Reads `via` (and, for a like or a repost, the target) from the PDS that hosts it, and writes + * nothing if a read fails. + * - Does not touch the target or `via`. + * + * The function throws TypeError for invalid input, and what the reads and `submitWrites` throw. + */ +export function createAction( + action: SocialAction, +): StandaloneCreator { + return async (context, input) => { + const { build, parsed } = start(context, action.names.create, action.createInput, input); + const [subject, via] = await Promise.all([ + action.subject(context, parsed), + parsed.via === undefined ? undefined : resolveRecordRef(context, parsed.via), + ]); + const record = await prepareChecked( + build, + "input", + action.schema, + compact({ subject, createdAt: parsed.createdAt ?? build.createdAt, via }) as never, + ); + // No retry: a second request would create a second record under a new key. + await submitWrites(context, build.did, [record], build.operation); + return record.ref; + }; +} + +/** + * The function that removes the one social record in the client's repo that is for the input's + * target. + * + * Internal. Boundaries: + * - Looks only at the action's collection in the client's own repository, and reads all of it + * (see `listCollection`). It does not read the target, so a target that was edited or deleted + * does not prevent the removal. No indexer is consulted. + * - Deletes only when exactly one record matches, and then only if that record still has the CID + * the scan saw (see `submitDelete`). With several matches it deletes nothing. + * - The scan is a snapshot; it cannot stop another writer creating a matching record. + * + * The function throws TypeError for invalid input, Error when the collection cannot be read in + * full, and what `submitDelete` throws. + */ +export function undoAction( + action: SocialAction, +): UndoFunction { + return async (context, input) => { + const { build, parsed } = start(context, action.names.undo, action.targetInput, input); + const records = await listCollection(context, build.did, action.schema.$type, build.operation); + const matches = records.filter(({ value }) => action.isSubject(value.subject, parsed)); + const [match, ...others] = matches; + if (match === undefined) return { status: "not-found" }; + if (others.length > 0) return { status: "ambiguous", matchCount: matches.length }; + await submitDelete(context, build.did, match.ref, build.operation); + return { status: "deleted" }; + }; +} + +// Checks that the client is signed in, then the input, before anything is sent. +function start( + context: SDKContext, + operation: string, + schema: l.Schema, + input: unknown, +): { build: BuildContext; parsed: T } { + const build = createBuildContext(context, operation); + return { build, parsed: parseInput(build, "input", schema, input) }; +} diff --git a/packages/sdk/src/social/undo.test.ts b/packages/sdk/src/social/undo.test.ts new file mode 100644 index 0000000..355c310 --- /dev/null +++ b/packages/sdk/src/social/undo.test.ts @@ -0,0 +1,295 @@ +import { describe, expect, it } from "vitest"; +import { fakeCollection, type StoredEntry } from "../test-utils/fake-collection.js"; +import { CID, DID, json } from "../test-utils/fake-pds.js"; +import { methods } from "../test-utils/fake-repo.js"; +import { + unfollowAccount, + unfollowEntity, + unlike, + unrepost, + WriteOutcomeUnknownError, + WriteRejectedError, +} from "./index.js"; + +const ACCOUNT = "did:plc:abc123"; +const OTHER_ACCOUNT = "did:plc:other456"; +const TARGET = `at://${DID}/org.hypercerts.claim.activity/3k2a4b5c6d7e8`; +const OTHER_TARGET = `at://${DID}/org.hypercerts.claim.activity/3k2a4b5c6d7e9`; +// CIDv1 (raw, sha-256) of the bytes "head": a version of the target other than CID. +const OLD_CID = "bafkreie7fzwthi3rp3ucmnj2ibf2iymndlxlnb4226jwxtuo2x2gqfesju"; +const CREATED_AT = "2024-01-01T00:00:00.000Z"; + +type Context = Parameters[0]; + +// Each undo function, the record it removes, and the same kind of record for another target. +const actions = [ + { + name: "unfollowAccount", + collection: "app.certified.graph.follow", + undo: (context: Context) => unfollowAccount(context, { targetDid: ACCOUNT }), + record: (subject: string) => subject, + mine: ACCOUNT, + others: OTHER_ACCOUNT, + }, + { + name: "unfollowEntity", + collection: "app.certified.graph.entityFollow", + undo: (context: Context) => unfollowEntity(context, { targetUri: TARGET }), + record: (subject: string) => ({ $type: "app.certified.defs#recordSubject", uri: subject }), + mine: TARGET, + others: OTHER_TARGET, + }, + { + name: "unlike", + collection: "app.certified.feed.like", + undo: (context: Context) => unlike(context, { targetUri: TARGET }), + // Pins a version of the target that is not the one it has now. + record: (subject: string) => ({ uri: subject, cid: OLD_CID }), + mine: TARGET, + others: OTHER_TARGET, + }, + { + name: "unrepost", + collection: "app.certified.feed.repost", + undo: (context: Context) => unrepost(context, { targetUri: TARGET }), + record: (subject: string) => ({ uri: subject, cid: OLD_CID }), + mine: TARGET, + others: OTHER_TARGET, + }, +]; + +describe.each(actions)("$name", ({ collection, undo, record, mine, others }) => { + const entry = (rkey: string, subject: string): StoredEntry => ({ + rkey, + cid: CID, + value: { $type: collection, subject: record(subject), createdAt: CREATED_AT }, + }); + + it("deletes the one matching record, guarded by its CID, without reading the target", async () => { + // The target now has another CID than the one the record pins; it is not read anyway. + const { context, requests, deletes, lists } = fakeCollection({ + entries: { [collection]: [entry("3aaaaaaaaaaaa", others), entry("3bbbbbbbbbbbb", mine)] }, + existing: { [TARGET]: CID }, + }); + + const result = await undo(context); + + expect(result).toEqual({ status: "deleted" }); + expect(deletes).toEqual([{ repo: DID, collection, rkey: "3bbbbbbbbbbbb", swapRecord: CID }]); + expect(lists).toEqual([{ repo: DID, collection, cursor: null, limit: "100" }]); + expect(methods(requests)).toEqual([ + "com.atproto.repo.listRecords", + "com.atproto.repo.deleteRecord", + ]); + }); + + it("returns not-found, and deletes nothing, when no record matches", async () => { + const { context, requests, deletes } = fakeCollection({ + entries: { + [collection]: [entry("3aaaaaaaaaaaa", others)], + // The same subject in another collection is not this action's record. + "app.certified.graph.other": [entry("3bbbbbbbbbbbb", mine)], + }, + }); + + await expect(undo(context)).resolves.toEqual({ status: "not-found" }); + + expect(deletes).toEqual([]); + expect(methods(requests)).toEqual(["com.atproto.repo.listRecords"]); + }); + + it("returns ambiguous with the count, and deletes nothing, when several records match", async () => { + const { context, deletes } = fakeCollection({ + entries: { + [collection]: [entry("3aaaaaaaaaaaa", mine), entry("3bbbbbbbbbbbb", mine)], + }, + }); + + await expect(undo(context)).resolves.toEqual({ status: "ambiguous", matchCount: 2 }); + + expect(deletes).toEqual([]); + }); +}); + +describe("unfollowEntity matching", () => { + const collection = "app.certified.graph.entityFollow"; + const stored = (rkey: string, subject?: unknown): StoredEntry => ({ + rkey, + cid: CID, + value: { + $type: collection, + createdAt: CREATED_AT, + ...(subject === undefined ? {} : { subject }), + }, + }); + + it("does not match a subject of another type with the same uri, or a record without a usable subject", async () => { + const { context, deletes } = fakeCollection({ + entries: { + [collection]: [ + stored("3aaaaaaaaaaaa", { $type: "app.example.other#subject", uri: TARGET }), + stored("3bbbbbbbbbbbb", { uri: TARGET }), + stored("3cccccccccccc"), + stored("3dddddddddddd", { $type: "app.certified.defs#recordSubject" }), + stored("3eeeeeeeeeeee", ACCOUNT), + ], + }, + }); + + await expect(unfollowEntity(context, { targetUri: TARGET })).resolves.toEqual({ + status: "not-found", + }); + + expect(deletes).toEqual([]); + }); +}); + +describe("scanning the records", () => { + const collection = "app.certified.feed.like"; + const like = (rkey: string, subject: string): StoredEntry => ({ + rkey, + cid: CID, + value: { $type: collection, subject: { uri: subject, cid: OLD_CID }, createdAt: CREATED_AT }, + }); + const unlikeTarget = (context: Context) => unlike(context, { targetUri: TARGET }); + + it("reads every page, so a single match on the last page is found", async () => { + const { context, deletes, lists } = fakeCollection({ + pageSize: 2, + entries: { + [collection]: [ + like("3aaaaaaaaaaaa", OTHER_TARGET), + like("3bbbbbbbbbbbb", OTHER_TARGET), + like("3cccccccccccc", OTHER_TARGET), + like("3dddddddddddd", OTHER_TARGET), + like("3eeeeeeeeeeee", TARGET), + ], + }, + }); + + await expect(unlikeTarget(context)).resolves.toEqual({ status: "deleted" }); + + expect(lists.map((list) => list.cursor)).toEqual([null, "2", "4"]); + expect(deletes.map(({ rkey }) => rkey)).toEqual(["3eeeeeeeeeeee"]); + }); + + it("counts matches over all pages", async () => { + const { context, deletes } = fakeCollection({ + pageSize: 2, + entries: { + [collection]: [ + like("3aaaaaaaaaaaa", TARGET), + like("3bbbbbbbbbbbb", OTHER_TARGET), + like("3cccccccccccc", TARGET), + like("3dddddddddddd", OTHER_TARGET), + like("3eeeeeeeeeeee", TARGET), + ], + }, + }); + + await expect(unlikeTarget(context)).resolves.toEqual({ status: "ambiguous", matchCount: 3 }); + + expect(deletes).toEqual([]); + }); + + describe("when the records cannot be read in full", () => { + // The first page holds the one match: acting on it would be wrong if the rest cannot be read. + const firstPage = { + records: [ + { + uri: `at://${DID}/${collection}/3aaaaaaaaaaaa`, + cid: CID, + value: like("3aaaaaaaaaaaa", TARGET).value, + }, + ], + cursor: "1", + }; + const foreign = (uri: string) => json(200, { records: [{ uri, cid: CID, value: {} }] }); + + it.each([ + ["a server error", () => json(500, { error: "InternalServerError", message: "boom" })], + ["a client error", () => json(400, { error: "InvalidRequest", message: "bad cursor" })], + ["a response without records", () => json(200, {})], + [ + "a record of another collection", + () => foreign(`at://${DID}/app.bsky.feed.post/3zzzzzzzzzzzz`), + ], + [ + "a record of another repository", + () => foreign(`at://did:plc:somebody/${collection}/3zzzzzzzzzzzz`), + ], + ["a cursor that repeats", () => json(200, { records: [], cursor: "1" })], + ])("throws, and deletes nothing, after %s", async (_, secondPage) => { + let pages = 0; + const { context, requests } = fakeCollection({ + listRecords: () => (++pages === 1 ? json(200, firstPage) : secondPage()), + }); + + await expect(unlikeTarget(context)).rejects.toThrow( + new RegExp(`^unlike: cannot read all ${collection} records of ${DID}`), + ); + + expect(methods(requests)).not.toContain("com.atproto.repo.deleteRecord"); + }); + }); +}); + +describe("deleting the selected record", () => { + const collection = "app.certified.feed.like"; + const entries = { + [collection]: [ + { + rkey: "3aaaaaaaaaaaa", + cid: CID, + value: { $type: collection, subject: { uri: TARGET, cid: OLD_CID }, createdAt: CREATED_AT }, + }, + ], + }; + const deleteRequests = (requests: Parameters[0]) => + methods(requests).filter((method) => method.endsWith("deleteRecord")); + + it("does not delete when the record changed after it was read (CID conflict), and does not retry", async () => { + const { context, requests } = fakeCollection({ + entries, + deleteRecord: () => json(400, { error: "InvalidSwap", message: "Record CID did not match" }), + }); + + const error = await unlike(context, { targetUri: TARGET }).catch((e) => e); + + expect(error).toBeInstanceOf(WriteRejectedError); + expect(error).toMatchObject({ status: 400, code: "InvalidSwap" }); + expect(error.message).toMatch(/no longer has the version .* not deleted/); + expect(deleteRequests(requests)).toHaveLength(1); + }); + + it("reports an unusable answer as WriteOutcomeUnknownError naming the record, and does not retry", async () => { + const { context, requests } = fakeCollection({ + entries, + deleteRecord: () => json(500, { error: "InternalServerError", message: "boom" }), + }); + + const error = await unlike(context, { targetUri: TARGET }).catch((e) => e); + + expect(error).toBeInstanceOf(WriteOutcomeUnknownError); + expect(error.attempted).toEqual([{ uri: `at://${DID}/${collection}/3aaaaaaaaaaaa`, cid: CID }]); + expect(deleteRequests(requests)).toHaveLength(1); + }); +}); + +describe("target validation", () => { + it("rejects a target of the wrong kind before sending anything", async () => { + const { context, requests } = fakeCollection(); + + await expect( + unfollowAccount(context, { targetDid: "alice.bsky.social" } as never), + ).rejects.toThrow(/^unfollowAccount: invalid input: must be an account DID/); + await expect(unfollowAccount(context, { targetDid: TARGET } as never)).rejects.toThrow(/DID/); + for (const run of [unfollowEntity, unlike, unrepost]) { + for (const targetUri of [ACCOUNT, `at://alice.bsky.social/a.b.c/d`, `at://${DID}/a.b.c`]) { + await expect(run(context, { targetUri })).rejects.toThrow(/must be a full record URI/); + } + } + + expect(requests).toHaveLength(0); + }); +}); diff --git a/packages/sdk/src/test-utils/fake-collection.ts b/packages/sdk/src/test-utils/fake-collection.ts new file mode 100644 index 0000000..610faa4 --- /dev/null +++ b/packages/sdk/src/test-utils/fake-collection.ts @@ -0,0 +1,107 @@ +import { type LexMap, lexParse } from "@atproto/lex"; +import { cidForLex } from "@atproto/lex-cbor"; +import { json } from "./fake-pds.js"; +import { type FakeRepoOptions, fakeRepo } from "./fake-repo.js"; + +/** A record the fake holds. `cid` defaults to the CID a PDS computes from `value`. */ +export interface StoredEntry { + rkey: string; + value: LexMap; + cid?: string; +} + +export interface FakeCollectionOptions extends FakeRepoOptions { + /** The records the repo holds, by collection, in the order `listRecords` returns them. */ + entries?: Record; + /** How many records one `listRecords` page holds at most. Default: as many as the request asks for. */ + pageSize?: number; +} + +/** One `deleteRecord` request the fake received. */ +export interface ReceivedDelete { + repo: string; + collection: string; + rkey: string; + swapRecord?: string | undefined; +} + +/** The query of one `listRecords` request the fake received. */ +export interface ReceivedList { + repo: string | null; + collection: string | null; + cursor: string | null; + limit: string | null; +} + +/** + * A fake repo that also lists and deletes records of the collections in `entries`: `listRecords` + * pages through them with a cursor, and `deleteRecord` removes a record, refusing with + * `InvalidSwap` when its `swapRecord` is not the record's CID. Everything else is `fakeRepo`'s. + * `listRecords` and `deleteRecord` in the options replace these answers, to simulate failures. + */ +export function fakeCollection(options: FakeCollectionOptions = {}) { + const { entries = {}, pageSize, ...repoOptions } = options; + const deletes: ReceivedDelete[] = []; + const lists: ReceivedList[] = []; + const repo = fakeRepo({ + ...repoOptions, + listRecords: + repoOptions.listRecords ?? + (async (request) => { + const query = new URL(request.path, "https://pds.test").searchParams; + const list = { + repo: query.get("repo"), + collection: query.get("collection"), + cursor: query.get("cursor"), + limit: query.get("limit"), + }; + lists.push(list); + return page(entries[list.collection ?? ""] ?? [], list, pageSize); + }), + deleteRecord: + repoOptions.deleteRecord ?? + (async (request) => { + const body = JSON.parse(new TextDecoder().decode(request.body)) as ReceivedDelete; + deletes.push(body); + return remove(entries[body.collection] ?? [], body); + }), + }); + return { ...repo, deletes, lists }; +} + +async function cidOf(entry: StoredEntry): Promise { + // As a PDS computes it, from the value as the client decodes it. + return entry.cid ?? (await cidForLex(lexParse(JSON.stringify(entry.value)))).toString(); +} + +async function page( + all: readonly StoredEntry[], + list: ReceivedList, + pageSize: number | undefined, +): Promise { + const start = list.cursor === null ? 0 : Number(list.cursor); + const size = Math.min(pageSize ?? Infinity, Number(list.limit ?? 50)); + const slice = all.slice(start, start + size); + const records = await Promise.all( + slice.map(async (entry) => ({ + uri: `at://${list.repo}/${list.collection}/${entry.rkey}`, + cid: await cidOf(entry), + value: entry.value, + })), + ); + const next = start + slice.length; + return json(200, { records, ...(next < all.length ? { cursor: String(next) } : {}) }); +} + +async function remove(entries: StoredEntry[], body: ReceivedDelete): Promise { + const index = entries.findIndex((entry) => entry.rkey === body.rkey); + const current = entries[index]; + if ( + body.swapRecord !== undefined && + (current === undefined || (await cidOf(current)) !== body.swapRecord) + ) { + return json(400, { error: "InvalidSwap", message: "Record CID did not match" }); + } + if (index >= 0) entries.splice(index, 1); + return json(200, {}); +} diff --git a/packages/sdk/src/test-utils/fake-repo.ts b/packages/sdk/src/test-utils/fake-repo.ts index 81299bb..530ce92 100644 --- a/packages/sdk/src/test-utils/fake-repo.ts +++ b/packages/sdk/src/test-utils/fake-repo.ts @@ -40,6 +40,10 @@ export interface FakeRepoOptions { putRecord?: (request: RecordedRequest) => Response; /** Replaces the fake's answer to `getLatestCommit`, to simulate failures. */ getLatestCommit?: (request: RecordedRequest) => Response; + /** Answers `listRecords`; without it the fake answers HTTP 404, as it does for any method it does not know. */ + listRecords?: (request: RecordedRequest) => Response | Promise; + /** Answers `deleteRecord`; without it the fake answers HTTP 404, as it does for any method it does not know. */ + deleteRecord?: (request: RecordedRequest) => Response | Promise; /** Replaces the fake's answer to `uploadBlob`, to simulate failures. */ uploadBlob?: (request: RecordedRequest) => Response; /** Replaces the fake's answer to `applyWrites`, to simulate failures. */ @@ -80,6 +84,12 @@ export function fakeRepo(options: FakeRepoOptions = {}) { if (path.endsWith("com.atproto.repo.applyWrites")) { return options.applyWrites?.(request) ?? applyWrites(request, received, state); } + if (path.endsWith("com.atproto.repo.listRecords") && options.listRecords) { + return options.listRecords(request); + } + if (path.endsWith("com.atproto.repo.deleteRecord") && options.deleteRecord) { + return options.deleteRecord(request); + } if (path.endsWith("com.atproto.repo.putRecord")) { return options.putRecord?.(request) ?? putRecord(request, puts, options.existing); } From 98c91d6505a6fa08ab313f41f057d79374854080 Mon Sep 17 00:00:00 2001 From: kzoeps Date: Tue, 10 Nov 2026 19:39:03 +0600 Subject: [PATCH 2/2] sdk/social: describe uploads and write errors in the short form Social operations upload nothing, so only the write-error @throws and the social reference are shortened to the form used on main after #17. --- .../hypercerts-org-sdk/references/social.md | 4 +-- packages/sdk/src/social/feed.ts | 32 ++++++++----------- packages/sdk/src/social/graph.ts | 32 ++++++++----------- 3 files changed, 30 insertions(+), 38 deletions(-) diff --git a/.agents/skills/hypercerts-org-sdk/references/social.md b/.agents/skills/hypercerts-org-sdk/references/social.md index 71004d2..91672c3 100644 --- a/.agents/skills/hypercerts-org-sdk/references/social.md +++ b/.agents/skills/hypercerts-org-sdk/references/social.md @@ -72,10 +72,10 @@ switch (result.status) { - The SDK lists **all** records of that collection in your own repo (every page, from your PDS, no indexer) and matches by subject: DID for follows, record URI for entity follows, likes and reposts. The CID a like or repost pinned is ignored, so a like of an older version of an edited record is found. - The target is **not** read, so a deleted or edited target does not stop you removing the like or follow. -- Exactly one match is deleted with a CID guard. If that record changed in between, the PDS refuses: `WriteRejectedError` with `code === "InvalidSwap"`, nothing deleted. The SDK never retries or deletes without the guard; call again to scan afresh. +- Exactly one match is deleted, only if it still has the CID the scan saw. If it changed in between, the call throws `WriteRejectedError` with `code === "InvalidSwap"` and nothing is deleted; call again to scan afresh. - A page that fails to load or looks wrong throws `Error`. It is never treated as "not found". - The scan is a snapshot. It cannot stop another writer creating a matching record meanwhile, so `deleted` does not promise that none remains. -- `WriteOutcomeUnknownError` from an undo: `attempted` is the record the SDK tried to delete. Calling the undo again is safe: it either deletes the record or returns `not-found`. +- `WriteOutcomeUnknownError` from an undo: `attempted` is the record the SDK tried to delete. Calling the undo again is safe: it either deletes the record or returns `not-found`. For create functions it is not safe to repeat; see [Handle failures](../SKILL.md#6-handle-failures). - The session needs permission to **delete** the collection (`app.certified.graph.follow`, `...graph.entityFollow`, `...feed.like`, `...feed.repost`) to undo, and to create it to create. ## Input fields diff --git a/packages/sdk/src/social/feed.ts b/packages/sdk/src/social/feed.ts index a75287c..417db08 100644 --- a/packages/sdk/src/social/feed.ts +++ b/packages/sdk/src/social/feed.ts @@ -36,10 +36,9 @@ const repostAction = recordRefAction({ create: "repost", undo: "unrepost" }, rep * `createdAt` the lexicon rejects. Nothing was written. * @throws {@link Error} If the client is not authenticated, or the target or the `via` record cannot * be read (missing, or the PDS cannot be reached). Nothing was written. - * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). Nothing was created. - * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the like - * may or may not exist. It carries the URI to check. The SDK does not retry, because a retry would - * create a second like with a new key if the first attempt had succeeded. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS. Calling again + * is not safe: it would create a second like if the first attempt had succeeded. * @throws {@link WriteResultMismatchError} If the PDS reported a different URI or CID than the SDK * computed. * @@ -93,11 +92,10 @@ export const like = createAction(likeAction); * @throws {@link Error} If the client is not authenticated, or the likes cannot be read in full (a * failed or malformed page). A partial read is never treated as "not found". Nothing was changed. * @throws {@link WriteRejectedError} If the PDS refused the deletion (HTTP 4xx). With `code` - * `"InvalidSwap"` the like changed after the scan, so it was not deleted; nothing is retried or - * deleted without that check, and calling again scans afresh. - * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the like - * may or may not be deleted. It carries the like's URI and CID. The SDK does not retry; calling - * again is safe and either deletes the like or returns `not-found`. + * `"InvalidSwap"` the like changed after the scan, so it was not deleted; call again to scan + * afresh. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS. Calling again + * is safe: it either deletes the like or returns `not-found`. * * @example * ```ts @@ -141,10 +139,9 @@ export const unlike = undoAction(likeAction); * `createdAt` the lexicon rejects. Nothing was written. * @throws {@link Error} If the client is not authenticated, or the target or the `via` record cannot * be read (missing, or the PDS cannot be reached). Nothing was written. - * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). Nothing was created. - * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the - * repost may or may not exist. It carries the URI to check. The SDK does not retry, because a retry - * would create a second repost with a new key if the first attempt had succeeded. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS. Calling again + * is not safe: it would create a second repost if the first attempt had succeeded. * @throws {@link WriteResultMismatchError} If the PDS reported a different URI or CID than the SDK * computed. * @@ -199,11 +196,10 @@ export const repost = createAction(repostAction); * @throws {@link Error} If the client is not authenticated, or the reposts cannot be read in full (a * failed or malformed page). A partial read is never treated as "not found". Nothing was changed. * @throws {@link WriteRejectedError} If the PDS refused the deletion (HTTP 4xx). With `code` - * `"InvalidSwap"` the repost changed after the scan, so it was not deleted; nothing is retried or - * deleted without that check, and calling again scans afresh. - * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the repost - * may or may not be deleted. It carries the repost's URI and CID. The SDK does not retry; calling - * again is safe and either deletes the repost or returns `not-found`. + * `"InvalidSwap"` the repost changed after the scan, so it was not deleted; call again to scan + * afresh. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS. Calling again + * is safe: it either deletes the repost or returns `not-found`. * * @example * ```ts diff --git a/packages/sdk/src/social/graph.ts b/packages/sdk/src/social/graph.ts index 0d0f244..57fccf8 100644 --- a/packages/sdk/src/social/graph.ts +++ b/packages/sdk/src/social/graph.ts @@ -63,10 +63,9 @@ const followEntityAction: SocialAction = { * @throws {@link Error} If the client is not authenticated, or the `via` record cannot be read. * Nothing was written. * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx), for example because - * the session may not create `app.certified.graph.follow` records. Nothing was created. - * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the - * record may or may not exist. It carries the URI to check. The SDK does not retry, because a retry - * would create a second follow with a new key if the first attempt had succeeded. + * the session may not create `app.certified.graph.follow` records. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS. Calling again + * is not safe: it would create a second follow if the first attempt had succeeded. * @throws {@link WriteResultMismatchError} If the PDS reported a different URI or CID than the SDK * computed. * @@ -128,11 +127,10 @@ export const followAccount = createAction(followAccountAction); * full (a failed or malformed page). A partial read is never treated as "not found". Nothing was * changed. * @throws {@link WriteRejectedError} If the PDS refused the deletion (HTTP 4xx). With `code` - * `"InvalidSwap"` the record changed after the scan, so it was not deleted; nothing is retried or - * deleted without that check, and calling again scans afresh. - * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the record - * may or may not be deleted. It carries the record's URI and CID. The SDK does not retry; calling - * again is safe and either deletes the record or returns `not-found`. + * `"InvalidSwap"` the record changed after the scan, so it was not deleted; call again to scan + * afresh. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS. Calling again + * is safe: it either deletes the record or returns `not-found`. * * @example * ```ts @@ -177,10 +175,9 @@ export const unfollowAccount = undoAction(followAccountAction); * `createdAt` the lexicon rejects. Nothing was written. * @throws {@link Error} If the client is not authenticated, or the `via` record cannot be read. * Nothing was written. - * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). Nothing was created. - * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the - * record may or may not exist. It carries the URI to check. The SDK does not retry, because a retry - * would create a second follow with a new key if the first attempt had succeeded. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS. Calling again + * is not safe: it would create a second follow if the first attempt had succeeded. * @throws {@link WriteResultMismatchError} If the PDS reported a different URI or CID than the SDK * computed. * @@ -232,11 +229,10 @@ export const followEntity = createAction(followEntityAction); * full (a failed or malformed page). A partial read is never treated as "not found". Nothing was * changed. * @throws {@link WriteRejectedError} If the PDS refused the deletion (HTTP 4xx). With `code` - * `"InvalidSwap"` the record changed after the scan, so it was not deleted; nothing is retried or - * deleted without that check, and calling again scans afresh. - * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the record - * may or may not be deleted. It carries the record's URI and CID. The SDK does not retry; calling - * again is safe and either deletes the record or returns `not-found`. + * `"InvalidSwap"` the record changed after the scan, so it was not deleted; call again to scan + * afresh. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS. Calling again + * is safe: it either deletes the record or returns `not-found`. * * @example * ```ts