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.
- package/CHANGELOG.md +160 -0
- package/README.md +5 -4
- package/dist/auth/app-key.js +2 -2
- package/dist/auth/index.js +1 -1
- package/dist/catalog/catalog.gen.d.ts +24 -24
- package/dist/catalog/catalog.gen.js +356 -66
- package/dist/connect.d.ts +96 -12
- package/dist/connect.js +83 -12
- package/dist/generated/lexicons.d.ts +140 -36
- package/dist/generated/lexicons.js +77 -18
- package/dist/generated/nsid.d.ts +4 -0
- package/dist/generated/nsid.js +4 -0
- package/dist/generated/nsid.json +4 -0
- package/dist/generated/types/pub/techne/draft/beacon.d.ts +2 -0
- package/dist/generated/types/pub/techne/draft/collective.d.ts +1 -1
- package/dist/generated/types/pub/techne/draft/identity/attest.d.ts +3 -0
- package/dist/generated/types/pub/techne/draft/identity/attest.js +7 -0
- package/dist/generated/types/pub/techne/draft/identity/beginAddMethod.d.ts +3 -0
- package/dist/generated/types/pub/techne/draft/identity/beginAddMethod.js +7 -0
- package/dist/generated/types/pub/techne/draft/identity/finishAddMethod.d.ts +6 -0
- package/dist/generated/types/pub/techne/draft/identity/finishAddMethod.js +14 -0
- package/dist/generated/types/pub/techne/draft/identity/resolve.d.ts +6 -0
- package/dist/generated/types/pub/techne/draft/membership.d.ts +1 -1
- package/dist/generated/types/pub/techne/draft/permissioned/deleteRecord.d.ts +3 -0
- package/dist/generated/types/pub/techne/draft/permissioned/deleteRecord.js +7 -0
- package/dist/generated/types/pub/techne/draft/permissioned/putRecord.d.ts +3 -0
- package/dist/generated/types/pub/techne/draft/permissioned/putRecord.js +7 -0
- package/dist/generated/types/pub/techne/draft/permissioned/putRecords.d.ts +4 -1
- package/dist/generated/types/pub/techne/draft/permissioned/putRecords.js +7 -0
- package/dist/generated/types/pub/techne/draft/summary.d.ts +2 -0
- package/dist/item.d.ts +130 -0
- package/dist/item.js +74 -0
- package/dist/links/index.d.ts +15 -8
- package/dist/links/index.js +18 -0
- package/dist/put/contacts.d.ts +2 -2
- package/dist/put/index.d.ts +6 -9
- package/dist/put/index.js +8 -166
- package/dist/put/put.d.ts +14 -0
- package/dist/put/put.js +206 -0
- package/dist/query/compose.d.ts +246 -0
- package/dist/query/compose.js +572 -0
- package/dist/query/hosts.d.ts +98 -1
- package/dist/query/hosts.js +143 -2
- package/dist/query/index.d.ts +60 -29
- package/dist/query/index.js +55 -26
- package/dist/react/context.d.ts +18 -0
- package/dist/react/context.js +19 -0
- package/dist/react/index.d.ts +14 -0
- package/dist/react/index.js +14 -0
- package/dist/react/query.d.ts +75 -0
- package/dist/react/query.js +116 -0
- package/dist/read/index.d.ts +60 -0
- package/dist/read/index.js +107 -0
- package/dist/resend.d.ts +25 -0
- package/dist/resend.js +52 -0
- package/dist/versions/entities.gen.d.ts +8 -0
- package/dist/versions/entities.gen.js +9 -0
- package/dist/versions/index.d.ts +59 -17
- package/dist/versions/index.js +156 -22
- package/dist/versions/react.d.ts +1 -1
- package/dist/versions/react.js +1 -1
- package/dist/versions/text.d.ts +19 -0
- package/dist/versions/text.js +73 -0
- package/dist/wasm/techne-wasm.gen.js +1 -1
- package/dist/wasm/techne-wasm2js.gen.js +8928 -8927
- package/package.json +17 -5
|
@@ -0,0 +1,572 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `pub.techne.draft.query.composeRecords` from the SDK (CQ2): several generic reads in one request, where a
|
|
3
|
+
* later step reads what an earlier one answered.
|
|
4
|
+
*
|
|
5
|
+
* A composition is built step by step and sent once:
|
|
6
|
+
*
|
|
7
|
+
* ```ts
|
|
8
|
+
* const c = compose()
|
|
9
|
+
* const events = c.list('events', FEED_QUERY, { params, limit: 500 })
|
|
10
|
+
* const prov = c.list('prov', PROVENANCE_OF_QUERY, { params: { uris: events.uri }, fields: ['subject', 'sources[].uri'] })
|
|
11
|
+
* const sources = c.get('sources', [prov.value('sources[].uri')], { fields: ENVELOPE_ONLY })
|
|
12
|
+
* const answer = await c.run(post)
|
|
13
|
+
* answer.list(events).records // a ListPage
|
|
14
|
+
* answer.records(sources) // a Map by URI
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* A step's handle names its outputs as bindings (`events.uri` is the string `"$events.uri"`), which the platform
|
|
18
|
+
* fills with that output over the earlier step's answered records (deduplicated, first seen first; possibly
|
|
19
|
+
* empty). A step asked with `return: false` only feeds later bindings: its handle cannot be read from the answer
|
|
20
|
+
* (a compile error). `fields` keeps only those value paths of each answered record, and `envelope` only those of
|
|
21
|
+
* its own fields ({@link ENVELOPE_FIELDS}: `cid`, `author` and the rest; every field without it); `uri: false`
|
|
22
|
+
* drops the record's `uri` too (`value` always comes back); bindings read the whole record, before any cut.
|
|
23
|
+
*
|
|
24
|
+
* The platform's rules (the lexicon's): at most {@link MAX_STEPS} steps; a list step's `limit` at most
|
|
25
|
+
* {@link MAX_STEP_LIMIT} (past {@link MAX_PAGE}, one `listRecords` page, the platform reads the pages and answers
|
|
26
|
+
* them as one); a `return: false` list step is read in full (no `limit` or `cursor`; past {@link MAX_STEP_LIMIT}
|
|
27
|
+
* records it fails); a get step at most {@link MAX_STEP_URIS} URIs after binding; a bound list at most
|
|
28
|
+
* {@link MAX_BOUND} values; at most {@link MAX_TOTAL_RECORDS} records across the one-page steps. A signed-in caller spends
|
|
29
|
+
* a row budget: `run` waits and asks again on `RateLimitExceeded` ({@link COMPOSE_RETRIES} times).
|
|
30
|
+
*
|
|
31
|
+
* **A failed step fails alone.** The platform answers a step it could not answer in `errors` (its own error, or
|
|
32
|
+
* `Skipped` when a step it binds to failed) and every other step as usual. A step built with `optional: true` (a
|
|
33
|
+
* decoration a screen can show without) then reads as empty, and {@link Composed.failed} names its error; any
|
|
34
|
+
* other step's failure fails `run` with that step's error ({@link ComposeStepError}), as a failed call would.
|
|
35
|
+
*
|
|
36
|
+
* The wire is plain data, so a stand-in platform can answer it from its own `listRecords` and `getRecords`
|
|
37
|
+
* ({@link emulateCompose}): tests and Beacon's dev seed do. It is not the platform: `references` and `subject`
|
|
38
|
+
* come from the type's query document there; the emulation reads `subject` (or `subject.uri`) and refuses
|
|
39
|
+
* `references`.
|
|
40
|
+
*/
|
|
41
|
+
import { NSID } from '../generated/nsid.js';
|
|
42
|
+
import { answerOf, MAX_PAGE, } from './index.js';
|
|
43
|
+
/** `read` as a {@link Reader} posting with `post` (a new function: `read` itself is left alone). */
|
|
44
|
+
export function withPost(read, post) {
|
|
45
|
+
const reader = ((nsid, params) => read(nsid, params));
|
|
46
|
+
return Object.assign(reader, { post });
|
|
47
|
+
}
|
|
48
|
+
/** A stand-in platform's GET reader as a {@link Reader} whose POST answers `composeRecords` from those GETs
|
|
49
|
+
* ({@link emulateCompose}): for tests and dev seeds, never the platform. */
|
|
50
|
+
export function testReader(read, otherwise) {
|
|
51
|
+
return withPost(read, emulateCompose(read, otherwise));
|
|
52
|
+
}
|
|
53
|
+
/** The most steps one call takes. */
|
|
54
|
+
export const MAX_STEPS = 12;
|
|
55
|
+
/** The most URIs one get step names, after its bindings are filled in. */
|
|
56
|
+
export const MAX_STEP_URIS = 500;
|
|
57
|
+
/** The most values one bound list holds. */
|
|
58
|
+
export const MAX_BOUND = 2000;
|
|
59
|
+
/** The most records the one-page steps of one call answer in all: a list step whose `limit` is over
|
|
60
|
+
* {@link MAX_PAGE}, or that is `return: false`, is not counted (its own limit bounds it). */
|
|
61
|
+
export const MAX_TOTAL_RECORDS = 3000;
|
|
62
|
+
/** The largest `limit` a list step takes, and the most records a `return: false` list step (read in full) may
|
|
63
|
+
* match before it fails. A step read for all of its records asks this and treats a cursor back as an error. */
|
|
64
|
+
export const MAX_STEP_LIMIT = 50_000;
|
|
65
|
+
/** How many times `run` asks again after the platform answers `RateLimitExceeded` (the row budget refills at
|
|
66
|
+
* 500 rows a second, and a call is charged at most 3000). */
|
|
67
|
+
export const COMPOSE_RETRIES = 2;
|
|
68
|
+
/** `fields` that keep no value: a path no record has. For a step whose records count only by being there
|
|
69
|
+
* (a host's live source). */
|
|
70
|
+
export const ENVELOPE_ONLY = ['_'];
|
|
71
|
+
/** The record fields a step's `envelope` may keep besides `uri` (kept unless the step asks `uri: false`) and
|
|
72
|
+
* `value` (always kept). */
|
|
73
|
+
export const ENVELOPE_FIELDS = ['cid', 'author', 'collection', 'time', 'space', 'source', 'curated', 'held', 'measures', 'signals'];
|
|
74
|
+
const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
75
|
+
/** `e` as a {@link StepError} when it is one; `undefined` otherwise. */
|
|
76
|
+
function stepErrorOf(e) {
|
|
77
|
+
if (!isRecord(e))
|
|
78
|
+
return undefined;
|
|
79
|
+
const { error, message, status } = e;
|
|
80
|
+
return typeof error === 'string' && typeof message === 'string' && typeof status === 'number' ? { error, message, status } : undefined;
|
|
81
|
+
}
|
|
82
|
+
/** The answer's `errors`, each entry a {@link StepError}: a malformed one reads as a generic failure of its step,
|
|
83
|
+
* never as an answer. */
|
|
84
|
+
function stepErrorsOf(errors) {
|
|
85
|
+
if (!isRecord(errors))
|
|
86
|
+
return {};
|
|
87
|
+
return Object.fromEntries(Object.entries(errors).map(([step, e]) => [step, stepErrorOf(e) ?? { error: 'InternalError', message: `step ${step}: failed (malformed error)`, status: 500 }]));
|
|
88
|
+
}
|
|
89
|
+
/** A required step of a composed call failed: the call fails as that step's method would have alone. */
|
|
90
|
+
export class ComposeStepError extends Error {
|
|
91
|
+
step;
|
|
92
|
+
status;
|
|
93
|
+
error;
|
|
94
|
+
constructor(step, e) {
|
|
95
|
+
super(e.message);
|
|
96
|
+
this.step = step;
|
|
97
|
+
this.name = 'ComposeStepError';
|
|
98
|
+
this.status = e.status;
|
|
99
|
+
this.error = e.error;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const STEP_NAME = /^[A-Za-z][A-Za-z0-9_]{0,31}$/;
|
|
103
|
+
const isBinding = (v) => typeof v === 'string' && v.startsWith('$');
|
|
104
|
+
function ref(name, kind, returned) {
|
|
105
|
+
const b = (o) => `$${name}.${o}`;
|
|
106
|
+
return { name, kind, returned, uri: b('uri'), author: b('author'), type: b('type'), space: b('space'), subject: b('subject'), references: b('references'), value: (p) => b(`value.${p}`) };
|
|
107
|
+
}
|
|
108
|
+
/** The step a binding names. */
|
|
109
|
+
const stepOf = (b) => b.slice(1).split('.')[0];
|
|
110
|
+
/** One `composeRecords` call being built. Steps run in the order added; a binding names only an earlier step. */
|
|
111
|
+
export class Composition {
|
|
112
|
+
#steps = [];
|
|
113
|
+
/** The steps built `optional`. */
|
|
114
|
+
#optional = new Set();
|
|
115
|
+
/** Steps left out because they could ask for nothing (a get step with no URIs, a param bound only to such
|
|
116
|
+
* steps): their answer is empty, and a step binding only to them is left out too. */
|
|
117
|
+
#empty = new Set();
|
|
118
|
+
/** The steps as they will be sent. */
|
|
119
|
+
get steps() {
|
|
120
|
+
return this.#steps;
|
|
121
|
+
}
|
|
122
|
+
#name(name) {
|
|
123
|
+
if (!STEP_NAME.test(name))
|
|
124
|
+
throw new Error(`compose: a step name is a letter then up to 31 letters, digits or _, not "${name}"`);
|
|
125
|
+
if (this.#steps.some((s) => s.name === name) || this.#empty.has(name))
|
|
126
|
+
throw new Error(`compose: step ${name} is used twice`);
|
|
127
|
+
}
|
|
128
|
+
/** `entries` with bindings to left-out steps dropped (they fill nothing). */
|
|
129
|
+
#live(entries) {
|
|
130
|
+
return entries.filter((e) => !(isBinding(e) && this.#empty.has(stepOf(e))));
|
|
131
|
+
}
|
|
132
|
+
#checkBinding(step, b) {
|
|
133
|
+
if (!this.#steps.some((s) => s.name === stepOf(b)) && !this.#empty.has(stepOf(b)))
|
|
134
|
+
throw new Error(`compose: step ${step} binds ${b}, which names no earlier step`);
|
|
135
|
+
}
|
|
136
|
+
/** A list step: one `listRecords` page of `query` (inline, or a published query's AT-URI). */
|
|
137
|
+
list(name, query, opts = {}) {
|
|
138
|
+
this.#name(name);
|
|
139
|
+
const returned = (opts.return ?? true);
|
|
140
|
+
const params = {};
|
|
141
|
+
let leftOut = false;
|
|
142
|
+
for (const [k, v] of Object.entries(opts.params ?? {})) {
|
|
143
|
+
const items = Array.isArray(v) ? v : [v];
|
|
144
|
+
const bound = items.filter(isBinding);
|
|
145
|
+
bound.forEach((b) => this.#checkBinding(name, b));
|
|
146
|
+
if (bound.length === 0) {
|
|
147
|
+
params[k] = v;
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
const live = this.#live(items);
|
|
151
|
+
// Every binding names a left-out step and nothing literal remains: the param is an empty list, which
|
|
152
|
+
// matches nothing. The platform takes that, but only from a binding: leave the step out instead.
|
|
153
|
+
if (live.length === 0)
|
|
154
|
+
leftOut = true;
|
|
155
|
+
params[k] = Array.isArray(v) ? live : live[0];
|
|
156
|
+
}
|
|
157
|
+
if (opts.limit !== undefined && (opts.limit < 1 || opts.limit > MAX_STEP_LIMIT))
|
|
158
|
+
throw new Error(`compose: step ${name}'s limit must be within 1..=${MAX_STEP_LIMIT}`);
|
|
159
|
+
if (!returned && (opts.limit !== undefined || opts.cursor !== undefined))
|
|
160
|
+
throw new Error(`compose: step ${name} is return: false, read in full: it takes no limit or cursor`);
|
|
161
|
+
if (leftOut) {
|
|
162
|
+
this.#empty.add(name);
|
|
163
|
+
return ref(name, 'list', returned);
|
|
164
|
+
}
|
|
165
|
+
this.#steps.push({
|
|
166
|
+
name,
|
|
167
|
+
...('queryUri' in query && typeof query.queryUri === 'string' ? { queryUri: query.queryUri } : { query }),
|
|
168
|
+
...(Object.keys(params).length ? { params } : {}),
|
|
169
|
+
...(opts.limit !== undefined ? { limit: opts.limit } : {}),
|
|
170
|
+
...(opts.cursor !== undefined ? { cursor: opts.cursor } : {}),
|
|
171
|
+
...(opts.count ? { count: true } : {}),
|
|
172
|
+
...(opts.handles ? { handles: true } : {}),
|
|
173
|
+
...(opts.curation ? { curation: true } : {}),
|
|
174
|
+
...common(opts),
|
|
175
|
+
});
|
|
176
|
+
if (opts.optional)
|
|
177
|
+
this.#optional.add(name);
|
|
178
|
+
return ref(name, 'list', returned);
|
|
179
|
+
}
|
|
180
|
+
/** A get step: `getRecords` of `uris`, each an AT-URI or a binding (deduplicated). No URIs (or only bindings
|
|
181
|
+
* to left-out steps): the step is left out and answers nothing. */
|
|
182
|
+
get(name, uris, opts = {}) {
|
|
183
|
+
this.#name(name);
|
|
184
|
+
const returned = (opts.return ?? true);
|
|
185
|
+
const all = [...new Set(uris)];
|
|
186
|
+
all.filter(isBinding).forEach((b) => this.#checkBinding(name, b));
|
|
187
|
+
const live = this.#live(all);
|
|
188
|
+
if (live.length === 0) {
|
|
189
|
+
this.#empty.add(name);
|
|
190
|
+
return ref(name, 'get', returned);
|
|
191
|
+
}
|
|
192
|
+
if (live.length > MAX_STEP_URIS)
|
|
193
|
+
throw new Error(`compose: step ${name} names ${live.length} URIs, more than ${MAX_STEP_URIS}`);
|
|
194
|
+
this.#steps.push({
|
|
195
|
+
name,
|
|
196
|
+
uris: live,
|
|
197
|
+
...(opts.curated ? { curated: true } : {}),
|
|
198
|
+
...(opts.handles ? { handles: true } : {}),
|
|
199
|
+
...(opts.curation ? { curation: true } : {}),
|
|
200
|
+
...(opts.defaults ? { defaults: true } : {}),
|
|
201
|
+
...(opts.includeBlockedByMe ? { includeBlockedByMe: true } : {}),
|
|
202
|
+
...common(opts),
|
|
203
|
+
});
|
|
204
|
+
if (opts.optional)
|
|
205
|
+
this.#optional.add(name);
|
|
206
|
+
return ref(name, 'get', returned);
|
|
207
|
+
}
|
|
208
|
+
/** Send the steps (one POST) and answer them. No steps left (every one could ask for nothing): no call.
|
|
209
|
+
* A step that failed and is not `optional` fails the run ({@link ComposeStepError}, the first in step
|
|
210
|
+
* order). `sleep` waits between retries (a test's stand-in; a timer otherwise). */
|
|
211
|
+
async run(post, opts = {}) {
|
|
212
|
+
const sleep = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
213
|
+
if (this.#steps.length > MAX_STEPS)
|
|
214
|
+
throw new Error(`compose: ${this.#steps.length} steps, more than ${MAX_STEPS}`);
|
|
215
|
+
if (this.#steps.length === 0)
|
|
216
|
+
return new Composed({});
|
|
217
|
+
for (let attempt = 0;; attempt++) {
|
|
218
|
+
try {
|
|
219
|
+
const out = await post(NSID.QUERY_COMPOSE_RECORDS, { steps: this.#steps });
|
|
220
|
+
const errors = stepErrorsOf(out?.errors);
|
|
221
|
+
for (const s of this.#steps) {
|
|
222
|
+
const e = errors[s.name];
|
|
223
|
+
if (e && !this.#optional.has(s.name))
|
|
224
|
+
throw new ComposeStepError(s.name, e);
|
|
225
|
+
}
|
|
226
|
+
return new Composed(isRecord(out?.steps) ? out.steps : {}, errors);
|
|
227
|
+
}
|
|
228
|
+
catch (e) {
|
|
229
|
+
if (attempt >= COMPOSE_RETRIES || !rateLimited(e))
|
|
230
|
+
throw e;
|
|
231
|
+
await sleep(1000 * (attempt + 1));
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
function common(opts) {
|
|
237
|
+
// The type keeps a caller to ENVELOPE_FIELDS; this keeps one that reached here untyped (JS, a cast) from a
|
|
238
|
+
// step the platform refuses.
|
|
239
|
+
for (const f of opts.envelope ?? []) {
|
|
240
|
+
if (!isEnvelopeField(f))
|
|
241
|
+
throw new Error(`envelope names ${f}, not one of ${ENVELOPE_FIELDS.join(', ')} (uri is the step's uri flag; value always comes back)`);
|
|
242
|
+
}
|
|
243
|
+
if (opts.uri !== undefined && typeof opts.uri !== 'boolean')
|
|
244
|
+
throw new Error('uri is a boolean');
|
|
245
|
+
return {
|
|
246
|
+
...(opts.return === false ? { return: false } : {}),
|
|
247
|
+
...(opts.fields ? { fields: [...opts.fields] } : {}),
|
|
248
|
+
...(opts.envelope ? { envelope: [...opts.envelope] } : {}),
|
|
249
|
+
// Not asked (or true): the platform's default, the uri comes back.
|
|
250
|
+
...(opts.uri === false ? { uri: false } : {}),
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
const isEnvelopeField = (f) => ENVELOPE_FIELDS.includes(f);
|
|
254
|
+
/** `r` as the wire answers it with only `uri` (unless `keepUri` is false), `value` and the `envelope` fields (all
|
|
255
|
+
* of them without one): the platform's cut. Plain JSON: the emulated answer is read back as the platform's would be. */
|
|
256
|
+
function cutEnvelope(r, envelope, keepUri = true) {
|
|
257
|
+
return Object.fromEntries(Object.entries(r).filter(([k]) => (k === 'uri' ? keepUri : k === 'value' || !envelope || envelope.some((f) => f === k))));
|
|
258
|
+
}
|
|
259
|
+
/** An error's HTTP status, whatever client threw it: `status` (the app's error, `@atproto/xrpc`'s XRPCError, whose
|
|
260
|
+
* `ResponseType` is the HTTP code) or `statusCode` (an `http-errors`-like error, which XRPCError.from reads too). */
|
|
261
|
+
function statusOf(e) {
|
|
262
|
+
const s = typeof e.status === 'number' ? e.status : e.statusCode;
|
|
263
|
+
return typeof s === 'number' ? s : undefined;
|
|
264
|
+
}
|
|
265
|
+
/** An error's XRPC name, at the top (XRPCError) or in `body` (the app's error). */
|
|
266
|
+
const errorNameOf = (e) => (typeof e.error === 'string' ? e.error : isRecord(e.body) && typeof e.body.error === 'string' ? e.body.error : undefined);
|
|
267
|
+
/** The platform refused the caller (401: not signed in or a bad credential; 429: its budget), whatever client threw
|
|
268
|
+
* it: a whole call's failure, never a step's. A 401 by its status or by its name (`AuthenticationRequired`, the
|
|
269
|
+
* app's `AuthRequired`), read as {@link rateLimited} reads a 429 (B453). */
|
|
270
|
+
function callRefused(e) {
|
|
271
|
+
if (rateLimited(e))
|
|
272
|
+
return true;
|
|
273
|
+
if (!isRecord(e))
|
|
274
|
+
return false;
|
|
275
|
+
const name = errorNameOf(e);
|
|
276
|
+
return statusOf(e) === 401 || name === 'AuthenticationRequired' || name === 'AuthRequired';
|
|
277
|
+
}
|
|
278
|
+
/** The platform refused the call for the caller's row budget (429 `RateLimitExceeded`), whatever client threw it. */
|
|
279
|
+
function rateLimited(e) {
|
|
280
|
+
if (!isRecord(e))
|
|
281
|
+
return false;
|
|
282
|
+
return statusOf(e) === 429 || errorNameOf(e) === 'RateLimitExceeded';
|
|
283
|
+
}
|
|
284
|
+
/** A new composition. */
|
|
285
|
+
export const compose = () => new Composition();
|
|
286
|
+
/** A `composeRecords` answer, read by step. A step left out (it could ask for nothing), or an optional one
|
|
287
|
+
* that failed, answers empty. */
|
|
288
|
+
export class Composed {
|
|
289
|
+
#steps;
|
|
290
|
+
#errors;
|
|
291
|
+
constructor(steps, errors = {}) {
|
|
292
|
+
this.#steps = steps;
|
|
293
|
+
this.#errors = errors;
|
|
294
|
+
}
|
|
295
|
+
/** Why `step` has no answer: its error, or `Skipped` for a step it binds to; `undefined` when it answered
|
|
296
|
+
* (or was left out unsent). Only an `optional` step can have failed in an answer `run` gave. */
|
|
297
|
+
failed(step) {
|
|
298
|
+
return this.#errors[step.name];
|
|
299
|
+
}
|
|
300
|
+
#raw(name) {
|
|
301
|
+
const s = this.#steps[name];
|
|
302
|
+
return isRecord(s) ? s : {};
|
|
303
|
+
}
|
|
304
|
+
/** A list step's page: its records (value cut to its `fields`), cursor and, asked with `count`, count; asked
|
|
305
|
+
* with `handles` or `curation`, those of the records it answered. */
|
|
306
|
+
list(step) {
|
|
307
|
+
const s = this.#raw(step.name);
|
|
308
|
+
return { ...s, records: Array.isArray(s.records) ? s.records : [] };
|
|
309
|
+
}
|
|
310
|
+
/** A list step asked {@link MAX_STEP_LIMIT} records: all of them. A step that still answers a cursor matched more
|
|
311
|
+
* than the platform reads in one step, and this throws (`<who>: step <name> matched more than …`) rather than
|
|
312
|
+
* answer part of the list. */
|
|
313
|
+
whole(step, who) {
|
|
314
|
+
const page = this.list(step);
|
|
315
|
+
if (page.cursor)
|
|
316
|
+
throw new Error(`${who}: step ${step.name} matched more than ${MAX_STEP_LIMIT} records`);
|
|
317
|
+
return page.records;
|
|
318
|
+
}
|
|
319
|
+
/** A get step's answer as `getRecordsAnswer` gives it: records by URI, withheld, handles, curation, defaults.
|
|
320
|
+
* Only a step that keeps its records' `uri`. */
|
|
321
|
+
answer(step) {
|
|
322
|
+
const s = this.#raw(step.name);
|
|
323
|
+
return answerOf([{ ...s, records: Array.isArray(s.records) ? s.records : [] }]);
|
|
324
|
+
}
|
|
325
|
+
/** A step's records in the order answered, list or get: the read for a step asked `uri: false`, whose records
|
|
326
|
+
* {@link records} cannot key by URI. */
|
|
327
|
+
answered(step) {
|
|
328
|
+
const s = this.#raw(step.name);
|
|
329
|
+
return Array.isArray(s.records) ? s.records : [];
|
|
330
|
+
}
|
|
331
|
+
/** A step's records by URI: only a step that keeps their `uri`. */
|
|
332
|
+
records(step) {
|
|
333
|
+
const s = this.#raw(step.name);
|
|
334
|
+
return new Map((Array.isArray(s.records) ? s.records : []).map((r) => [r.uri, r]));
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
// ── a stand-in's answer ─────────────────────────────────────────────────────────────────────────────
|
|
338
|
+
/** The values at a value path (`a`, `a.b`, `a[].b`), as the platform reads them. */
|
|
339
|
+
function at(value, path) {
|
|
340
|
+
let here = [value];
|
|
341
|
+
for (const seg of path.split('.')) {
|
|
342
|
+
const each = seg.endsWith('[]');
|
|
343
|
+
const name = each ? seg.slice(0, -2) : seg;
|
|
344
|
+
here = here.flatMap((v) => {
|
|
345
|
+
const got = v && typeof v === 'object' && !Array.isArray(v) ? v[name] : undefined;
|
|
346
|
+
if (got === undefined)
|
|
347
|
+
return [];
|
|
348
|
+
return each ? (Array.isArray(got) ? got : []) : [got];
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
return here;
|
|
352
|
+
}
|
|
353
|
+
/** `value` keeping only what `paths` reach (the platform's `select`). */
|
|
354
|
+
export function selectFields(value, paths) {
|
|
355
|
+
const tree = { whole: false, children: new Map() };
|
|
356
|
+
for (const path of paths) {
|
|
357
|
+
let node = tree;
|
|
358
|
+
for (const seg of path.split('.')) {
|
|
359
|
+
if (node.whole)
|
|
360
|
+
break;
|
|
361
|
+
if (!node.children.has(seg))
|
|
362
|
+
node.children.set(seg, { whole: false, children: new Map() });
|
|
363
|
+
node = node.children.get(seg);
|
|
364
|
+
}
|
|
365
|
+
node.whole = true;
|
|
366
|
+
node.children.clear();
|
|
367
|
+
}
|
|
368
|
+
const keep = (v, t) => {
|
|
369
|
+
if (t.whole)
|
|
370
|
+
return v;
|
|
371
|
+
if (!v || typeof v !== 'object' || Array.isArray(v))
|
|
372
|
+
return undefined;
|
|
373
|
+
const out = {};
|
|
374
|
+
for (const [seg, child] of t.children) {
|
|
375
|
+
const each = seg.endsWith('[]');
|
|
376
|
+
const name = each ? seg.slice(0, -2) : seg;
|
|
377
|
+
const got = v[name];
|
|
378
|
+
if (got === undefined)
|
|
379
|
+
continue;
|
|
380
|
+
if (each) {
|
|
381
|
+
if (!Array.isArray(got))
|
|
382
|
+
continue;
|
|
383
|
+
const kept = got.map((g) => keep(g, child)).filter((g) => g !== undefined);
|
|
384
|
+
out[name] = kept;
|
|
385
|
+
}
|
|
386
|
+
else {
|
|
387
|
+
const kept = keep(got, child);
|
|
388
|
+
if (kept !== undefined)
|
|
389
|
+
out[name] = kept;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
return Object.keys(out).length ? out : undefined;
|
|
393
|
+
};
|
|
394
|
+
return keep(value, tree) ?? {};
|
|
395
|
+
}
|
|
396
|
+
function outputOf(r, output) {
|
|
397
|
+
switch (output) {
|
|
398
|
+
case 'uri':
|
|
399
|
+
return [r.uri];
|
|
400
|
+
case 'author':
|
|
401
|
+
return [r.author];
|
|
402
|
+
case 'type':
|
|
403
|
+
return [r.collection];
|
|
404
|
+
case 'space':
|
|
405
|
+
return r.space ? [r.space] : [];
|
|
406
|
+
case 'subject': {
|
|
407
|
+
const s = r.value.subject;
|
|
408
|
+
const uri = typeof s === 'string' ? s : s && typeof s === 'object' ? s.uri : undefined;
|
|
409
|
+
return typeof uri === 'string' ? [uri] : [];
|
|
410
|
+
}
|
|
411
|
+
default:
|
|
412
|
+
if (output.startsWith('value.'))
|
|
413
|
+
return at(r.value, output.slice('value.'.length)).filter((v) => typeof v === 'string');
|
|
414
|
+
throw new Error(`emulateCompose: output ${output} is the platform's (from the type's query document)`);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
/** A list step the platform reads past one page: `return: false`, or a `limit` over {@link MAX_PAGE}. */
|
|
418
|
+
const pagedStep = (s) => !Array.isArray(s.uris) && (s.return === false || (typeof s.limit === 'number' && s.limit > MAX_PAGE));
|
|
419
|
+
/**
|
|
420
|
+
* A {@link ComposePoster} that answers `composeRecords` from a stand-in platform's `listRecords` and
|
|
421
|
+
* `getRecords` (the steps in order; a list step one page, or as many as the platform reads: its `limit` past one
|
|
422
|
+
* page, every page of a `return: false` step): for tests and dev seeds, never the platform. Any
|
|
423
|
+
* other POST goes to `otherwise` (or is refused). A stand-in read refused with 401 or 429 fails the whole call
|
|
424
|
+
* (thrown as is), as the platform refuses the caller before any step; any other failure is the step's.
|
|
425
|
+
*/
|
|
426
|
+
export function emulateCompose(read, otherwise) {
|
|
427
|
+
return async (nsid, body) => {
|
|
428
|
+
if (nsid !== NSID.QUERY_COMPOSE_RECORDS) {
|
|
429
|
+
if (otherwise)
|
|
430
|
+
return otherwise(nsid, body);
|
|
431
|
+
throw new Error(`emulateCompose: no stand-in for ${nsid}`);
|
|
432
|
+
}
|
|
433
|
+
const steps = (body?.steps ?? []);
|
|
434
|
+
const answered = new Map();
|
|
435
|
+
const out = {};
|
|
436
|
+
const errors = {};
|
|
437
|
+
const roots = new Map();
|
|
438
|
+
let total = 0;
|
|
439
|
+
// The records the call's steps read past one page have read so far: at most MAX_STEP_LIMIT in all.
|
|
440
|
+
let paged = 0;
|
|
441
|
+
const fill = (entries) => {
|
|
442
|
+
const vals = [];
|
|
443
|
+
for (const e of entries) {
|
|
444
|
+
if (isBinding(e)) {
|
|
445
|
+
const [step, ...rest] = e.slice(1).split('.');
|
|
446
|
+
for (const r of answered.get(step) ?? [])
|
|
447
|
+
vals.push(...outputOf(r, rest.join('.')));
|
|
448
|
+
}
|
|
449
|
+
else if (typeof e === 'string')
|
|
450
|
+
vals.push(e);
|
|
451
|
+
}
|
|
452
|
+
return [...new Set(vals)];
|
|
453
|
+
};
|
|
454
|
+
const bindingsOf = (s) => [...(Array.isArray(s.uris) ? s.uris : []), ...Object.values((s.params ?? {})).flat()].filter(isBinding).map(stepOf);
|
|
455
|
+
const refuse = (message) => {
|
|
456
|
+
throw Object.assign(new Error(message), { status: 400, error: 'InvalidRequest' });
|
|
457
|
+
};
|
|
458
|
+
for (const s of steps) {
|
|
459
|
+
// As the platform: a step bound to a failed one is skipped, naming the root failure (the step that failed
|
|
460
|
+
// itself, never a skipped one between); any other failure is the step's alone.
|
|
461
|
+
const failedDep = bindingsOf(s).find((d) => errors[d]);
|
|
462
|
+
if (failedDep) {
|
|
463
|
+
roots.set(s.name, roots.get(failedDep) ?? failedDep);
|
|
464
|
+
errors[s.name] = { error: 'Skipped', message: `step ${s.name}: skipped because ${roots.get(s.name)} failed`, status: 424 };
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
467
|
+
try {
|
|
468
|
+
let result;
|
|
469
|
+
if (Array.isArray(s.uris)) {
|
|
470
|
+
const uris = fill(s.uris);
|
|
471
|
+
if (uris.length > MAX_STEP_URIS)
|
|
472
|
+
refuse(`a get step takes at most ${MAX_STEP_URIS} URIs, its bindings fill ${uris.length}`);
|
|
473
|
+
const extra = Object.fromEntries(['curated', 'handles', 'curation', 'defaults', 'includeBlockedByMe'].filter((k) => s[k]).map((k) => [k, 'true']));
|
|
474
|
+
result = uris.length ? await read(NSID.QUERY_GET_RECORDS, { uris, ...extra }) : { records: [] };
|
|
475
|
+
}
|
|
476
|
+
else {
|
|
477
|
+
const params = {};
|
|
478
|
+
for (const [k, v] of Object.entries((s.params ?? {}))) {
|
|
479
|
+
const items = Array.isArray(v) ? v : [v];
|
|
480
|
+
if (items.some(isBinding)) {
|
|
481
|
+
const filled = fill(items);
|
|
482
|
+
if (filled.length > MAX_BOUND)
|
|
483
|
+
refuse(`param ${k} is bound to ${filled.length} values, more than ${MAX_BOUND}`);
|
|
484
|
+
params[k] = filled;
|
|
485
|
+
}
|
|
486
|
+
else
|
|
487
|
+
params[k] = v;
|
|
488
|
+
}
|
|
489
|
+
const query = s.queryUri ? undefined : JSON.stringify(s.query);
|
|
490
|
+
const page = (limit, cursor, count) => read(NSID.QUERY_LIST_RECORDS, {
|
|
491
|
+
...(query ? { query } : { queryUri: s.queryUri }),
|
|
492
|
+
params: Object.keys(params).length ? JSON.stringify(params) : undefined,
|
|
493
|
+
limit,
|
|
494
|
+
cursor,
|
|
495
|
+
...(count ? { count: 'true' } : {}),
|
|
496
|
+
});
|
|
497
|
+
if (pagedStep(s)) {
|
|
498
|
+
// As the platform: pages of at most MAX_PAGE, the last only what the limit still wants; a bind-only
|
|
499
|
+
// step reads one past its ceiling, and answering it fails the step.
|
|
500
|
+
// A cursor that comes back twice fails the step (InternalError), and so does a page that takes the call's
|
|
501
|
+
// paged reads past MAX_STEP_LIMIT (InvalidRequest; a bind-only step past its own ceiling says so).
|
|
502
|
+
const want = s.return === false ? MAX_STEP_LIMIT + 1 : typeof s.limit === 'number' ? s.limit : MAX_PAGE;
|
|
503
|
+
// The step's own rows are among the call's, so a bind-only step past its ceiling fails here too.
|
|
504
|
+
const tally = (got, stepTotal) => {
|
|
505
|
+
paged += got;
|
|
506
|
+
if (paged <= MAX_STEP_LIMIT)
|
|
507
|
+
return;
|
|
508
|
+
if (s.return === false && stepTotal > MAX_STEP_LIMIT)
|
|
509
|
+
refuse(`a \`return: false\` step is read in full, at most ${MAX_STEP_LIMIT} records, and this one's query matches more`);
|
|
510
|
+
refuse(`the steps read past one page read more than ${MAX_STEP_LIMIT} records in all`);
|
|
511
|
+
};
|
|
512
|
+
const first = await page(Math.min(MAX_PAGE, want), s.cursor, Boolean(s.count));
|
|
513
|
+
const all = [...(first?.records ?? [])];
|
|
514
|
+
tally(all.length, all.length);
|
|
515
|
+
const seen = new Set(typeof s.cursor === 'string' ? [s.cursor] : []);
|
|
516
|
+
let next = first?.cursor;
|
|
517
|
+
while (next && all.length < want) {
|
|
518
|
+
if (seen.has(next))
|
|
519
|
+
throw Object.assign(new Error('reading it page by page, a page came back with a cursor already read'), { status: 500, error: 'InternalError' });
|
|
520
|
+
seen.add(next);
|
|
521
|
+
const more = await page(Math.min(MAX_PAGE, want - all.length), next, false);
|
|
522
|
+
const got = more?.records ?? [];
|
|
523
|
+
all.push(...got);
|
|
524
|
+
tally(got.length, all.length);
|
|
525
|
+
next = more?.cursor;
|
|
526
|
+
}
|
|
527
|
+
const { cursor: _first, ...rest } = first ?? { records: [] };
|
|
528
|
+
result = { ...rest, records: all, ...(s.return !== false && next ? { cursor: next } : {}) };
|
|
529
|
+
}
|
|
530
|
+
else
|
|
531
|
+
result = await page(s.limit, s.cursor, Boolean(s.count));
|
|
532
|
+
// A list step's `handles` / `curation`: getRecords' for the URIs the page answered.
|
|
533
|
+
const listed = Array.isArray(result?.records) ? result.records : [];
|
|
534
|
+
if ((s.handles || s.curation) && listed.length) {
|
|
535
|
+
const asked = Object.fromEntries(['handles', 'curation'].filter((k) => s[k]).map((k) => [k, 'true']));
|
|
536
|
+
const more = await read(NSID.QUERY_GET_RECORDS, { uris: listed.map((r) => r.uri), ...asked });
|
|
537
|
+
result = { ...result };
|
|
538
|
+
for (const k of ['handles', 'curation'])
|
|
539
|
+
if (s[k] && Array.isArray(more?.[k]) && more[k].length)
|
|
540
|
+
result[k] = more[k];
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
const records = Array.isArray(result?.records) ? result.records : [];
|
|
544
|
+
// A list step read past one page is bounded by its own limit, not the call's total.
|
|
545
|
+
if (!pagedStep(s)) {
|
|
546
|
+
if (total + records.length > MAX_TOTAL_RECORDS)
|
|
547
|
+
refuse(`the steps answer more than ${MAX_TOTAL_RECORDS} records in all`);
|
|
548
|
+
total += records.length;
|
|
549
|
+
}
|
|
550
|
+
answered.set(s.name, records);
|
|
551
|
+
if (s.return === false)
|
|
552
|
+
continue;
|
|
553
|
+
const fields = s.fields;
|
|
554
|
+
const envelope = Array.isArray(s.envelope) ? s.envelope.filter(isEnvelopeField) : undefined;
|
|
555
|
+
out[s.name] = { ...result, records: records.map((r) => cutEnvelope(fields ? { ...r, value: selectFields(r.value, fields) } : r, envelope, s.uri !== false)) };
|
|
556
|
+
}
|
|
557
|
+
catch (e) {
|
|
558
|
+
// A refusal of the caller (401, or 429 for its budget) is the whole call's on the platform, decided before any
|
|
559
|
+
// step runs, never one step's: thrown as is, so `run` fails (or asks again) as it would against the platform.
|
|
560
|
+
if (callRefused(e))
|
|
561
|
+
throw e;
|
|
562
|
+
const err = isRecord(e) ? e : {};
|
|
563
|
+
errors[s.name] = {
|
|
564
|
+
error: typeof err.error === 'string' ? err.error : 'InternalError',
|
|
565
|
+
message: `step ${s.name}: ${typeof err.message === 'string' ? err.message : String(e)}`,
|
|
566
|
+
status: typeof err.status === 'number' ? err.status : 500,
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
return (Object.keys(errors).length ? { steps: out, errors } : { steps: out });
|
|
571
|
+
};
|
|
572
|
+
}
|