techne-sdk 0.3.3 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +160 -0
  2. package/README.md +5 -4
  3. package/dist/auth/app-key.js +2 -2
  4. package/dist/auth/index.js +1 -1
  5. package/dist/catalog/catalog.gen.d.ts +24 -24
  6. package/dist/catalog/catalog.gen.js +356 -66
  7. package/dist/connect.d.ts +96 -12
  8. package/dist/connect.js +83 -12
  9. package/dist/generated/lexicons.d.ts +140 -36
  10. package/dist/generated/lexicons.js +77 -18
  11. package/dist/generated/nsid.d.ts +4 -0
  12. package/dist/generated/nsid.js +4 -0
  13. package/dist/generated/nsid.json +4 -0
  14. package/dist/generated/types/pub/techne/draft/beacon.d.ts +2 -0
  15. package/dist/generated/types/pub/techne/draft/collective.d.ts +1 -1
  16. package/dist/generated/types/pub/techne/draft/identity/attest.d.ts +3 -0
  17. package/dist/generated/types/pub/techne/draft/identity/attest.js +7 -0
  18. package/dist/generated/types/pub/techne/draft/identity/beginAddMethod.d.ts +3 -0
  19. package/dist/generated/types/pub/techne/draft/identity/beginAddMethod.js +7 -0
  20. package/dist/generated/types/pub/techne/draft/identity/finishAddMethod.d.ts +6 -0
  21. package/dist/generated/types/pub/techne/draft/identity/finishAddMethod.js +14 -0
  22. package/dist/generated/types/pub/techne/draft/identity/resolve.d.ts +6 -0
  23. package/dist/generated/types/pub/techne/draft/membership.d.ts +1 -1
  24. package/dist/generated/types/pub/techne/draft/permissioned/deleteRecord.d.ts +3 -0
  25. package/dist/generated/types/pub/techne/draft/permissioned/deleteRecord.js +7 -0
  26. package/dist/generated/types/pub/techne/draft/permissioned/putRecord.d.ts +3 -0
  27. package/dist/generated/types/pub/techne/draft/permissioned/putRecord.js +7 -0
  28. package/dist/generated/types/pub/techne/draft/permissioned/putRecords.d.ts +4 -1
  29. package/dist/generated/types/pub/techne/draft/permissioned/putRecords.js +7 -0
  30. package/dist/generated/types/pub/techne/draft/summary.d.ts +2 -0
  31. package/dist/item.d.ts +130 -0
  32. package/dist/item.js +74 -0
  33. package/dist/links/index.d.ts +15 -8
  34. package/dist/links/index.js +18 -0
  35. package/dist/put/contacts.d.ts +2 -2
  36. package/dist/put/index.d.ts +6 -9
  37. package/dist/put/index.js +8 -166
  38. package/dist/put/put.d.ts +14 -0
  39. package/dist/put/put.js +206 -0
  40. package/dist/query/compose.d.ts +246 -0
  41. package/dist/query/compose.js +572 -0
  42. package/dist/query/hosts.d.ts +98 -1
  43. package/dist/query/hosts.js +143 -2
  44. package/dist/query/index.d.ts +60 -29
  45. package/dist/query/index.js +55 -26
  46. package/dist/react/context.d.ts +18 -0
  47. package/dist/react/context.js +19 -0
  48. package/dist/react/index.d.ts +14 -0
  49. package/dist/react/index.js +14 -0
  50. package/dist/react/query.d.ts +75 -0
  51. package/dist/react/query.js +116 -0
  52. package/dist/read/index.d.ts +60 -0
  53. package/dist/read/index.js +107 -0
  54. package/dist/resend.d.ts +25 -0
  55. package/dist/resend.js +52 -0
  56. package/dist/versions/entities.gen.d.ts +8 -0
  57. package/dist/versions/entities.gen.js +9 -0
  58. package/dist/versions/index.d.ts +59 -17
  59. package/dist/versions/index.js +156 -22
  60. package/dist/versions/react.d.ts +1 -1
  61. package/dist/versions/react.js +1 -1
  62. package/dist/versions/text.d.ts +19 -0
  63. package/dist/versions/text.js +73 -0
  64. package/dist/wasm/techne-wasm.gen.js +1 -1
  65. package/dist/wasm/techne-wasm2js.gen.js +8928 -8927
  66. package/package.json +17 -5
