techne-sdk 0.3.3 → 0.3.4

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.
@@ -21,17 +21,103 @@
21
21
  * public record might be the commons collective's or name it, so every public record is anonymous then:
22
22
  * "Hosted by" never names the commons collective for want of its DID.
23
23
  */
24
+ import { type Binding, type EnvelopeField, type Composed, type Composition, type Reader, type StepRecord, type StepRef } from './compose.js';
24
25
  import { type Query, type QueryReader, type QueryRecord } from './index.js';
25
26
  /** The provenance records written about `$uris` (as written: a read scoped to subjects). */
26
27
  export declare const PROVENANCE_OF_QUERY: Query;
27
28
  /** The mirror sidecars written about `$uris` (`source`, and the frozen old-Almanac `sourceRef`). */
28
29
  export declare const MIRROR_SIDECARS_QUERY: Query;
30
+ interface StrongRef {
31
+ uri?: unknown;
32
+ }
33
+ interface ProvenanceValue {
34
+ subject?: StrongRef;
35
+ sources?: unknown;
36
+ composition?: {
37
+ byline?: unknown;
38
+ };
39
+ }
40
+ /** Each curated record's own provenance (same author, subject that record), by the curated record's URI. */
41
+ export declare function provenancesOf(read: QueryReader, curated: readonly StepRecord<unknown, 'author'>[]): Promise<Map<string, ProvenanceValue>>;
29
42
  /** The sources each curated record's own provenance lists (same author, subject that record, public), in
30
43
  * provenance order, by the curated record's URI. A record that is not curated, or has no such provenance,
31
44
  * is absent. */
32
45
  export declare function provenanceSourcesOf(read: QueryReader, records: readonly QueryRecord[]): Promise<Map<string, string[]>>;
33
46
  /** The host DID of each record (by URI), `null` when it is anonymous. */
34
- export declare function hostsOf(read: QueryReader, records: readonly QueryRecord[], commonsDid?: string | null): Promise<Map<string, string | null>>;
47
+ export declare function hostsOf(read: QueryReader, records: readonly HostedRecord[], commonsDid?: string | null): Promise<Map<string, string | null>>;
48
+ /** What {@link hostsFrom} reads of a provenance: its subject's URI (never its `cid`), its sources' URIs and its byline. */
49
+ export declare const PROVENANCE_FIELDS: readonly string[];
50
+ /** The records at `$uris` that no mirror sidecar describes (no public `source` or `sourceRef` by the record's own
51
+ * author has it as its subject), as written (envelope and value; not their curated stand-ins): {@link hostSteps}'
52
+ * `src`, the sources a provenance lists that can host, in one bound list.
53
+ * The anti-join is the server's (`has`), so the step answers the few hosting sources, not every mirror's copy. */
54
+ export declare const HOST_SOURCES_QUERY: Query;
55
+ /** What the host rule reads of a record whose host it finds: its `uri`, `author`, `source` and `curated`. */
56
+ export type HostedRecord = StepRecord<unknown, 'author' | 'source' | 'curated'>;
57
+ /** The record fields {@link hostsFrom} reads of the host steps' records: a page that hands the provenances to no
58
+ * other rule asks {@link hostSteps} for exactly these. */
59
+ export declare const HOST_ENVELOPE: readonly ["author", "source"];
60
+ export type HostEnvelope = (typeof HOST_ENVELOPE)[number];
61
+ /** The steps {@link hostsFrom} reads, as {@link hostSteps} builds them, each keeping the `E` record fields (the
62
+ * sidecars `M`). `prov` and `mirrors` may answer their records without their `uri` (hostSteps asks `uri: false`:
63
+ * nothing reads it); `src` is read by URI. */
64
+ export interface HostSteps<E extends EnvelopeField = EnvelopeField, M extends EnvelopeField = E> {
65
+ /** The provenances about the records, cut to {@link PROVENANCE_FIELDS}. */
66
+ prov: StepRef<'list', true, E, boolean>;
67
+ /** The sources the provenances list that no mirror sidecar describes, envelope only, with their repos' handles
68
+ * ({@link HOST_SOURCES_QUERY}): every live one that can host, since it is read up to {@link MAX_STEP_LIMIT}. */
69
+ src: StepRef<'list', true, E>;
70
+ /** The mirror sidecars about the records (and their sources with `sourceMirrors`), cut to their `subject` (or
71
+ * `mirrorFields`). */
72
+ mirrors: StepRef<'list', true, M, boolean>;
73
+ }
74
+ /** What {@link hostSteps} takes beside the records. */
75
+ export interface HostStepOpts<E extends EnvelopeField = EnvelopeField, M extends EnvelopeField = E> {
76
+ /** What the mirror sidecars keep (default `subject`, all {@link hostsFrom} reads): a page that also reads the
77
+ * sidecars' own fields (their `url` and credits, `listedOnOf`) asks those too. */
78
+ mirrorFields?: readonly string[];
79
+ /** Also read the mirror sidecars about every source the provenances list (`mirrors` bound to them too), for a
80
+ * page that names the mirrors themselves (`listedOnOf`'s "also listed on"). {@link hostsFrom} does not need
81
+ * them: `src` already leaves out a mirrored source. */
82
+ sourceMirrors?: boolean;
83
+ /** The record fields the three steps keep besides `uri` and `value` (every one when absent). {@link hostsFrom}
84
+ * reads `author` and `source`; a page that hands the provenances to other rules asks what those read. */
85
+ envelope?: readonly E[];
86
+ /** The record fields the mirror sidecars keep instead (default `envelope`): a page that also reads the
87
+ * sidecars' own fields (`listedOnOf`'s `sidecarsOf`, a `source` before a `sourceRef`: `collection`) asks those. */
88
+ mirrorEnvelope?: readonly M[];
89
+ }
90
+ /**
91
+ * Add to `c` the three steps "Hosted by" reads about `records` (a step's records, or a list of AT-URIs and
92
+ * bindings, at least one), all `optional` (a decoration: when one fails {@link hostsFrom} reads the hosts after the
93
+ * call, never failing the call), each asked {@link MAX_STEP_LIMIT} records so it answers all of them in this call
94
+ * (lucian 2026-11-04: no second round for the rest): `prov` their provenances, `src` every source those list
95
+ * that no mirror sidecar describes ({@link HOST_SOURCES_QUERY}: the server's anti-join, so a mirror's copy is never
96
+ * read; envelope only, with handles: a host's handle when its face has none) and `mirrors` the mirror sidecars about
97
+ * the records (and the sources, `sourceMirrors`). Only the fields {@link hostsFrom} reads come back: `prov` and
98
+ * `mirrors` answer without their records' own `uri` (`uri: false`; their bindings still read it). `prefix`
99
+ * keeps the step names apart when one composition asks for two sets of hosts. The hosts' faces are the caller's:
100
+ * bind `[records.author, steps.src.author]` (or the records' authors as literals).
101
+ */
102
+ export declare function hostSteps<E extends EnvelopeField, M extends EnvelopeField>(c: Composition, records: {
103
+ uri: Binding;
104
+ } | readonly (string | Binding)[], prefix: string, opts: HostStepOpts<E, M> & {
105
+ mirrorEnvelope: readonly M[];
106
+ }): HostSteps<E, M>;
107
+ /** The sidecars keep what `envelope` keeps (no `mirrorEnvelope`): one field set `E` for all three steps. */
108
+ export declare function hostSteps<E extends EnvelopeField = EnvelopeField>(c: Composition, records: {
109
+ uri: Binding;
110
+ } | readonly (string | Binding)[], prefix?: string, opts?: HostStepOpts<E, E> & {
111
+ mirrorEnvelope?: undefined;
112
+ }): HostSteps<E, E>;
113
+ /**
114
+ * The host DID of each record (by URI, `null` anonymous) from one composed answer ({@link hostSteps}): the same
115
+ * rule as {@link hostsOf}, read from the three steps alone (each asked {@link MAX_STEP_LIMIT} records, so `src` is
116
+ * every live source no mirror sidecar describes and `mirrors` every sidecar about the records). A step that failed (or was skipped): the whole of
117
+ * {@link hostsOf} after the call. A step that still answers a cursor matched more than {@link MAX_STEP_LIMIT}
118
+ * records: an error, never a partial host (no read of the rest). Never a wrong host.
119
+ */
120
+ export declare function hostsFrom(answer: Composed, steps: HostSteps<HostEnvelope, HostEnvelope>, records: readonly HostedRecord[], commonsDid: string | null | undefined, read: QueryReader): Promise<Map<string, string | null>>;
35
121
  /** One source credit (`pub.techne.draft.sourceAttribution`), pinned to its publisher and exact CID. */