@@ -32,6 +32,9 @@ export declare class InvalidRequestError extends XRPCError {
32
32
  export declare class ForbiddenError extends XRPCError {
33
33
  constructor(src: XRPCError);
34
34
  }
35
+ export declare class LastManagerError extends XRPCError {
36
+ constructor(src: XRPCError);
37
+ }
35
38
  export declare class AccountDeletingError extends XRPCError {
36
39
  constructor(src: XRPCError);
37
40
  }
@@ -76,7 +79,7 @@ export declare function validateWriteResult<V>(v: V): ValidationResult<WriteResu
76
79
  /** A write refused, and nothing of it written: the error putRecord would have answered. */
77
80
  export interface WriteError {
78
81
  $type?: 'pub.techne.draft.permissioned.putRecords#writeError';
79
- /** InvalidRequest (malformed, a body that fails its collection's published lexicon, or a record over 2 MiB, more than a putRecord body may be), InvalidSwap (swapCid did not match the current version), Conflict (the same key holds a public record in the caller's repo, or a concurrent write replaced this version before it was recorded), IdentityConflict (the write would change a contact's identity, which writing again never fixes; see putRecord) or DuplicatePhone (a contact write introduces a number another of the caller's active contacts carries; see putRecord). */
82
+ /** InvalidRequest (malformed, a body that fails its collection's published lexicon, or a record over 2 MiB, more than a putRecord body may be), InvalidSwap (swapCid did not match the current version), Conflict (the same key holds a public record in the caller's repo, or a concurrent write replaced this version before it was recorded), IdentityConflict (the write would change a contact's identity, which writing again never fixes; see putRecord), DuplicatePhone (a contact write introduces a number another of the caller's active contacts carries; see putRecord) or Forbidden (the call's `space:` scopes do not cover the write, or it replaces a record already written for an app's space and the caller is neither the app its key names nor holds `space:` scopes covering it; see putRecord). */
80
83
  error: 'InvalidRequest' | 'InvalidSwap' | 'Conflict' | 'IdentityConflict' | 'DuplicatePhone' | (string & {});
81
84
  message: string;
82
85
  }
@@ -16,6 +16,11 @@ export class ForbiddenError extends XRPCError {
16
16
  super(src.status, src.error, src.message, src.headers, { cause: src });
17
17
  }
18
18
  }