36
122
  export interface SourceCredit {
37
123
  uri: string;
@@ -75,3 +161,14 @@ export declare const CURATED_FROM_QUERY: Query;
75
161
  * author wrote counts, and only a record the platform marks curated. `undefined`: nothing stands for it.
76
162
  */
77
163
  export declare function curatedFor(read: QueryReader, uri: string): Promise<QueryRecord | undefined>;
164
+ /**
165
+ * {@link curatedFor} of each of `uris` (at most 500, the misses of one get step), as ONE `composeRecords` call:
166
+ * `cf` the provenances listing a URI among their sources and `cfSub` their subjects; `own` each URI's own
167
+ * provenance, `viaSrc` the provenances listing its sources and `viaSub` their subjects. The same checks, per
168
+ * URI, on the client (public, not superseded, written by its subject's author, the subject curated; for the
169
+ * second way the URI's own provenance only). Each list step is asked {@link MAX_STEP_LIMIT} records, so it
170
+ * answers all of them; one that still answers a cursor (more than that) throws, as a failed call does.
171
+ * By URI; `undefined`, nothing stands for it.
172
+ */
173
+ export declare function curatedForAll(read: Reader, uris: readonly string[]): Promise<Map<string, QueryRecord | undefined>>;
174
+ export {};
@@ -22,6 +22,7 @@
22
22
  * "Hosted by" never names the commons collective for want of its DID.
23
23
  */
24
24
  import { NSID } from '../generated/nsid.js';
25
+ import { compose, ENVELOPE_ONLY, MAX_STEP_LIMIT } from './compose.js';
25
26
  import { getRecords, listAllRecordsFor } from './index.js';
26
27
  /** The provenance records written about `$uris` (as written: a read scoped to subjects). */
27
28
  export const PROVENANCE_OF_QUERY = {
@@ -50,11 +51,20 @@ async function sidecarsOf(read, uris) {
50
51
  out.set(uri, [...(out.get(uri) ?? []), s]);
51
52
  }
52
53
  for (const list of out.values())
53
- list.sort((a, b) => Number(b.collection === NSID.SOURCE) - Number(a.collection === NSID.SOURCE) || a.uri.localeCompare(b.uri));
54
+ list.sort(bySidecarOrder);
54
55
  return out;
55
56
  }
57
+ /** A `source` before a `sourceRef`, then by URI; with no URI (all equal) by the sidecar's `url`, then its whole
58
+ * value, so {@link listedOnOf} picks the same `source` (and its url) on every load whatever order they came in. */
59
+ function bySidecarOrder(a, b) {
60
+ const url = (s) => { const u = s.value.url; return typeof u === 'string' ? u : ''; };
61
+ return Number(b.collection === NSID.SOURCE) - Number(a.collection === NSID.SOURCE)
62
+ || (a.uri ?? '').localeCompare(b.uri ?? '')
63
+ || url(a).localeCompare(url(b))
64
+ || JSON.stringify(a.value).localeCompare(JSON.stringify(b.value));
65
+ }
56
66
  /** Each curated record's own provenance (same author, subject that record), by the curated record's URI. */
57
- async function provenancesOf(read, curated) {
67
+ export async function provenancesOf(read, curated) {
58
68
  const out = new Map();
59
69
  if (curated.length === 0)
60
70
  return out;
@@ -106,6 +116,85 @@ export async function hostsOf(read, records, commonsDid) {
106
116
  out.set(r.uri, r.author === commons || mirrors.has(r.uri) ? null : r.author);
107
117
  return out;
108
118
  }
119
+ // ── "Hosted by" on one composed call ────────────────────────────────────────────────────────────
120
+ /** What {@link hostsFrom} reads of a provenance: its subject's URI (never its `cid`), its sources' URIs and its byline. */
121
+ export const PROVENANCE_FIELDS = ['subject.uri', 'sources[].uri', 'composition.byline'];
122
+ /** The records at `$uris` that no mirror sidecar describes (no public `source` or `sourceRef` by the record's own
123
+ * author has it as its subject), as written (envelope and value; not their curated stand-ins): {@link hostSteps}'
124
+ * `src`, the sources a provenance lists that can host, in one bound list.
125
+ * The anti-join is the server's (`has`), so the step answers the few hosting sources, not every mirror's copy. */
126
+ export const HOST_SOURCES_QUERY = {
127
+ where: {
128
+ all: [
129
+ { uri: { in: ['$uris'] } },
130
+ { not: [{ has: { via: 'subject', by: 'author', where: { type: { in: [NSID.SOURCE, NSID.SOURCE_REF] } } } }] },
131
+ ],
132
+ },
133
+ curated: false,
134
+ };
135
+ /** The record fields {@link hostsFrom} reads of the host steps' records: a page that hands the provenances to no
136
+ * other rule asks {@link hostSteps} for exactly these. */
137
+ export const HOST_ENVELOPE = ['author', 'source'];
138
+ export function hostSteps(c, records, prefix = 'host', opts = {}) {
139
+ const uris = 'uri' in records ? [records.uri] : [...new Set(records)];
140
+ if (uris.length === 0)
141
+ throw new Error('hostSteps: no records to read the hosts of');
142
+ const { envelope } = opts;
143
+ // The overloads tie `M` to `mirrorEnvelope` when one is given, else to `envelope` (`M` is `E`).
144
+ const mirrorEnvelope = opts.mirrorEnvelope ?? envelope;
145
+ const prov = c.list(`${prefix}Prov`, PROVENANCE_OF_QUERY, { params: { uris: 'uri' in records ? records.uri : uris }, limit: MAX_STEP_LIMIT, fields: PROVENANCE_FIELDS, envelope, uri: false, optional: true });
146
+ const sources = prov.value('sources[].uri');
147
+ const src = c.list(`${prefix}Src`, HOST_SOURCES_QUERY, { params: { uris: sources }, limit: MAX_STEP_LIMIT, fields: ENVELOPE_ONLY, envelope, handles: true, optional: true });
148
+ const mirrors = c.list(`${prefix}Mirrors`, MIRROR_SIDECARS_QUERY, { params: { uris: opts.sourceMirrors ? [sources, ...uris] : uris }, limit: MAX_STEP_LIMIT, fields: opts.mirrorFields ?? ['subject'], envelope: mirrorEnvelope, uri: false, optional: true });
149
+ return { prov, src, mirrors };
150
+ }
151
+ /** Mirror sidecars by the URI they describe (only the described record's own author's count). */
152
+ function sidecarsIn(found) {
153
+ const out = new Set();
154
+ for (const s of found) {
155
+ if (s.source !== 'public')
156
+ continue;
157
+ const subject = s.value.subject;
158
+ const uri = typeof subject === 'string' ? subject : typeof subject?.uri === 'string' ? subject.uri : undefined;
159
+ if (uri && authority(uri) === s.author)
160
+ out.add(uri);
161
+ }
162
+ return out;
163
+ }
164
+ /**
165
+ * The host DID of each record (by URI, `null` anonymous) from one composed answer ({@link hostSteps}): the same
166
+ * rule as {@link hostsOf}, read from the three steps alone (each asked {@link MAX_STEP_LIMIT} records, so `src` is
167
+ * every live source no mirror sidecar describes and `mirrors` every sidecar about the records). A step that failed (or was skipped): the whole of
168
+ * {@link hostsOf} after the call. A step that still answers a cursor matched more than {@link MAX_STEP_LIMIT}
169
+ * records: an error, never a partial host (no read of the rest). Never a wrong host.
170
+ */
171
+ export async function hostsFrom(answer, steps, records, commonsDid, read) {
172
+ const out = new Map();
173
+ for (const r of records)
174
+ out.set(r.uri, r.source === 'public' ? null : r.author);
175
+ if (commonsDid === null)
176
+ return out;
177
+ if (answer.failed(steps.prov) || answer.failed(steps.src) || answer.failed(steps.mirrors))
178
+ return hostsOf(read, records, commonsDid);
179
+ for (const step of [steps.prov, steps.src, steps.mirrors])
180
+ answer.whole(step, 'hostsFrom');
181
+ const commons = commonsDid?.trim() || undefined;
182
+ const curated = records.filter((r) => r.source === 'public' && r.curated);
183
+ const plain = records.filter((r) => r.source === 'public' && !r.curated);
184
+ const provs = answer.list(steps.prov).records.filter((p) => p.source === 'public');
185
+ const live = new Set([...answer.records(steps.src).values()].filter((r) => r.source === 'public').map((r) => r.uri));
186
+ const mirrors = sidecarsIn(answer.list(steps.mirrors).records);
187
+ const ownProv = (r) => provs.find((p) => p.author === r.author && p.value.subject?.uri === r.uri)?.value;
188
+ for (const r of curated) {
189
+ const v = ownProv(r);
190
+ const byline = typeof v?.composition?.byline === 'string' ? v.composition.byline : undefined;
191
+ const host = sourceUris(v).find((u) => authority(u) !== commons && (byline === undefined || u === byline) && live.has(u) && !mirrors.has(u));
192
+ out.set(r.uri, host ? authority(host) : null);
193
+ }
194
+ for (const r of plain)
195
+ out.set(r.uri, r.author === commons || mirrors.has(r.uri) ? null : r.author);
196
+ return out;
197
+ }
109
198
  /** `http(s)` with a host and no credentials: the server's `public_links::public_web_url`. */
110
199
  export function publicWebUrl(value) {
111
200
  if (typeof value !== 'string' || value.length > 2048 || /[\u0000-\u001f\u007f-\u009f]/.test(value))
@@ -225,3 +314,55 @@ export async function curatedFor(read, uri) {
225
314
  const own = (await publicFor(read, PROVENANCE_OF_QUERY, [uri])).find((p) => p.author === authority(uri) && p.value.subject?.uri === uri);
226
315
  return viaSources(sourceUris(own?.value));
227
316
  }
317
+ /** What {@link curatedForAll} reads of a provenance: its subject, its sources and whether it is superseded. */
318
+ const CURATED_FROM_FIELDS = ['subject', 'sources[].uri', 'readiness'];
319
+ /**
320
+ * {@link curatedFor} of each of `uris` (at most 500, the misses of one get step), as ONE `composeRecords` call:
321
+ * `cf` the provenances listing a URI among their sources and `cfSub` their subjects; `own` each URI's own
322
+ * provenance, `viaSrc` the provenances listing its sources and `viaSub` their subjects. The same checks, per
323
+ * URI, on the client (public, not superseded, written by its subject's author, the subject curated; for the
324
+ * second way the URI's own provenance only). Each list step is asked {@link MAX_STEP_LIMIT} records, so it
325
+ * answers all of them; one that still answers a cursor (more than that) throws, as a failed call does.
326
+ * By URI; `undefined`, nothing stands for it.
327
+ */
328
+ export async function curatedForAll(read, uris) {
329
+ const out = new Map();
330
+ const asked = [...new Set(uris)];
331
+ if (asked.length === 0)
332
+ return out;
333
+ const c = compose();
334
+ const cf = c.list('cf', CURATED_FROM_QUERY, { params: { uris: asked }, limit: MAX_STEP_LIMIT, fields: CURATED_FROM_FIELDS });
335
+ const cfSub = c.get('cfSub', [cf.value('subject.uri')]);
336
+ const own = c.list('own', PROVENANCE_OF_QUERY, { params: { uris: asked }, limit: MAX_STEP_LIMIT, fields: ['subject', 'sources[].uri'] });
337
+ const viaSrc = c.list('viaSrc', CURATED_FROM_QUERY, { params: { uris: [own.value('sources[].uri')] }, limit: MAX_STEP_LIMIT, fields: CURATED_FROM_FIELDS });
338
+ const viaSub = c.get('viaSub', [viaSrc.value('subject.uri')]);
339
+ const answer = await c.run(read.post);
340
+ const [cfs, owns, vias] = [answer.whole(cf, 'curatedForAll'), answer.whole(own, 'curatedForAll'), answer.whole(viaSrc, 'curatedForAll')];
341
+ const subjectOf = (p) => p.value.subject?.uri;
342
+ // `curatedFor`'s `viaSources`: the live provenances listing any of `sources`, their curated subjects.
343
+ const viaSources = (uri, sources, provenances, subjects) => {
344
+ if (sources.length === 0)
345
+ return undefined;
346
+ const counted = provenances.filter((p) => {
347
+ const v = p.value;
348
+ const subject = subjectOf(p);
349
+ return p.source === 'public' && sourceUris(v).some((s) => sources.includes(s)) && v.readiness !== 'superseded' && typeof subject === 'string' && authority(subject) === p.author;
350
+ });
351
+ return counted
352
+ .map((p) => subjectOf(p))
353
+ .filter((u) => u !== uri)
354
+ .map((u) => subjects.get(u))
355
+ .find((r) => r?.curated);
356
+ };
357
+ const [cfSubjects, viaSubjects] = [answer.records(cfSub), answer.records(viaSub)];
358
+ for (const uri of asked) {
359
+ const asSource = viaSources(uri, [uri], cfs, cfSubjects);
360
+ if (asSource) {
361
+ out.set(uri, asSource);
362
+ continue;
363
+ }
364
+ const mine = owns.find((p) => p.source === 'public' && p.author === authority(uri) && subjectOf(p) === uri);
365
+ out.set(uri, viaSources(uri, sourceUris(mine?.value), vias, viaSubjects));
366
+ }
367
+ return out;
368
+ }
@@ -5,8 +5,9 @@
5
5
  * `space`, `uri`, `written`, and what each type's query document declares: `start`, `end`, `location`,
6
6
  * `text`, `references`), one `order` and `signals`. The platform scopes every query to what the
7
7
  * viewer may read and proves it bounded; this module only carries it: `listRecords` (one page),
8
- * `listAllRecords` (every page), `countRecords`, and `getRecords` (by URI, in batches the platform takes; `getRecordsAnswer` also says which
9
- * asked URIs moderation withheld).
8
+ * `listAllRecords` (every page), `countRecords`, `getRecords` (by URI, in batches the platform takes; `getRecordsAnswer` also says which
9
+ * asked URIs moderation withheld), and `compose` (several of these in one request, a later step reading what an earlier one
10
+ * answered: `composeRecords`, `./compose.ts`).
10
11
  *
11
12
  * An app holds its query definitions (data, like any record) and calls these with its own reader: a
12
13
  * `get(nsid, params)` over whatever session it has. What a record means stays the app's.
@@ -18,26 +19,37 @@ export type Param = string | readonly string[];
18
19
  export type QueryReader = <T>(nsid: string, params: Record<string, string | number | readonly string[] | undefined>) => Promise<T>;
19
20
  /** One condition on a role (`{ "is": … }`, `{ "near": { point, within }, "as": … }`, …). */
20
21
  export type Condition = Readonly<Record<string, unknown>>;
21
- /** A node of a query's `where`: `all` / `any` / `not`, or one role's condition. */
22
+ /** `has`: some public record the caller may read names this one through the role `via` (`subject`), by this
23
+ * record's own author when `by: 'author'`, and matches `where` (type and author conditions, `is`/`in`, alone or
24
+ * under `all`). It narrows a branch and never drives one; under `not` it is an anti-join. */
25
+ export interface HasCondition {
26
+ readonly via: string;
27
+ readonly by?: 'author';
28
+ readonly where?: QueryNode;
29
+ }
30
+ /** A node of a query's `where`: `all` / `any` / `not` / `has`, or one role's condition. */
22
31
  export type QueryNode = {
23
32
  readonly all: readonly QueryNode[];
24
33
  } | {
25
34
  readonly any: readonly QueryNode[];
26
35
  } | {
27
36
  readonly not: readonly [QueryNode];
37
+ } | {
38
+ readonly has: HasCondition;
28
39
  } | {
29
40
  readonly [role: string]: Condition | readonly QueryNode[];
30
41
  };
31
42
  /** A `pub.techne.draft.query`, as data (the platform validates it). */
32
43
  export interface Query {
33
44
  readonly where: QueryNode;
45
+ /** A role, a measure's `as` name, or `shuffle` (one deterministic order per {@link Query.seed}). */
34
46
  readonly order?: string;
47
+ /** The seed of `order: "shuffle"`: a literal or a `$param`; required with it, refused without it. */
48
+ readonly seed?: string;
35
49
  readonly limit?: number;
36
50
  readonly signals?: readonly Readonly<Record<string, unknown>>[];
37
51
  readonly curated?: boolean;
38
- /** The seed of `order: 'shuffle'`, a literal or a parameter (`$seed`); required with it. */
39
- readonly seed?: string;
40
- /** Only the signed-in caller's own records the reach limit holds back (each answered `held`). */
52
+ /** Only the caller's own permissioned records the reach limit is holding back (each marked `held`). */
41
53
  readonly held?: boolean;
42
54
  }
43
55
  /** One record a query answered (`pub.techne.draft.query.listRecords#record`). */
@@ -55,8 +67,8 @@ export interface QueryRecord<V = Record<string, unknown>> {
55
67
  /** A public record that is a live curated record (a curator the commons root trusts merged it); its
56
68
  * provenance names who it is from ({@link hostsOf}). Absent otherwise. */
57
69
  curated?: boolean;
58
- /** The caller's own permissioned record the reach limit holds back from the people it would reach,
59
- * answered to its author alone until the limit admits it. Absent otherwise. */
70
+ /** The caller's own permissioned record the reach limit holds back from the people it would reach:
71
+ * answered to its author alone (anyone else does not see it) until the limit admits it. */
60
72
  held?: boolean;
61
73
  /** The numbers the query's operators produced, by name (a `near` distance in metres). */
62
74
  measures?: Record<string, number>;
@@ -65,22 +77,32 @@ export interface QueryRecord<V = Record<string, unknown>> {
65
77
  export interface ListPage<V = Record<string, unknown>> {
66
78
  records: QueryRecord<V>[];
67
79
  cursor?: string;
68
- /** Asked with `count: true`: how many records the query answers this caller ({@link countRecords}'s). */
80
+ /** Asked with `count`: how many records the query answers this caller (countRecords' `count`). */
69
81
  count?: number;
70
- /** Asked with `count: true`: there are more than `count`. */
82
+ /** Asked with `count`: counting stopped at the platform's cap. */
71
83
  capped?: boolean;
72
84
  }
73
- /** The most records one page (and one `getRecords` call) carries. */
74
- export declare const MAX_PAGE = 100;
85
+ /** The most records one `listRecords` page carries (the lexicon's `limit` maximum). */
86
+ export declare const MAX_PAGE = 500;
87
+ /** The most URIs one `getRecords` call takes, and the most values one `in` list takes (the platform's
88
+ * `MAX_IN`). Separate from {@link MAX_PAGE}: a bigger page does not make a list longer. */
89
+ export declare const MAX_BATCH = 100;
75
90
  export interface ListCall {
76
91
  params?: Readonly<Record<string, Param>>;
77
92
  limit?: number;
78
93
  cursor?: string;
79
- /** Also count what the query answers (the page gains `count` and `capped`). */
94
+ /** Also count what the query answers (the page gains `count`/`capped`). */
80
95
  count?: boolean;
81
96
  }
82
97
  /** One page of `query`. */
83
98
  export declare function listRecords<V = Record<string, unknown>>(read: QueryReader, query: Query, call?: ListCall): Promise<ListPage<V>>;
99
+ /** One page of `query` and how many records it answers in all (`listRecords count=true`): the page and
100
+ * the count in one call. `limit: 1` is the cheap way to ask "how many" with a first record to show.
101
+ * Throws when the answer carries no numeric `count` (a platform that ignores `count`). */
102
+ export declare function listRecordsCounted<V = Record<string, unknown>>(read: QueryReader, query: Query, call?: Omit<ListCall, 'count'>): Promise<ListPage<V> & {
103
+ count: number;
104
+ capped: boolean;
105
+ }>;
84
106
  /** A page whose cursor came back again: paging would never end. */
85
107
  export declare class QueryNoProgressError extends Error {
86
108
  constructor();
@@ -89,15 +111,16 @@ export declare class QueryNoProgressError extends Error {
89
111
  export declare const MAX_PAGES = 100;
90
112
  /**
91
113
  * The most characters one GET's query string may carry. Every read here is a GET (an XRPC query, and it
92
- * must pass a PDS's atproto-proxy as one), and proxies refuse a long request line: one in front of a test
93
- * PDS answered 414 past about 8 KB (nginx's default line buffer), and 100 AT-URIs in one `getRecords` or
94
- * one `in` list are ~11 KB. So a list is sent in runs that fit this as well as {@link MAX_PAGE}.
114
+ * must pass a PDS's atproto-proxy as one), and proxies refuse a long request line: staging's answered 414
115
+ * past about 8 KB (nginx's default line buffer), and 100 AT-URIs in one `getRecords` or one `in` list are
116
+ * ~11 KB. So a list is sent in runs that fit this as well as {@link MAX_BATCH}. A page's size
117
+ * ({@link MAX_PAGE}) is only the `limit` number and never lengthens the request.
95
118
  */
96
119
  export declare const MAX_QUERY_CHARS = 6000;
97
120
  /** The query-string characters a list call spends besides its list: the query JSON and its other params. */
98
121
  export declare function fixedChars(query?: Query, params?: Readonly<Record<string, Param>>): number;
99
122
  /**
100
- * `list` in runs of at most {@link MAX_PAGE} (what one `getRecords` call or one `in` takes) that also fit
123
+ * `list` in runs of at most {@link MAX_BATCH} (what one `getRecords` call or one `in` takes) that also fit
101
124
  * one GET ({@link MAX_QUERY_CHARS}) beside `fixed` characters of query and other params ({@link fixedChars}).
102
125
  * An item too long to fit with anything else goes alone.
103
126
  */
@@ -139,8 +162,8 @@ export interface GetRecordsPage<V = Record<string, unknown>> {
139
162
  handles?: GetRecords.Handle[];
140
163
  /** Asked with `curation`, signed in: the curation status of each asked URI that is the caller's own. */
141
164
  curation?: GetRecords.Curation[];
142
- /** Asked with `defaults`, signed in: each asked URI naming a missing record of the caller's own that
143
- * the platform reads a starting value for, and that value. */
165
+ /** Asked with `defaults`, signed in: each asked URI naming a missing record of the caller's own that the
166
+ * platform reads a starting value for, and that value. */
144
167
  defaults?: GetRecords.Default[];
145
168
  }
146
169
  /**
@@ -161,32 +184,40 @@ export type Curation = {
161
184
  status: 'notCurated';
162
185
  reason: string;
163
186
  };
187
+ /** `c` as a {@link Curation}, or `undefined` for a malformed one or a status this SDK does not know. */
188
+ export declare function curationOf(c: unknown): Curation | undefined;
189
+ /** A handle fit to show, trimmed: `undefined` when there is none, or when it is `handle.invalid` (any case),
190
+ * what atproto reports for an account whose handle does not verify, which names no one. */
191
+ export declare function shownHandle(handle: string | null | undefined): string | undefined;
164
192
  /** {@link getRecords}'s records, and the asked URIs moderation withheld from this caller. */
165
193
  export interface RecordsAnswer<V = Record<string, unknown>> {
166
194
  records: Map<string, QueryRecord<V>>;
167
195
  withheld: Set<string>;
168
- /** Asked with `{ handles: true }`: each named repo's public handle, by DID (empty otherwise). */
196
+ /** Asked with `{ handles: true }`: each named repo's public handle, by DID (empty otherwise; never
197
+ * `handle.invalid`, see {@link shownHandle}). */
169
198
  handles: Map<string, string>;
170
199
  /** Asked with `{ curation: true }`, signed in: the curation status of each asked URI that is the
171
200
  * caller's own, by URI (empty otherwise, and for anyone else's record or a private one). */
172
201
  curation: Map<string, Curation>;
173
- /** Asked with `{ defaults: true }`, signed in: the starting value the platform reads for each asked URI
174
- * naming a missing record of the caller's own, by URI (empty otherwise). Show it until the caller
175
- * writes the record. */
176
- defaults: Map<string, unknown>;
202
+ /** Asked with `{ defaults: true }`, signed in: the value the platform reads in place of each asked
203
+ * missing record of the caller's own that has a starting value, by URI (empty otherwise). Today: a
204
+ * circle someone outside the caller's People added them to starts with its Notifications off. */
205
+ defaults: Map<string, Record<string, unknown>>;
177
206
  }
178
207
  /** The records at `uris` the viewer may read, by URI, and which of the asked URIs were withheld. With
179
208
  * `handles`, also the public handle of each repo the URIs name; with `curation`, the curation status
180
- * of each asked URI that is the signed-in caller's own; with `defaults`, the starting value of each
181
- * missing record of the caller's own the platform has one for (no extra read: the same call answers
182
- * them). `includeBlockedByMe` lifts the caller's own blocks for this read (to name the people they
183
- * blocked). */
209
+ * of each asked URI that is the signed-in caller's own (no extra read: the same call answers it).
210
+ * Like every generic read, it leaves out records and handles across a block either way; `includeBlockedByMe`
211
+ * lifts only the caller's own blocks (naming the people they blocked). */
184
212
  export declare function getRecordsAnswer<V = Record<string, unknown>>(read: QueryReader, uris: Iterable<string>, opts?: {
185
213
  handles?: boolean;
186
214
  curation?: boolean;
187
215
  defaults?: boolean;
188
216
  includeBlockedByMe?: boolean;
189
217
  }): Promise<RecordsAnswer<V>>;
218
+ /** One or more `getRecords` pages (or a composed get step's answer) as a {@link RecordsAnswer}. */
219
+ export declare function answerOf<V = Record<string, unknown>>(pages: readonly GetRecordsPage<V>[]): RecordsAnswer<V>;
190
220
  /** The records at `uris` the viewer may read, by URI (absent: no such record, not readable, or withheld). */
191
221
  export declare function getRecords<V = Record<string, unknown>>(read: QueryReader, uris: Iterable<string>): Promise<Map<string, QueryRecord<V>>>;
192
- export { CURATED_FROM_QUERY, curatedFor, hostsOf, listedOnOf, MIRROR_SIDECARS_QUERY, PROVENANCE_OF_QUERY, provenanceSourcesOf, publicWebUrl, type ListedOn, type SourceCredit, } from './hosts.js';
222
+ export { CURATED_FROM_QUERY, curatedFor, curatedForAll, hostsFrom, hostsOf, HOST_ENVELOPE, hostSteps, listedOnOf, MIRROR_SIDECARS_QUERY, PROVENANCE_FIELDS, PROVENANCE_OF_QUERY, HOST_SOURCES_QUERY, provenanceSourcesOf, publicWebUrl, type HostStepOpts, type HostEnvelope, type HostedRecord, type HostSteps, type ListedOn, type SourceCredit, } from './hosts.js';
223
+ export { compose, Composed, ComposeStepError, Composition, COMPOSE_RETRIES, emulateCompose, ENVELOPE_FIELDS, ENVELOPE_ONLY, MAX_BOUND, MAX_STEP_LIMIT, MAX_STEP_URIS, MAX_STEPS, MAX_TOTAL_RECORDS, selectFields, testReader, withPost, type Binding, type EnvelopeField, type ComposePoster, type GetStepOpts, type ListStepOpts, type ListStepPage, type Output, type Reader, type RunOpts, type StepError, type StepParam, type StepAnswer, type StepRecord, type StepRef, type WireStep, } from './compose.js';
@@ -5,15 +5,19 @@
5
5
  * `space`, `uri`, `written`, and what each type's query document declares: `start`, `end`, `location`,
6
6
  * `text`, `references`), one `order` and `signals`. The platform scopes every query to what the
7
7
  * viewer may read and proves it bounded; this module only carries it: `listRecords` (one page),
8
- * `listAllRecords` (every page), `countRecords`, and `getRecords` (by URI, in batches the platform takes; `getRecordsAnswer` also says which
9
- * asked URIs moderation withheld).
8
+ * `listAllRecords` (every page), `countRecords`, `getRecords` (by URI, in batches the platform takes; `getRecordsAnswer` also says which
9
+ * asked URIs moderation withheld), and `compose` (several of these in one request, a later step reading what an earlier one
10
+ * answered: `composeRecords`, `./compose.ts`).
10
11
  *
11
12
  * An app holds its query definitions (data, like any record) and calls these with its own reader: a
12
13
  * `get(nsid, params)` over whatever session it has. What a record means stays the app's.
13
14
  */
14
15
  import { NSID } from '../generated/nsid.js';
15
- /** The most records one page (and one `getRecords` call) carries. */
16
- export const MAX_PAGE = 100;
16
+ /** The most records one `listRecords` page carries (the lexicon's `limit` maximum). */
17
+ export const MAX_PAGE = 500;
18
+ /** The most URIs one `getRecords` call takes, and the most values one `in` list takes (the platform's
19
+ * `MAX_IN`). Separate from {@link MAX_PAGE}: a bigger page does not make a list longer. */
20
+ export const MAX_BATCH = 100;
17
21
  const paramsOf = (params) => (params && Object.keys(params).length ? JSON.stringify(params) : undefined);
18
22
  /** One page of `query`. */
19
23
  export function listRecords(read, query, call = {}) {
@@ -22,9 +26,19 @@ export function listRecords(read, query, call = {}) {
22
26
  params: paramsOf(call.params),
23
27
  limit: call.limit,
24
28
  cursor: call.cursor,
25
- count: call.count ? 'true' : undefined,
29
+ ...(call.count ? { count: 'true' } : {}),
26
30
  });
27
31
  }
32
+ /** One page of `query` and how many records it answers in all (`listRecords count=true`): the page and
33
+ * the count in one call. `limit: 1` is the cheap way to ask "how many" with a first record to show.
34
+ * Throws when the answer carries no numeric `count` (a platform that ignores `count`). */
35
+ export async function listRecordsCounted(read, query, call = {}) {
36
+ const page = await listRecords(read, query, { ...call, count: true });
37
+ // A platform before pub.10 ignores `count=true` and answers the page alone: never read that as 0.
38
+ if (typeof page.count !== 'number')
39
+ throw new Error('listRecords answered no count: the platform does not count (before pub.10)');
40
+ return { ...page, count: page.count, capped: page.capped === true };
41
+ }
28
42
  /** A page whose cursor came back again: paging would never end. */
29
43
  export class QueryNoProgressError extends Error {
30
44
  constructor() {
@@ -36,9 +50,10 @@ export class QueryNoProgressError extends Error {
36
50
  export const MAX_PAGES = 100;
37
51
  /**
38
52
  * The most characters one GET's query string may carry. Every read here is a GET (an XRPC query, and it
39
- * must pass a PDS's atproto-proxy as one), and proxies refuse a long request line: one in front of a test
40
- * PDS answered 414 past about 8 KB (nginx's default line buffer), and 100 AT-URIs in one `getRecords` or
41
- * one `in` list are ~11 KB. So a list is sent in runs that fit this as well as {@link MAX_PAGE}.
53
+ * must pass a PDS's atproto-proxy as one), and proxies refuse a long request line: staging's answered 414
54
+ * past about 8 KB (nginx's default line buffer), and 100 AT-URIs in one `getRecords` or one `in` list are
55
+ * ~11 KB. So a list is sent in runs that fit this as well as {@link MAX_BATCH}. A page's size
56
+ * ({@link MAX_PAGE}) is only the `limit` number and never lengthens the request.
42
57
  */
43
58
  export const MAX_QUERY_CHARS = 6000;
44
59
  /** What the path, `limit`, `handles` and a cursor may take beside the list. A cursor is `<sort key>~<uri>`
@@ -54,7 +69,7 @@ export function fixedChars(query, params = {}) {
54
69
  return (query ? formChars(JSON.stringify(query)) : 0) + formChars(JSON.stringify(params));
55
70
  }
56
71
  /**
57
- * `list` in runs of at most {@link MAX_PAGE} (what one `getRecords` call or one `in` takes) that also fit
72
+ * `list` in runs of at most {@link MAX_BATCH} (what one `getRecords` call or one `in` takes) that also fit
58
73
  * one GET ({@link MAX_QUERY_CHARS}) beside `fixed` characters of query and other params ({@link fixedChars}).
59
74
  * An item too long to fit with anything else goes alone.
60
75
  */
@@ -65,7 +80,7 @@ export function batches(list, fixed = 0) {
65
80
  let used = 0;
66
81
  for (const item of list) {
67
82
  const cost = itemChars(item);
68
- if (run.length > 0 && (run.length === MAX_PAGE || used + cost > budget)) {
83
+ if (run.length > 0 && (run.length === MAX_BATCH || used + cost > budget)) {
69
84
  out.push(run);
70
85
  run = [];
71
86
  used = 0;
@@ -114,36 +129,49 @@ export async function listAllRecordsFor(read, query, key, uris, params = {}) {
114
129
  export function countRecords(read, query, call = {}) {
115
130
  return read(NSID.QUERY_COUNT_RECORDS, { query: JSON.stringify(query), params: paramsOf(call.params), groupBy: call.groupBy });
116
131
  }
117
- /** `c` as a {@link Curation}, or `undefined` for a malformed one or a status this SDK does not know (the
118
- * guards are for the wire: a platform's answer is not held to the generated type). */
119
- function curationOf(c) {
132
+ /** `c` as a {@link Curation}, or `undefined` for a malformed one or a status this SDK does not know. */
133
+ export function curationOf(c) {
120
134
  if (!c || typeof c !== 'object')
121
135
  return undefined;
122
136
  const { uri, status, curated, reason } = c;
123
137
  if (typeof uri !== 'string')
124
138
  return undefined;
125
139
  if (status === 'pending')
126
- return { uri, status: 'pending' };
140
+ return { uri, status };
127
141
  if (status === 'curated' && typeof curated === 'string')
128
- return { uri, status: 'curated', curated };
142
+ return { uri, status, curated };
129
143
  if (status === 'notCurated')
130
- return { uri, status: 'notCurated', reason: typeof reason === 'string' ? reason : 'not curated' };
144
+ return { uri, status, reason: typeof reason === 'string' ? reason : 'not curated' };
131
145
  return undefined;
132
146
  }
147
+ /** A handle fit to show, trimmed: `undefined` when there is none, or when it is `handle.invalid` (any case),
148
+ * what atproto reports for an account whose handle does not verify, which names no one. */
149
+ export function shownHandle(handle) {
150
+ const h = handle?.trim();
151
+ return h && h.toLowerCase() !== 'handle.invalid' ? h : undefined;
152
+ }
133
153
  /** The records at `uris` the viewer may read, by URI, and which of the asked URIs were withheld. With
134
154
  * `handles`, also the public handle of each repo the URIs name; with `curation`, the curation status
135
- * of each asked URI that is the signed-in caller's own; with `defaults`, the starting value of each
136
- * missing record of the caller's own the platform has one for (no extra read: the same call answers
137
- * them). `includeBlockedByMe` lifts the caller's own blocks for this read (to name the people they
138
- * blocked). */
155
+ * of each asked URI that is the signed-in caller's own (no extra read: the same call answers it).
156
+ * Like every generic read, it leaves out records and handles across a block either way; `includeBlockedByMe`
157
+ * lifts only the caller's own blocks (naming the people they blocked). */
139
158
  export async function getRecordsAnswer(read, uris, opts = {}) {
140
- const flags = ['handles', 'curation', 'defaults', 'includeBlockedByMe'];
141
- const extra = Object.fromEntries(flags.filter((f) => opts[f]).map((f) => [f, 'true']));
159
+ const extra = {
160
+ ...(opts.handles ? { handles: 'true' } : {}),
161
+ ...(opts.curation ? { curation: 'true' } : {}),
162
+ ...(opts.defaults ? { defaults: 'true' } : {}),
163
+ ...(opts.includeBlockedByMe ? { includeBlockedByMe: 'true' } : {}),
164
+ };
142
165
  const pages = await Promise.all(batches([...new Set(uris)]).map((uris) => read(NSID.QUERY_GET_RECORDS, { uris, ...extra })));
166
+ return answerOf(pages);
167
+ }
168
+ /** One or more `getRecords` pages (or a composed get step's answer) as a {@link RecordsAnswer}. */
169
+ export function answerOf(pages) {
143
170
  const handles = new Map();
144
171
  for (const h of pages.flatMap((p) => (Array.isArray(p.handles) ? p.handles : []))) {
145
- if (typeof h?.did === 'string' && typeof h.handle === 'string')
146
- handles.set(h.did, h.handle);
172
+ const handle = typeof h?.did === 'string' && typeof h.handle === 'string' ? shownHandle(h.handle) : undefined;
173
+ if (handle)
174
+ handles.set(h.did, handle);
147
175
  }
148
176
  return {
149
177
  records: new Map(pages.flatMap((p) => p.records).map((r) => [r.uri, r])),
@@ -156,7 +184,7 @@ export async function getRecordsAnswer(read, uris, opts = {}) {
156
184
  .map((c) => [c.uri, c])),
157
185
  defaults: new Map(pages
158
186
  .flatMap((p) => (Array.isArray(p.defaults) ? p.defaults : []))
159
- .filter((d) => typeof d?.uri === 'string')
187
+ .filter((d) => typeof d?.uri === 'string' && d.value !== null && typeof d.value === 'object' && !Array.isArray(d.value))
160
188
  .map((d) => [d.uri, d.value])),
161
189
  };
162
190
  }
@@ -164,4 +192,5 @@ export async function getRecordsAnswer(read, uris, opts = {}) {
164
192
  export async function getRecords(read, uris) {
165
193
  return (await getRecordsAnswer(read, uris)).records;
166
194
  }
167
- export { CURATED_FROM_QUERY, curatedFor, hostsOf, listedOnOf, MIRROR_SIDECARS_QUERY, PROVENANCE_OF_QUERY, provenanceSourcesOf, publicWebUrl, } from './hosts.js';
195
+ export { CURATED_FROM_QUERY, curatedFor, curatedForAll, hostsFrom, hostsOf, HOST_ENVELOPE, hostSteps, listedOnOf, MIRROR_SIDECARS_QUERY, PROVENANCE_FIELDS, PROVENANCE_OF_QUERY, HOST_SOURCES_QUERY, provenanceSourcesOf, publicWebUrl, } from './hosts.js';
196
+ export { compose, Composed, ComposeStepError, Composition, COMPOSE_RETRIES, emulateCompose, ENVELOPE_FIELDS, ENVELOPE_ONLY, MAX_BOUND, MAX_STEP_LIMIT, MAX_STEP_URIS, MAX_STEPS, MAX_TOTAL_RECORDS, selectFields, testReader, withPost, } from './compose.js';