19
+ export class LastManagerError extends XRPCError {
20
+ constructor(src) {
21
+ super(src.status, src.error, src.message, src.headers, { cause: src });
22
+ }
23
+ }
19
24
  export class AccountDeletingError extends XRPCError {
20
25
  constructor(src) {
21
26
  super(src.status, src.error, src.message, src.headers, { cause: src });
@@ -37,6 +42,8 @@ export function toKnownErr(e) {
37
42
  return new InvalidRequestError(e);
38
43
  if (e.error === 'Forbidden')
39
44
  return new ForbiddenError(e);
45
+ if (e.error === 'LastManager')
46
+ return new LastManagerError(e);
40
47
  if (e.error === 'AccountDeleting')
41
48
  return new AccountDeletingError(e);
42
49
  if (e.error === 'AuthenticationRequired')
@@ -8,6 +8,8 @@ export interface Main {
8
8
  subject: ComAtprotoRepoStrongRef.Main;
9
9
  /** The line, as plain text. */
10
10
  text: string;
11
+ /** Optional: one emoji for the record (a card mark and map pin glyph). A single emoji, no flags; readers fall back to their own when absent. */
12
+ emoji?: string;
11
13
  createdAt: string;
12
14
  [k: string]: unknown;
13
15
  }
package/dist/item.d.ts ADDED
@@ -0,0 +1,130 @@
1
+ /**
2
+ * The SDK's items (internal; their types reach apps through `techne-sdk/connect` and `techne-sdk/react`):
3
+ * the one shape every read answers (`Item<T>`), typed URIs, and the check that
4
+ * gives each item its verdict.
5
+ *
6
+ * An item is `{ uri, cid, record, verdict, problems, curated, byline }`:
7
+ *
8
+ * - `uri` is typed (`Uri<Place>`), so a hook handed `item.uri` comes back typed. A bare string is no
9
+ * `Uri<Place>` (only an item, or `Place.uri(s)`, makes one); a read taking a bare string answers
10
+ * `unknown` records.
11
+ * - `record` is a `T` only when the record passed the lexicon check: a `valid` or `pending` item (pending
12
+ * comes after the lexicon check, `techne-lexicon-check::decide`). An `invalid` one's record is `unknown`.
13
+ * A read with `include: 'valid'` (the default) answers {@link ValidItem}s; `include: 'all'` the union.
14
+ * - `verdict` is the SDK's own answer for the record (`valid`, `pending` or `invalid`), from the pure
15
+ * check run here as WebAssembly (`decide`). techne.computer has already left out what privacy and
16
+ * safety require (spaces the caller may not read, admission, hidden accounts and moderation) before
17
+ * anything comes back, so the check never sees those: `include: 'all'` adds pending and invalid
18
+ * records the platform answered, never blocked or hidden ones.
19
+ * - `problems` says why: the check's reasons for an invalid record, one plain sentence for a pending one
20
+ * (what it is waiting for), empty for a valid one.
21
+ * - `curated`: the record is a live curated record (the commons' composition of several versions).
22
+ * - `byline`: for a curated record, whose version speaks first and whose version each field came from
23
+ * (the provenance composition). `null` otherwise. Items never carry the versions themselves: that is
24
+ * `techne.versions(uri)`.
25
+ *
26
+ * `cid` is there so an item can be pointed at (a strongRef needs it).
27
+ */
28
+ import { type Claims } from './wasm/index.js';
29
+ declare const uriOf: unique symbol;
30
+ declare const recordOf: unique symbol;
31
+ /** An AT-URI whose record is a `T`. Only an item's `uri` or a type's `uri(s)` makes one: a bare string is
32
+ * not one (a read that takes a bare string answers `unknown`). */
33
+ export type Uri<T = unknown> = string & {
34
+ readonly [uriOf]: T;
35
+ };
36
+ /** The record type a typed URI names (`unknown` for a bare string). */
37
+ export type RecordOfUri<U> = U extends Uri<infer T> ? T : unknown;
38
+ /** Marks a query document with the record type it answers; `Place.query(…)` makes one. */
39
+ export interface Typed<T> {
40
+ readonly [recordOf]?: T;
41
+ }
42
+ /** The record type a typed query answers (`unknown` for an untyped one). */
43
+ export type RecordOfQuery<Q> = Q extends Typed<infer T> ? T : unknown;
44
+ export type Verdict = 'valid' | 'pending' | 'invalid';
45
+ /** Which items a read answers: `valid` (the default) or `all` (adds pending and invalid ones, with their
46
+ * problems). Neither ever adds what techne.computer left out (blocked, hidden, unadmitted). */
47
+ export type Include = 'valid' | 'all';
48
+ /** One version a byline names: its URI and its author. */
49
+ export interface BylineRef {
50
+ uri: string;
51
+ author: string;
52
+ }
53
+ /** Whose version a curated record's fields came from (its provenance composition). */
54
+ export interface Byline extends BylineRef {
55
+ /** Each top-level field the composition names, and the version it came from. */
56
+ fields: Record<string, BylineRef>;
57
+ }
58
+ /** What every item carries, whatever its verdict. */
59
+ interface ItemBase<T> {
60
+ uri: Uri<T>;
61
+ cid: string;
62
+ /** Why it is not valid: the check's reasons when invalid, what it waits for when pending. */
63
+ problems: string[];
64
+ /** A live curated record (the commons composed it from versions). */
65
+ curated: boolean;
66
+ /** For a curated record: whose version speaks first, and each field's source. `null` otherwise. */
67
+ byline: Byline | null;
68
+ }
69
+ /** A valid item: its record passed every check. */
70
+ export interface ValidItem<T = unknown> extends ItemBase<T> {
71
+ verdict: 'valid';
72
+ record: T;
73
+ }
74
+ /** A pending item: its record passed the lexicon check and waits for a claim (or the reach limit). */
75
+ export interface PendingItem<T = unknown> extends ItemBase<T> {
76
+ verdict: 'pending';
77
+ record: T;
78
+ }
79
+ /** An invalid item: its record may not even be a `T` (`problems` says why). */
80
+ export interface InvalidItem<T = unknown> extends ItemBase<T> {
81
+ verdict: 'invalid';
82
+ record: unknown;
83
+ }
84
+ /** One record as every read answers it, told apart by `verdict`. */
85
+ export type Item<T = unknown> = ValidItem<T> | PendingItem<T> | InvalidItem<T>;
86
+ /** What a read's options ask for: `'all'` when they may ask for every item (`include: 'all'`, or an
87
+ * `include` not known until run time), else `'valid'`. */
88
+ export type IncludeOf<O> = O extends {
89
+ include?: infer I;
90
+ } ? ([Exclude<I, undefined>] extends ['valid'] ? 'valid' : unknown extends I ? 'valid' : 'all') : 'valid';
91
+ /** The item a read answers for `include` `I`: a {@link ValidItem} by default, any {@link Item} for `all`. */
92
+ export type ItemFor<T, I extends Include> = I extends 'all' ? Item<T> : ValidItem<T>;
93
+ /** The problem a pending record held by the reach limit carries. */
94
+ export declare const HELD = "held: the reach limit holds this back from the people it would reach until it admits it";
95
+ /** The problem a pending record waiting for a claim carries. */
96
+ export declare const AWAITING_CLAIM = "pending: a claim it needs has not been seen yet (an admission, a membership or a vouch)";
97
+ /** The author DID of an AT-URI (`''` when it is not one). */
98
+ export declare const authorOf: (uri: string) => string;
99
+ /** The collection of an AT-URI (`''` when it is not one). */
100
+ export declare const collectionOf: (uri: string) => string;
101
+ /** The parts of one record the check reads. */
102
+ export interface Checked {
103
+ uri: string;
104
+ collection: string;
105
+ author: string;
106
+ value: unknown;
107
+ /** The space a permissioned record counts in. */
108
+ space?: string;
109
+ /** When the platform first saw it (its indexed time), RFC 3339. */
110
+ time?: string;
111
+ /** The platform answered it as held back by the reach limit (its author's own share). */
112
+ held?: boolean;
113
+ }
114
+ /**
115
+ * The verdict for one record the platform answered, over the claims the app holds. A permissioned record
116
+ * the platform answered passed its space's write policy there (the platform applies admission before
117
+ * anything comes back), so that admission is taken as given here; anything else the check needs and the
118
+ * app does not hold (a membership, a vouch) leaves the record pending.
119
+ */
120
+ export declare function check(r: Checked, claims?: Claims): {
121
+ verdict: Verdict;
122
+ problems: string[];
123
+ };
124
+ /** The byline of a curated record from its provenance `composition` (`null` when it has none). */
125
+ export declare function bylineOf(composition: unknown): Byline | null;
126
+ /** Whether `include` keeps `item`. */
127
+ export declare const keeps: <T, I extends Include>(item: Item<T>, include: I | undefined) => item is ItemFor<T, I>;
128
+ /** Keep the items `include` asks for. */
129
+ export declare function included<T, I extends Include = 'valid'>(items: Item<T>[], include?: I): ItemFor<T, I>[];
130
+ export {};
package/dist/item.js ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The SDK's items (internal; their types reach apps through `techne-sdk/connect` and `techne-sdk/react`):
3
+ * the one shape every read answers (`Item<T>`), typed URIs, and the check that
4
+ * gives each item its verdict.
5
+ *
6
+ * An item is `{ uri, cid, record, verdict, problems, curated, byline }`:
7
+ *
8
+ * - `uri` is typed (`Uri<Place>`), so a hook handed `item.uri` comes back typed. A bare string is no
9
+ * `Uri<Place>` (only an item, or `Place.uri(s)`, makes one); a read taking a bare string answers
10
+ * `unknown` records.
11
+ * - `record` is a `T` only when the record passed the lexicon check: a `valid` or `pending` item (pending
12
+ * comes after the lexicon check, `techne-lexicon-check::decide`). An `invalid` one's record is `unknown`.
13
+ * A read with `include: 'valid'` (the default) answers {@link ValidItem}s; `include: 'all'` the union.
14
+ * - `verdict` is the SDK's own answer for the record (`valid`, `pending` or `invalid`), from the pure
15
+ * check run here as WebAssembly (`decide`). techne.computer has already left out what privacy and
16
+ * safety require (spaces the caller may not read, admission, hidden accounts and moderation) before
17
+ * anything comes back, so the check never sees those: `include: 'all'` adds pending and invalid
18
+ * records the platform answered, never blocked or hidden ones.
19
+ * - `problems` says why: the check's reasons for an invalid record, one plain sentence for a pending one
20
+ * (what it is waiting for), empty for a valid one.
21
+ * - `curated`: the record is a live curated record (the commons' composition of several versions).
22
+ * - `byline`: for a curated record, whose version speaks first and whose version each field came from
23
+ * (the provenance composition). `null` otherwise. Items never carry the versions themselves: that is
24
+ * `techne.versions(uri)`.
25
+ *
26
+ * `cid` is there so an item can be pointed at (a strongRef needs it).
27
+ */
28
+ import { decide } from './wasm/index.js';
29
+ /** The problem a pending record held by the reach limit carries. */
30
+ export const HELD = 'held: the reach limit holds this back from the people it would reach until it admits it';
31
+ /** The problem a pending record waiting for a claim carries. */
32
+ export const AWAITING_CLAIM = 'pending: a claim it needs has not been seen yet (an admission, a membership or a vouch)';
33
+ /** The author DID of an AT-URI (`''` when it is not one). */
34
+ export const authorOf = (uri) => (uri.startsWith('at://') ? (uri.slice(5).split('/')[0] ?? '') : '');
35
+ /** The collection of an AT-URI (`''` when it is not one). */
36
+ export const collectionOf = (uri) => (uri.startsWith('at://') ? (uri.slice(5).split('/')[1] ?? '') : '');
37
+ /**
38
+ * The verdict for one record the platform answered, over the claims the app holds. A permissioned record
39
+ * the platform answered passed its space's write policy there (the platform applies admission before
40
+ * anything comes back), so that admission is taken as given here; anything else the check needs and the
41
+ * app does not hold (a membership, a vouch) leaves the record pending.
42
+ */
43
+ export function check(r, claims = {}) {
44
+ const rkey = r.uri.split('/')[4] ?? '';
45
+ const admissions = r.space ? [...(claims.admissions ?? []), { author: r.author, space: r.space, admitted: true }] : claims.admissions;
46
+ const d = decide({ collection: r.collection, author: r.author, rkey, body: r.value, space: r.space, firstSeen: r.time }, { ...claims, admissions });
47
+ if (d.decision === 'invalid')
48
+ return { verdict: 'invalid', problems: d.reason.split('; ') };
49
+ if (r.held)
50
+ return { verdict: 'pending', problems: [HELD] };
51
+ if (d.decision === 'pending')
52
+ return { verdict: 'pending', problems: [AWAITING_CLAIM] };
53
+ return { verdict: 'valid', problems: [] };
54
+ }
55
+ /** The byline of a curated record from its provenance `composition` (`null` when it has none). */
56
+ export function bylineOf(composition) {
57
+ if (!composition || typeof composition !== 'object')
58
+ return null;
59
+ const { byline, fields } = composition;
60
+ if (typeof byline !== 'string')
61
+ return null;
62
+ const out = { uri: byline, author: authorOf(byline), fields: {} };
63
+ for (const f of Array.isArray(fields) ? fields : []) {
64
+ if (f && typeof f.field === 'string' && typeof f.from === 'string')
65
+ out.fields[f.field] = { uri: f.from, author: authorOf(f.from) };
66
+ }
67
+ return out;
68
+ }
69
+ /** Whether `include` keeps `item`. */
70
+ export const keeps = (item, include) => include === 'all' || item.verdict === 'valid';
71
+ /** Keep the items `include` asks for. */
72
+ export function included(items, include) {
73
+ return items.filter((i) => keeps(i, include));
74
+ }
@@ -1,4 +1,4 @@
1
- import type { Techne } from '../connect.js';
1
+ import type { Clients } from '../connect.js';
2
2
  import type * as Defs from '../generated/types/pub/techne/draft/identity/defs.js';
3
3
  import type * as Create from '../generated/types/pub/techne/draft/identity/createLinkToken.js';
4
4
  import type * as Redeem from '../generated/types/pub/techne/draft/identity/redeemLinkToken.js';
@@ -23,6 +23,13 @@ export declare class OwnLinkError extends Error {
23
23
  cause?: unknown;
24
24
  });
25
25
  }
26
+ /** The user's PDS refused the call: the session's scopes do not name it (a Sign in with Techne session;
27
+ * see the module doc). `cause` is the PDS's answer. */
28
+ export declare class LinkScopeError extends Error {
29
+ constructor(options?: {
30
+ cause?: unknown;
31
+ });
32
+ }
26
33
  /** What a link is for: the app (a label of the caller's) and its target (a URI with a scheme). */
27
34
  export interface LinkFor {
28
35
  app: string;
@@ -31,7 +38,7 @@ export interface LinkFor {
31
38
  /** A new link: the token to put in the URL, and its view (`link.id` is its id). */
32
39
  export type NewLink = Create.OutputSchema;
33
40
  /** A new link for `app` and `target`: one-time unless `reusable`, live until `expiresAt` if given. */
34
- export declare function createLink(techne: Techne, input: LinkFor & {
41
+ export declare function createLink(techne: Clients, input: LinkFor & {
35
42
  reusable?: boolean;
36
43
  expiresAt?: Date | string;
37
44
  grant?: LinkGrant;
@@ -41,25 +48,25 @@ export declare function createLink(techne: Techne, input: LinkFor & {
41
48
  * `grant` it carries over the newest unrevoked grant of a reusable link for the same app and target (a
42
49
  * one-time link's grant is never carried); with neither, the new link has no grant.
43
50
  */
44
- export declare function resetLink(techne: Techne, input: LinkFor & {
51
+ export declare function resetLink(techne: Clients, input: LinkFor & {
45
52
  grant?: LinkGrant;
46
53
  }): Promise<Reset.OutputSchema>;
47
54
  /** Revoke one of the caller's links; `false` when they have no link with this id or it was already revoked. */
48
- export declare function revokeLink(techne: Techne, id: string): Promise<boolean>;
55
+ export declare function revokeLink(techne: Clients, id: string): Promise<boolean>;
49
56
  /** The caller's live links for `app` and `target`, in no promised order. */
50
- export declare function listLinks(techne: Techne, input: LinkFor): Promise<LinkTokenListed[]>;
57
+ export declare function listLinks(techne: Clients, input: LinkFor): Promise<LinkTokenListed[]>;
51
58
  /** Who redeemed one of the caller's links, and when (empty for a link that is not theirs). */
52
- export declare function linkRedemptions(techne: Techne, id: string): Promise<LinkRedemption[]>;
59
+ export declare function linkRedemptions(techne: Clients, id: string): Promise<LinkRedemption[]>;
53
60
  /**
54
61
  * Redeem `token` as the signed-in user. Throws {@link LinkNotUsableError} for a link that no longer
55
62
  * works and {@link OwnLinkError} for the caller's own; a repeat by the same account answers `repeat`.
56
63
  */
57
- export declare function redeemLink(techne: Techne, token: string): Promise<Redemption>;
64
+ export declare function redeemLink(techne: Clients, token: string): Promise<Redemption>;
58
65
  /** What a live token is for: the lexicon's answer with every field a live one carries. */
59
66
  export type LiveLink = Required<Pick<Check.OutputSchema, 'id' | 'app' | 'target' | 'owner' | 'reusable'>> & Pick<Check.OutputSchema, 'expiresAt'> & {
60
67
  live: true;
61
68
  };
62
69
  /** Whether `token` is live, and if so what it is for; a dead or unknown one says nothing more. */
63
- export declare function checkLink(techne: Techne, token: string): Promise<LiveLink | {
70
+ export declare function checkLink(techne: Clients, token: string): Promise<LiveLink | {
64
71
  live: false;
65
72
  }>;
@@ -21,6 +21,13 @@
21
21
  * Every call goes to the platform through the user's PDS (`techne.platform`, `atproto-proxy`), like
22
22
  * `put`; the platform relays it to the identity PDS. An account not on the identity PDS gets
23
23
  * `NotSupported`.
24
+ *
25
+ * Which session. The calls are `pub.techne.draft.identity.*` methods, and no published permission set
26
+ * names them (`authRead` and `authWrite` are the commons reads and writes), so a Sign in with Techne
27
+ * session (`connect` over the app's own OAuth session, asking for the default `scopes()`) is refused by
28
+ * its PDS for every one: they throw {@link LinkScopeError}. Links need a platform session
29
+ * (`connectHosted`), or an app that asks for those methods' `rpc:` scopes itself (with the platform's
30
+ * appview as their `aud`) beside the default ones.
24
31
  */
25
32
  import { XRPCError } from '@atproto/xrpc';
26
33
  /** The message every unusable link answers with (unknown, used, revoked or expired alike). */
@@ -39,12 +46,23 @@ export class OwnLinkError extends Error {
39
46
  this.name = 'OwnLinkError';
40
47
  }
41
48
  }
49
+ /** The user's PDS refused the call: the session's scopes do not name it (a Sign in with Techne session;
50
+ * see the module doc). `cause` is the PDS's answer. */
51
+ export class LinkScopeError extends Error {
52
+ constructor(options) {
53
+ super("techne-sdk/links: the session's scopes do not cover link tokens (no permission set names the identity methods): use a platform session (connectHosted), or ask for their rpc: scopes yourself", options);
54
+ this.name = 'LinkScopeError';
55
+ }
56
+ }
42
57
  function mapped(e) {
43
58
  if (e instanceof XRPCError) {
44
59
  if (e.error === 'LinkNotUsable')
45
60
  return new LinkNotUsableError({ cause: e });
46
61
  if (e.error === 'OwnLink')
47
62
  return new OwnLinkError({ cause: e });
63
+ // What a PDS answers for a call its OAuth session has no scope for (`@atproto/oauth-scopes` ScopeMissingError).
64
+ if (e.status === 403 && /^Missing required scope "rpc:/.test(e.message))
65
+ return new LinkScopeError({ cause: e });
48
66
  }
49
67
  return e;
50
68
  }
@@ -1,4 +1,4 @@
1
- import type { Techne } from '../connect.js';
1
+ import type { Clients } from '../connect.js';
2
2
  type Raw = {
3
3
  [k: string]: unknown;
4
4
  };
@@ -25,5 +25,5 @@ export declare function contactConflicts(stored: StoredContact[], writes: {
25
25
  record: object;
26
26
  }[]): ContactConflict[];
27
27
  /** Every contact the owner has, through the platform's private read (one page after another). */
28
- export declare function storedContacts(techne: Techne): Promise<StoredContact[]>;
28
+ export declare function storedContacts(techne: Clients): Promise<StoredContact[]>;
29
29
  export {};
@@ -3,9 +3,9 @@ import type * as CalendarEvent from '../generated/types/community/lexicon/calend
3
3
  import type * as EventConfig from '../generated/types/pub/techne/draft/event/config.js';
4
4
  import type * as EventDetail from '../generated/types/pub/techne/draft/event/detail.js';
5
5
  import type { OmitKey } from '../generated/util.js';
6
- import type { Techne } from '../connect.js';
7
6
  import { type Decision } from '../wasm/index.js';
8
- import { type Curation } from '../query/index.js';
7
+ import type { Curation } from '../query/index.js';
8
+ export { put, type PutOptions } from './put.js';
9
9
  export { contactConflicts, ContactConflictError, type ContactConflict, type StoredContact } from './contacts.js';
10
10
  export type { Records, AnyRecord, Decision, Curation };
11
11
  /** One record to put: the body (its `$type` is its collection), and its key or space if it has them. */
@@ -122,17 +122,14 @@ export declare class PutError extends Error {
122
122
  message: string;
123
123
  }[]);
124
124
  }
125
- /** The plan for `records` into `repo` (Rust, `techne_sdk::put::plan`). */
126
- export declare function plan(repo: string, records: PutRecord[], now?: Date): Write[];
125
+ /** The plan for `records` into `repo` (Rust, `techne_sdk::put::plan`) as of `now`: a `Date`, or unix
126
+ * seconds (the platform SDK's form); this machine's clock by default. */
127
+ export declare function plan(repo: string, records: PutRecord[], now?: Date | number): Write[];
127
128
  /** The plan for `records` and `deletes` into `repo` (Rust, `techne_sdk::put::plan_with_deletes`). */
128
- export declare function planWithDeletes(repo: string, records: PutRecord[], deletes: DeleteRecord[], now?: Date): {
129
+ export declare function planWithDeletes(repo: string, records: PutRecord[], deletes: DeleteRecord[], now?: Date | number): {
129
130
  writes: Write[];
130
131
  deletes: Delete[];
131
132
  };
132
- export declare function put(techne: Techne, records: PutRecord[], options?: {
133
- wait?: number;
134
- deletes?: DeleteRecord[];
135
- }): Promise<PutResult>;
136
133
  type EventFields = OmitKey<CalendarEvent.Record, '$type'>;
137
134
  type ConfigFields = OmitKey<EventConfig.Record, '$type' | 'event' | 'createdAt'>;
138
135
  type DetailFields = OmitKey<EventDetail.Record, '$type' | 'event' | 'createdAt'>;
package/dist/put/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  /**
2
- * techne-sdk/put — the SDK's one write (techne P13.2): `put(techne, records)`.
2
+ * techne-sdk/put — the SDK's one write (techne P13.2): `put(techne, records)`, also the client's
3
+ * `techne.put(records)` on what `connect` returns.
3
4
  *
4
5
  * An app writes records, typed from the lexicons, and nothing refuses a write. `put`:
5
6
  *
@@ -40,7 +41,8 @@
40
41
  * private deletes. Send the same records again: the keys are deterministic,
41
42
  * a private record written again is a no-op, a public record already at its CID is not rewritten, and a
42
43
  * record already gone is not deleted again.
43
- * Until every record has landed, show the thing as pending.
44
+ * Until every record has landed, show the thing as pending. `put` does that once itself when a call got
45
+ * no answer at all (the connection was lost before any response): it runs again from the start.
44
46
  *
45
47
  * Before writing a `contact`, `put` asks whether the write would change who the contact is (its
46
48
  * number, its account; `./contacts`): the platform no longer refuses that, so the SDK does, and throws
@@ -60,17 +62,10 @@
60
62
  * Builders exist only for writes that compose several records ({@link eventRecords}); any other record
61
63
  * is put as it is.
62
64
  */
63
- import { XRPCError } from '@atproto/xrpc';
64
65
  import { NSID } from '../generated/nsid.js';
65
66
  import { call } from '../wasm/index.js';
66
- import { contactConflicts, ContactConflictError, storedContacts } from './contacts.js';
67
- import { getRecordsAnswer } from '../query/index.js';
67
+ export { put } from './put.js';
68
68
  export { contactConflicts, ContactConflictError } from './contacts.js';
69
- /** Why a private record with no space is not written (lucian 2026-11-09): the platform's private write
70
- * needs a space, as `permissioned.putRecords` refuses a write that names none. */
71
- function noSpace(did, collection) {
72
- return `names no space. ${collection} is written privately, so name the space it is for: a record only you read goes in your own space.personal (at://${did}/${NSID.SPACE_PERSONAL}/self). Public records are written with com.atproto.repo.putRecord.`;
73
- }
74
69
  /** A put whose private batch write refused some records: nothing public was written. */
75
70
  export class PutError extends Error {
76
71
  refused;
@@ -79,173 +74,20 @@ export class PutError extends Error {
79
74
  this.refused = refused;
80
75
  }
81
76
  }
82
- /** The plan for `records` into `repo` (Rust, `techne_sdk::put::plan`). */
77
+ /** The plan for `records` into `repo` (Rust, `techne_sdk::put::plan`) as of `now`: a `Date`, or unix
78
+ * seconds (the platform SDK's form); this machine's clock by default. */
83
79
  export function plan(repo, records, now = new Date()) {
84
80
  return call('put', { repo, records, now: unixSeconds(now) });
85
81
  }
86
82
  /** The clock the plan reads (an old name has a lexicon only while its rename is honoured); the
87
83
  * WebAssembly has none of its own. */
88
84
  function unixSeconds(now) {
89
- return Math.floor(now.getTime() / 1000);
85
+ return typeof now === 'number' ? Math.floor(now) : Math.floor(now.getTime() / 1000);
90
86
  }
91
87
  /** The plan for `records` and `deletes` into `repo` (Rust, `techne_sdk::put::plan_with_deletes`). */
92
88
  export function planWithDeletes(repo, records, deletes, now = new Date()) {
93
89
  return call('putPlan', { repo, records, deletes, now: unixSeconds(now) });
94
90
  }
95
- /** How often `wait` asks for the curated record. */
96
- const WAIT_POLL_MS = 250;
97
- export async function put(techne, records, options = {}) {
98
- const { did } = techne;
99
- const { writes, deletes } = options.deletes?.length ? planWithDeletes(did, records, options.deletes) : { writes: plan(did, records), deletes: [] };
100
- const privates = writes.filter((w) => w.private);
101
- const publics = writes.filter((w) => !w.private);
102
- const publicDeletes = deletes.filter((d) => !d.private);
103
- const unplaced = privates.filter((w) => !w.space);
104
- if (unplaced.length)
105
- throw new PutError(unplaced.map((w) => ({ uri: w.uri, error: 'InvalidRequest', message: noSpace(did, w.collection) })));
106
- const contacts = writes.filter((w) => w.collection === NSID.CONTACT);
107
- if (contacts.length) {
108
- const gone = new Set(deletes.map((d) => d.uri));
109
- const conflicts = contactConflicts((await storedContacts(techne)).filter((c) => !gone.has(c.uri)), contacts);
110
- if (conflicts.length)
111
- throw new ContactConflictError(conflicts);
112
- }
113
- if (privates.length) {
114
- const { data } = await techne.platform.pub.techne.draft.permissioned.putRecords({
115
- repo: did,
116
- // Every private write names its space (checked above).
117
- writes: privates.map(({ collection, rkey, record, space }) => ({ collection, rkey, record, space: space })),
118
- });
119
- const refused = data.results.flatMap((r, i) => r.$type === NSID.PERMISSIONED_PUT_RECORDS_WRITE_ERROR ? [{ uri: privates[i].uri, error: String(r.error), message: String(r.message) }] : []);
120
- if (refused.length)
121
- throw new PutError(refused);
122
- }
123
- const done = new Map();
124
- // The public deletes the PDS carried out in the applyWrites, hinted after (step 5).
125
- const pdsDeleted = [];
126
- if (publics.length || publicDeletes.length) {
127
- const current = await Promise.all(publics.map((w) => currentCid(techne, w)));
128
- const ops = publics.flatMap((w, i) => current[i] === w.cid
129
- ? []
130
- : [{ $type: current[i] ? 'com.atproto.repo.applyWrites#update' : 'com.atproto.repo.applyWrites#create', collection: w.collection, rkey: w.rkey, value: w.record }]);
131
- // A record already gone is not deleted again (a PDS refuses deleting what it does not hold).
132
- const held = await Promise.all(publicDeletes.map((d) => currentCid(techne, d)));
133
- for (const [i, d] of publicDeletes.entries()) {
134
- if (held[i])
135
- ops.push({ $type: 'com.atproto.repo.applyWrites#delete', collection: d.collection, rkey: d.rkey });
136
- }
137
- if (ops.length)
138
- await techne.pds.com.atproto.repo.applyWrites({ repo: did, writes: ops });
139
- for (const [i, d] of publicDeletes.entries()) {
140
- if (!held[i])
141
- continue;
142
- done.set(d.uri, true);
143
- pdsDeleted.push(d.uri);
144
- }
145
- }
146
- // Private deletes after the public leg: nothing public is left pointing at what they remove. A public
147
- // delete the PDS did not hold goes here too: a record of that collection kept in a space, named
148
- // without it. Deleting what is already gone answers without a `rev`, so a retry is a no-op.
149
- for (const d of deletes) {
150
- if (done.has(d.uri))
151
- continue;
152
- const { data } = await techne.platform.pub.techne.draft.permissioned.deleteRecord({ repo: did, collection: d.collection, rkey: d.rkey });
153
- done.set(d.uri, Boolean(data.rev));
154
- }
155
- const answers = new Map();
156
- // The public deletes are hinted beside the writes; their answer is not kept (a failed hint is ignored).
157
- await Promise.all([...publics.map(async (w) => answers.set(w, await hint(techne, w.uri))), ...pdsDeleted.map((uri) => hint(techne, uri))]);
158
- const curatable = publics.filter((w) => w.lexicon);
159
- const counted = (curatable.length ? curatable : publics).map((w) => answers.get(w));
160
- const status = counted.find((a) => a.decision === 'invalid') ?? { decision: 'pending' };
161
- const result = {
162
- writes: writes.map((w) => (answers.has(w) ? { ...w, status: answers.get(w) } : w)),
163
- deletes: deletes.map((d) => ({ ...d, deleted: done.get(d.uri) ?? false })),
164
- status,
165
- curation: [],
166
- };
167
- // Only a record with a lexicon the platform did not refuse can come back curated.
168
- const waitable = curatable.filter((w) => answers.get(w).decision !== 'invalid');
169
- if (options.wait && waitable.length) {
170
- const curated = await curatedOf(techne, waitable, Date.now() + options.wait);
171
- if (curated)
172
- result.curated = curated;
173
- }
174
- const { read, error } = await curationRead(techne, publics);
175
- result.curation = curationOfWrites(publics, answers, read);
176
- if (error !== undefined)
177
- result.curationError = error;
178
- return result;
179
- }
180
- /** The platform's curation answer for `publics`, by URI, through {@link getRecordsAnswer} (which keeps each
181
- * GET under the length a proxy takes), and why it failed when it did (then nothing is read). */
182
- async function curationRead(techne, publics) {
183
- if (!publics.length)
184
- return { read: new Map() };
185
- const reader = async (nsid, params) => (await techne.platform.call(nsid, params)).data;
186
- try {
187
- return { read: (await getRecordsAnswer(reader, publics.map((w) => w.uri), { curation: true })).curation };
188
- }
189
- catch (error) {
190
- return { read: new Map(), error };
191
- }
192
- }
193
- /** The curation status of each of `publics` (see {@link PutResult.curation}). */
194
- function curationOfWrites(publics, answers, read) {
195
- return publics.map((w) => {
196
- const known = read.get(w.uri);
197
- const hinted = answers.get(w);
198
- // A refusal the hint answered stands over a read that has not caught up with it.
199
- if (hinted?.decision === 'invalid' && (!known || known.status === 'pending'))
200
- return { uri: w.uri, status: 'notCurated', reason: hinted.reason };
201
- return known ?? { uri: w.uri, status: 'pending' };
202
- });
203
- }
204
- /** The CID the user's repo holds at `w`'s key, or `null` when it holds nothing there. */
205
- async function currentCid(techne, w) {
206
- try {
207
- const { data } = await techne.pds.com.atproto.repo.getRecord({ repo: techne.did, collection: w.collection, rkey: w.rkey });
208
- return data.cid ?? null;
209
- }
210
- catch (e) {
211
- if (e instanceof XRPCError && e.error === 'RecordNotFound')
212
- return null;
213
- throw e;
214
- }
215
- }
216
- /**
217
- * The hint for one public record. `indexRecord` answers `decide` for the version it indexed (P1.4:
218
- * `valid`, `pending` or `invalid` with a reason); a version the platform refused answers `invalid`.
219
- * Anything it did not refuse answers `pending` here: `put` is pending until its curated version lands
220
- * (`wait`). Any other failure (rate limit, an unreachable PDS) answers `pending`: the relay brings the
221
- * record anyway.
222
- */
223
- async function hint(techne, uri) {
224
- try {
225
- const { data } = await techne.platform.pub.techne.draft.sync.indexRecord({ uri });
226
- if (data.decision === 'invalid')
227
- return { decision: 'invalid', reason: data.reason ?? 'invalid' };
228
- return { decision: 'pending' };
229
- }
230
- catch {
231
- return { decision: 'pending' };
232
- }
233
- }
234
- /** The first curated record that names one of `sources`, at the CID just written, as its source. */
235
- async function curatedOf(techne, sources, deadline) {
236
- for (;;) {
237
- for (const source of sources) {
238
- const answer = await techne.platform.pub.techne.draft.commons.getVersions({ uri: source.uri }).then((r) => r.data, () => null);
239
- if (answer && answer.uri !== source.uri && answer.versions.some((v) => v.uri === source.uri && v.cid === source.cid)) {
240
- return { uri: answer.uri, cid: answer.cid, record: answer.record };
241
- }
242
- }
243
- const left = deadline - Date.now();
244
- if (left <= 0)
245
- return undefined;
246
- await new Promise((r) => setTimeout(r, Math.min(WAIT_POLL_MS, left)));
247
- }
248
- }
249
91
  /**
250
92
  * An event with its config, and its detail when it has gated fields, as the records to `put`
251
93
  * (repo = the host's DID). The config and the detail point at the event by URI and CID. The config is
@@ -0,0 +1,14 @@
1
+ import type { Clients } from '../connect.js';
2
+ import { type DeleteRecord, type PutRecord, type PutResult } from './index.js';
3
+ /** What `put` takes beside the records (see `./index`). */
4
+ export interface PutOptions {
5
+ wait?: number;
6
+ deletes?: DeleteRecord[];
7
+ }
8
+ /**
9
+ * `put(techne, records, options)`: the write (`./index` says what it does), on what `connect` returns
10
+ * (`techne.put` is this) or on any {@link Clients}. Runs once more from the start when a call got no
11
+ * response; it re-reads first, so nothing lands twice and nothing is deleted twice. Only the writes and
12
+ * deletes throw: the hints and the curation read already answer `pending`.
13
+ */
14
+ export declare function put(techne: Clients, records: PutRecord[], options?: PutOptions): Promise<PutResult>;