techne-sdk 0.1.0 → 0.3.0

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 (72) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/README.md +48 -2
  3. package/dist/auth/app-key.d.ts +8 -0
  4. package/dist/auth/app-key.js +95 -0
  5. package/dist/auth/index.d.ts +192 -0
  6. package/dist/auth/index.js +230 -0
  7. package/dist/auth/placement.gen.d.ts +1 -0
  8. package/dist/auth/placement.gen.js +50 -0
  9. package/dist/catalog/catalog.gen.js +2161 -681
  10. package/dist/connect.js +2 -1
  11. package/dist/generated/index.d.ts +61 -0
  12. package/dist/generated/index.js +116 -0
  13. package/dist/generated/lexicons.d.ts +3689 -1449
  14. package/dist/generated/lexicons.js +1237 -42
  15. package/dist/generated/nsid.d.ts +23 -1
  16. package/dist/generated/nsid.js +23 -19
  17. package/dist/generated/nsid.json +23 -19
  18. package/dist/generated/records.d.ts +28 -26
  19. package/dist/generated/types/pub/techne/draft/commons/getVersions.d.ts +3 -3
  20. package/dist/generated/types/pub/techne/draft/commons/runChain.d.ts +1 -1
  21. package/dist/generated/types/pub/techne/draft/credential.d.ts +1 -1
  22. package/dist/generated/types/pub/techne/draft/credentialRevocation.d.ts +1 -1
  23. package/dist/generated/types/pub/techne/draft/permissioned/deleteRecord.d.ts +5 -0
  24. package/dist/generated/types/pub/techne/draft/permissioned/deleteRecord.js +7 -0
  25. package/dist/generated/types/pub/techne/draft/permissioned/getRecord.d.ts +2 -1
  26. package/dist/generated/types/pub/techne/draft/permissioned/listChanges.d.ts +1 -1
  27. package/dist/generated/types/pub/techne/draft/permissioned/putRecord.d.ts +2 -2
  28. package/dist/generated/types/pub/techne/draft/provenance.d.ts +1 -1
  29. package/dist/generated/types/pub/techne/draft/publisher.d.ts +1 -1
  30. package/dist/generated/types/pub/techne/draft/query/composeRecords.d.ts +152 -0
  31. package/dist/generated/types/pub/techne/draft/query/composeRecords.js +55 -0
  32. package/dist/generated/types/pub/techne/draft/query/getRecords.d.ts +1 -1
  33. package/dist/generated/types/pub/techne/draft/query/listRecords.d.ts +0 -4
  34. package/dist/generated/types/pub/techne/draft/query/listRejections.d.ts +2 -2
  35. package/dist/generated/types/pub/techne/draft/registry/blockIndex.d.ts +42 -0
  36. package/dist/generated/types/pub/techne/draft/registry/blockIndex.js +34 -0
  37. package/dist/generated/types/pub/techne/draft/registry/defs.d.ts +112 -0
  38. package/dist/generated/types/pub/techne/draft/registry/defs.js +32 -0
  39. package/dist/generated/types/pub/techne/draft/registry/getType.d.ts +23 -0
  40. package/dist/generated/types/pub/techne/draft/registry/getType.js +20 -0
  41. package/dist/generated/types/pub/techne/draft/registry/getTypeRequest.d.ts +23 -0
  42. package/dist/generated/types/pub/techne/draft/registry/getTypeRequest.js +20 -0
  43. package/dist/generated/types/pub/techne/draft/registry/listTypeRequests.d.ts +27 -0
  44. package/dist/generated/types/pub/techne/draft/registry/listTypeRequests.js +7 -0
  45. package/dist/generated/types/pub/techne/draft/registry/listTypes.d.ts +34 -0
  46. package/dist/generated/types/pub/techne/draft/registry/listTypes.js +7 -0
  47. package/dist/generated/types/pub/techne/draft/registry/publishType.d.ts +77 -0
  48. package/dist/generated/types/pub/techne/draft/registry/publishType.js +83 -0
  49. package/dist/generated/types/pub/techne/draft/registry/purgeType.d.ts +39 -0
  50. package/dist/generated/types/pub/techne/draft/registry/purgeType.js +34 -0
  51. package/dist/generated/types/pub/techne/draft/registry/requestType.d.ts +53 -0
  52. package/dist/generated/types/pub/techne/draft/registry/requestType.js +76 -0
  53. package/dist/generated/types/pub/techne/draft/registry/typeRequest.d.ts +22 -0
  54. package/dist/generated/types/pub/techne/draft/registry/typeRequest.js +12 -0
  55. package/dist/generated/types/pub/techne/draft/sync/indexRecord.d.ts +1 -1
  56. package/dist/generated/types/pub/techne/draft/verdict.d.ts +2 -2
  57. package/dist/platform.d.ts +14 -0
  58. package/dist/platform.js +16 -0
  59. package/dist/put/index.js +17 -7
  60. package/dist/query/index.d.ts +1 -10
  61. package/dist/query/index.js +1 -1
  62. package/dist/types-cli/emit.d.ts +20 -0
  63. package/dist/types-cli/emit.js +217 -0
  64. package/dist/types-cli/main.d.ts +5 -0
  65. package/dist/types-cli/main.js +63 -0
  66. package/dist/types-cli/resolve.d.ts +26 -0
  67. package/dist/types-cli/resolve.js +99 -0
  68. package/dist/wasm/index.d.ts +20 -3
  69. package/dist/wasm/index.js +6 -1
  70. package/dist/wasm/techne-wasm.gen.js +1 -1
  71. package/dist/wasm/techne-wasm2js.gen.js +26425 -25985
  72. package/package.json +23 -6
@@ -0,0 +1,217 @@
1
+ /**
2
+ * The emitter behind `npx techne-sdk types <nsid>`: one lexicon document in, TypeScript types out.
3
+ *
4
+ * Small on purpose. It covers what a record type needs (records, objects, tokens, the field types, local refs
5
+ * and unions) and the shapes of a method (params, input, output). A ref to another document becomes
6
+ * `unknown` with the ref in a comment, except `com.atproto.repo.strongRef`, which every sidecar uses. Names:
7
+ * `main` is the NSID's last segment in PascalCase (`toolListing` -> `ToolListing`); another def is that name
8
+ * plus the def's (`ToolListing` + `#photo` -> `ToolListingPhoto`). Output is deterministic (golden-tested).
9
+ */
10
+ import { isValidNsid } from '@atproto/syntax';
11
+ /** Whether `v` has a lexicon document's shape: a numeric `lexicon`, a string `id` and an object `defs`. */
12
+ export function isLexiconDoc(v) {
13
+ if (typeof v !== 'object' || v === null)
14
+ return false;
15
+ const d = v;
16
+ return typeof d.lexicon === 'number' && typeof d.id === 'string' && typeof d.defs === 'object' && d.defs !== null && !Array.isArray(d.defs);
17
+ }
18
+ const STRONG_REF = '{ uri: string; cid: string }';
19
+ // What may reach the emitted TypeScript. A lexicon comes from the network (the registry, or a PDS a DNS TXT
20
+ // record names), so every lexicon-derived name is checked against its syntax first and the emitter throws
21
+ // on anything else. An NSID as @atproto/syntax checks it; a def name as atproto names them.
22
+ const DEF_RE = /^[A-Za-z][A-Za-z0-9]*$/;
23
+ function checkNsid(v, what) {
24
+ if (typeof v !== 'string' || !isValidNsid(v))
25
+ throw new Error(`${what} ${JSON.stringify(v)} is not an NSID`);
26
+ return v;
27
+ }
28
+ function checkDef(v, what) {
29
+ if (typeof v !== 'string' || !DEF_RE.test(v))
30
+ throw new Error(`${what} ${JSON.stringify(v)} is not a def name (letters and digits, a letter first)`);
31
+ return v;
32
+ }
33
+ /** A ref: `#name`, `<nsid>` or `<nsid>#name`; anything else throws. */
34
+ function checkRef(v) {
35
+ if (typeof v !== 'string')
36
+ throw new Error(`ref ${JSON.stringify(v)} is not a string`);
37
+ const [id, def, ...more] = v.split('#');
38
+ if (more.length || (id === '' && def === undefined))
39
+ throw new Error(`ref ${JSON.stringify(v)} is not <nsid>, #<def> or <nsid>#<def>`);
40
+ if (id !== '')
41
+ checkNsid(id, `ref ${JSON.stringify(v)}: NSID`);
42
+ if (def !== undefined)
43
+ checkDef(def, `ref ${JSON.stringify(v)}: def`);
44
+ return v;
45
+ }
46
+ function pascal(s) {
47
+ const parts = s.split(/[^A-Za-z0-9]+/).filter(Boolean);
48
+ return parts.map((p) => p[0].toUpperCase() + p.slice(1)).join('');
49
+ }
50
+ /** The exported name of one def of `nsid`. */
51
+ export function defName(nsid, def) {
52
+ const base = pascal(nsid.split('.').pop() ?? nsid);
53
+ return def === 'main' ? base : base + pascal(def);
54
+ }
55
+ const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
56
+ const key = (k) => (IDENT.test(k) ? k : JSON.stringify(k));
57
+ /**
58
+ * A TypeScript literal type. A string is escaped by JSON.stringify (every control character, newlines
59
+ * included), then requoted with single quotes, the emitter's style: `\"` back to `"`, `'` escaped. Only
60
+ * strings, finite numbers and booleans; anything else in a const or enum throws.
61
+ */
62
+ function lit(v) {
63
+ if (typeof v === 'string')
64
+ return `'${JSON.stringify(v).slice(1, -1).replace(/\\.|'/g, (m) => (m === "'" ? "\\'" : m === '\\"' ? '"' : m))}'`;
65
+ if ((typeof v === 'number' && Number.isFinite(v)) || typeof v === 'boolean')
66
+ return String(v);
67
+ throw new Error(`${JSON.stringify(v)} is not a string, number or boolean literal`);
68
+ }
69
+ /** Text safe inside a `//` comment: one line (no line terminator of any kind), and no `*\/`. */
70
+ const line = (s) => s.replace(/[\r\n\u2028\u2029]/g, ' ').replace(/\*\//g, '* /');
71
+ function doc(text, pad) {
72
+ if (!text)
73
+ return '';
74
+ if (typeof text !== 'string')
75
+ throw new Error(`description ${JSON.stringify(text)} is not a string`);
76
+ const lines = text.replace(/\*\//g, '* /').split(/\r\n|[\r\n\u2028\u2029]/);
77
+ if (lines.length === 1)
78
+ return `${pad}/** ${lines[0]} */\n`;
79
+ return `${pad}/**\n${lines.map((l) => `${pad} * ${l}`.trimEnd()).join('\n')}\n${pad} */\n`;
80
+ }
81
+ class Emitter {
82
+ nsid;
83
+ constructor(nsid) {
84
+ this.nsid = nsid;
85
+ }
86
+ /** A ref string to a TypeScript type, and the `$type` a union member carries. */
87
+ ref(r) {
88
+ checkRef(r);
89
+ if (r.startsWith('#'))
90
+ return { type: defName(this.nsid, r.slice(1)), $type: `${this.nsid}${r}` };
91
+ const [id, def = 'main'] = r.split('#');
92
+ if (id === this.nsid)
93
+ return { type: defName(this.nsid, def), $type: def === 'main' ? id : `${id}#${def}` };
94
+ if (id === 'com.atproto.repo.strongRef' && def === 'main')
95
+ return { type: STRONG_REF, $type: id };
96
+ return { type: `unknown /* ${r} */`, $type: def === 'main' ? id : `${id}#${def}` };
97
+ }
98
+ type(s, pad) {
99
+ switch (s.type) {
100
+ case 'string':
101
+ if (s.const !== undefined)
102
+ return lit(s.const);
103
+ if (Array.isArray(s.enum))
104
+ return s.enum.map(lit).join(' | ');
105
+ if (Array.isArray(s.knownValues) && s.knownValues.length)
106
+ return `${s.knownValues.map(lit).join(' | ')} | (string & {})`;
107
+ return 'string';
108
+ case 'integer':
109
+ if (s.const !== undefined)
110
+ return lit(s.const);
111
+ if (Array.isArray(s.enum))
112
+ return s.enum.map(lit).join(' | ');
113
+ return 'number';
114
+ case 'boolean':
115
+ return s.const !== undefined ? lit(s.const) : 'boolean';
116
+ case 'null':
117
+ return 'null';
118
+ case 'bytes':
119
+ return 'Uint8Array';
120
+ case 'cid-link':
121
+ return '{ $link: string }';
122
+ case 'blob':
123
+ return "{ $type: 'blob'; ref: { $link: string }; mimeType: string; size: number }";
124
+ case 'unknown':
125
+ return 'unknown';
126
+ case 'array': {
127
+ const inner = this.type(s.items ?? {}, pad);
128
+ return /^[\w$.]+$/.test(inner) ? `${inner}[]` : `Array<${inner}>`;
129
+ }
130
+ case 'object':
131
+ return this.object(s, pad);
132
+ case 'ref':
133
+ return this.ref(s.ref).type;
134
+ case 'union': {
135
+ if (!Array.isArray(s.refs ?? []))
136
+ throw new Error('a union\'s refs is not a list');
137
+ const members = (s.refs ?? []).map((r) => {
138
+ const { type, $type } = this.ref(r);
139
+ return type.startsWith('unknown') ? `{ $type: ${lit($type)}; [k: string]: unknown }` : `(${type} & { $type: ${lit($type)} })`;
140
+ });
141
+ if (s.closed !== true)
142
+ members.push('{ $type: string; [k: string]: unknown }');
143
+ return members.length ? members.join(' | ') : 'never';
144
+ }
145
+ default:
146
+ return 'unknown';
147
+ }
148
+ }
149
+ /** An object schema's body, `{ ... }`, one property a line. */
150
+ object(s, pad, head = []) {
151
+ const required = new Set(s.required ?? []);
152
+ const nullable = new Set(s.nullable ?? []);
153
+ const inner = pad + ' ';
154
+ const lines = [...head.map((h) => `${inner}${h}\n`)];
155
+ for (const [k, p] of Object.entries(s.properties ?? {})) {
156
+ const t = this.type(p, inner) + (nullable.has(k) ? ' | null' : '');
157
+ lines.push(`${doc(p.description, inner)}${inner}${key(k)}${required.has(k) ? '' : '?'}: ${t}\n`);
158
+ }
159
+ return lines.length ? `{\n${lines.join('')}${pad}}` : '{}';
160
+ }
161
+ /** `export interface Name { ... }` from an object schema (a record's body carries its `$type`). */
162
+ iface(name, s, description, head = []) {
163
+ return `${doc(description, '')}export interface ${name} ${this.object(s, '', head)}\n`;
164
+ }
165
+ def(def, s) {
166
+ checkDef(def, `${this.nsid}: def`);
167
+ if (!s || typeof s !== 'object')
168
+ throw new Error(`${this.nsid}#${def} is not a schema object`);
169
+ const name = defName(this.nsid, def);
170
+ const $type = def === 'main' ? this.nsid : `${this.nsid}#${def}`;
171
+ switch (s.type) {
172
+ case 'record':
173
+ return this.iface(name, s.record ?? {}, s.description, [`$type: ${lit($type)}`]);
174
+ case 'token':
175
+ return `${doc(s.description, '')}export type ${name} = ${lit($type)}\n`;
176
+ case 'object':
177
+ case 'string':
178
+ case 'integer':
179
+ case 'boolean':
180
+ case 'array':
181
+ case 'union':
182
+ case 'ref':
183
+ case 'bytes':
184
+ case 'cid-link':
185
+ case 'blob':
186
+ case 'unknown':
187
+ return this.body(name, s);
188
+ case 'query':
189
+ case 'procedure': {
190
+ const out = [];
191
+ if (s.parameters?.properties)
192
+ out.push(this.iface(`${name}Params`, s.parameters, s.description));
193
+ if (s.input?.schema)
194
+ out.push(this.body(`${name}Input`, s.input.schema));
195
+ if (s.output?.schema)
196
+ out.push(this.body(`${name}Output`, s.output.schema));
197
+ return out.join('\n') || `// ${$type}: a ${s.type} with no params, input or output schema\n`;
198
+ }
199
+ default:
200
+ return `// ${$type}: a ${typeof s.type === 'string' ? line(s.type) : 'typeless'} def, not emitted\n`;
201
+ }
202
+ }
203
+ body(name, s) {
204
+ return s.type === 'object' ? this.iface(name, s, s.description) : `${doc(s.description, '')}export type ${name} = ${this.type(s, '')}\n`;
205
+ }
206
+ }
207
+ /** TypeScript for every def of `lexicon`, `main` first. `source` goes in the header (where it came from). */
208
+ export function emitTypes(lexicon, options = {}) {
209
+ if (!isLexiconDoc(lexicon))
210
+ throw new Error('not a lexicon document (needs `lexicon`, `id` and `defs`)');
211
+ checkNsid(lexicon.id, 'lexicon id');
212
+ const e = new Emitter(lexicon.id);
213
+ const defs = Object.keys(lexicon.defs).sort((a, b) => (a === 'main' ? -1 : b === 'main' ? 1 : a.localeCompare(b)));
214
+ const head = `// Types for ${lexicon.id}${options.source ? `, from ${line(options.source)}` : ''}.\n` +
215
+ `// Generated by \`npx techne-sdk types ${lexicon.id}\`; regenerate rather than edit.\n`;
216
+ return [head + (lexicon.description ? '\n' + doc(lexicon.description, '') : ''), ...defs.map((d) => e.def(d, lexicon.defs[d]))].join('\n');
217
+ }
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ export declare function main(argv: string[], io?: {
3
+ out: (s: string) => boolean;
4
+ err: (s: string) => boolean;
5
+ }): Promise<number>;
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `npx techne-sdk types <nsid> [--platform <url>] [--out <file>]`: TypeScript types for any record type,
4
+ * printed (or written to `--out`). The lexicon comes from the platform's registry, else from the network
5
+ * (src/types-cli/resolve.ts); the emitter is src/types-cli/emit.ts.
6
+ */
7
+ import { realpathSync, writeFileSync } from 'node:fs';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { parseArgs } from 'node:util';
10
+ import { emitTypes } from './emit.js';
11
+ import { DEFAULT_PLATFORM_URL, resolveLexicon } from './resolve.js';
12
+ const USAGE = `usage: techne-sdk types <nsid> [--platform <url>] [--out <file>]
13
+
14
+ Prints TypeScript types for one lexicon: a platform type, a community draft (pub.techne.draft.c.*),
15
+ a requested type, or any NSID published by atproto lexicon resolution.
16
+
17
+ --platform <url> the platform to ask first (default ${DEFAULT_PLATFORM_URL}; env TECHNE_PLATFORM_URL)
18
+ --out <file> write the types there instead of printing them`;
19
+ export async function main(argv, io = { out: (s) => process.stdout.write(s), err: (s) => process.stderr.write(s) }) {
20
+ const usage = (code, why = '') => {
21
+ io.err(`${why}${USAGE}\n`);
22
+ return code;
23
+ };
24
+ const [cmd, ...rest] = argv;
25
+ if (cmd !== 'types')
26
+ return usage(cmd === undefined || cmd === '-h' || cmd === '--help' ? 0 : 2);
27
+ let args;
28
+ try {
29
+ args = parseArgs({ args: rest, options: { platform: { type: 'string' }, out: { type: 'string' }, help: { type: 'boolean', short: 'h' } }, allowPositionals: true });
30
+ }
31
+ catch (e) {
32
+ return usage(2, `${e.message}\n`);
33
+ }
34
+ if (args.values.help)
35
+ return usage(0);
36
+ if (args.positionals.length !== 1)
37
+ return usage(2);
38
+ const [nsid] = args.positionals;
39
+ const platform = args.values.platform || process.env.TECHNE_PLATFORM_URL || undefined;
40
+ const { out } = args.values;
41
+ try {
42
+ const found = await resolveLexicon(nsid, { platform });
43
+ const text = emitTypes(found.lexicon, { source: found.source });
44
+ if (out) {
45
+ writeFileSync(out, text);
46
+ io.err(`wrote ${out}${found.page ? ` (page: ${found.page})` : ''}\n`);
47
+ }
48
+ else {
49
+ io.out(text);
50
+ if (found.page)
51
+ io.err(`page: ${found.page}\n`);
52
+ }
53
+ return 0;
54
+ }
55
+ catch (e) {
56
+ io.err(`${e.message}\n`);
57
+ return 1;
58
+ }
59
+ }
60
+ // Run when invoked as the bin (npx follows node_modules/.bin's symlink here), not when imported by a test.
61
+ const invoked = process.argv[1] ? realpathSync(process.argv[1]) : '';
62
+ if (invoked === fileURLToPath(import.meta.url))
63
+ main(process.argv.slice(2)).then((code) => process.exit(code));
@@ -0,0 +1,26 @@
1
+ import { type LexiconDoc } from './emit.js';
2
+ /** The platform `npx techne-sdk types` asks by default. */
3
+ export declare const DEFAULT_PLATFORM_URL = "https://techne.computer";
4
+ /** The PLC directory a did:plc is resolved at by default. */
5
+ export declare const DEFAULT_PLC_URL = "https://plc.directory";
6
+ /** The collection atproto publishes a lexicon in (com.atproto.lexicon.schema has no generated constant: no client calls it). */
7
+ export declare const LEXICON_SCHEMA_COLLECTION = "com.atproto.lexicon.schema";
8
+ export interface ResolveOptions {
9
+ /** The platform's base URL (its `/xrpc/...`); default {@link DEFAULT_PLATFORM_URL}. */
10
+ platform?: string;
11
+ plc?: string;
12
+ fetch?: typeof globalThis.fetch;
13
+ /** DNS TXT lookup, as `node:dns/promises` `resolveTxt` answers (each record a list of chunks). */
14
+ resolveTxt?: (name: string) => Promise<string[][]>;
15
+ }
16
+ export interface Resolved {
17
+ lexicon: LexiconDoc;
18
+ /** Where it came from, for the header: `https://techne.computer (registry.getType)` or `at://did/...`. */
19
+ source: string;
20
+ /** The type's techne.pub page, when the platform knows it. */
21
+ page?: string;
22
+ }
23
+ /** The `_lexicon` TXT name of an NSID's authority: `pub.techne.draft.c.ab.toolListing` -> `_lexicon.ab.c.draft.techne.pub`. */
24
+ export declare function lexiconTxtName(nsid: string): string;
25
+ /** The lexicon for `nsid`, from the platform or else the network. Throws, naming what it tried. */
26
+ export declare function resolveLexicon(nsid: string, options?: ResolveOptions): Promise<Resolved>;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Find the lexicon behind an NSID for `npx techne-sdk types`: the platform's registry first
3
+ * (`pub.techne.draft.registry.getType`: its own types, community drafts, requested types), then atproto
4
+ * lexicon resolution (the `_lexicon` TXT record of the NSID's authority names a DID; that DID's PDS holds the
5
+ * schema as a `com.atproto.lexicon.schema` record whose rkey is the NSID). No hierarchy walk: atproto names
6
+ * exactly one authority per NSID.
7
+ */
8
+ import { isAtprotoDid } from '@atproto/did';
9
+ import { XRPCError } from '@atproto/xrpc';
10
+ import { AtpBaseClient } from '../generated/index.js';
11
+ import { isLexiconDoc } from './emit.js';
12
+ /** The platform `npx techne-sdk types` asks by default. */
13
+ export const DEFAULT_PLATFORM_URL = 'https://techne.computer';
14
+ /** The PLC directory a did:plc is resolved at by default. */
15
+ export const DEFAULT_PLC_URL = 'https://plc.directory';
16
+ /** The collection atproto publishes a lexicon in (com.atproto.lexicon.schema has no generated constant: no client calls it). */
17
+ export const LEXICON_SCHEMA_COLLECTION = 'com.atproto.lexicon.schema';
18
+ /** The `_lexicon` TXT name of an NSID's authority: `pub.techne.draft.c.ab.toolListing` -> `_lexicon.ab.c.draft.techne.pub`. */
19
+ export function lexiconTxtName(nsid) {
20
+ const parts = nsid.split('.');
21
+ if (parts.length < 3 || parts.some((p) => !p))
22
+ throw new Error(`${nsid} is not an NSID`);
23
+ return `_lexicon.${parts.slice(0, -1).reverse().join('.')}`;
24
+ }
25
+ const trimSlash = (u) => u.replace(/\/+$/, '');
26
+ /** The generated client against `base` (its path kept: `new URL(path, base)` would drop it), fetching with `f`. */
27
+ const clientAt = (base, f) => new AtpBaseClient((path, init) => f(`${base}${path}`, init));
28
+ /** Why a call failed: an XRPC error's status and name, else the message. */
29
+ const why = (e) => (e instanceof XRPCError && e.status >= 400 ? `answered ${e.status}${e.error ? ` ${e.error}` : ''}` : `failed: ${e.message}`);
30
+ const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
31
+ async function getJson(f, url) {
32
+ const res = await f(url, { headers: { accept: 'application/json' } });
33
+ let body = null;
34
+ try {
35
+ body = await res.json();
36
+ }
37
+ catch { }
38
+ return { status: res.status, body };
39
+ }
40
+ /** The DID's `#atproto_pds` endpoint. */
41
+ async function pdsOf(f, did, plc) {
42
+ // The DID from a TXT record lands in a URL and the output header: atproto's rule (did:plc, or did:web with a host only).
43
+ if (!isAtprotoDid(did))
44
+ throw new Error(`${JSON.stringify(did)} is not an atproto DID (did:plc, or did:web with no path)`);
45
+ const url = did.startsWith('did:plc:') ? `${trimSlash(plc)}/${did}` : `https://${decodeURIComponent(did.slice('did:web:'.length))}/.well-known/did.json`;
46
+ const { status, body } = await getJson(f, url);
47
+ if (status !== 200 || !isObject(body))
48
+ throw new Error(`${did}: its DID document did not resolve (${url} answered ${status})`);
49
+ const services = Array.isArray(body.service) ? body.service : [];
50
+ const svc = services.find((s) => isObject(s) && (s.id === '#atproto_pds' || s.id === `${did}#atproto_pds`));
51
+ const endpoint = svc?.serviceEndpoint;
52
+ if (typeof endpoint !== 'string' || !URL.canParse(endpoint))
53
+ throw new Error(`${did}: its DID document names no #atproto_pds service`);
54
+ return trimSlash(endpoint);
55
+ }
56
+ /** `value` as the lexicon of `nsid`, without a schema record's `$type`. The emitter checks each def as it emits it. */
57
+ function asLexicon(value, nsid) {
58
+ if (!isObject(value) || value.id !== nsid)
59
+ throw new Error(`the document found for ${nsid} is not its lexicon`);
60
+ const { $type: _t, ...doc } = value;
61
+ if (!isLexiconDoc(doc))
62
+ throw new Error(`the document found for ${nsid} is not a lexicon document (needs \`lexicon\`, \`id\` and \`defs\`)`);
63
+ return doc;
64
+ }
65
+ /** The lexicon for `nsid`, from the platform or else the network. Throws, naming what it tried. */
66
+ export async function resolveLexicon(nsid, options = {}) {
67
+ const f = options.fetch ?? globalThis.fetch;
68
+ const platform = trimSlash(options.platform ?? DEFAULT_PLATFORM_URL);
69
+ const tried = [];
70
+ const txtName = lexiconTxtName(nsid);
71
+ try {
72
+ const view = (await clientAt(platform, f).pub.techne.draft.registry.getType({ nsid })).data;
73
+ return { lexicon: asLexicon(view.lexicon, nsid), source: `${platform} (registry.getType)`, page: view.page };
74
+ }
75
+ catch (e) {
76
+ tried.push(`${platform} registry.getType ${why(e)}`);
77
+ }
78
+ try {
79
+ const resolveTxt = options.resolveTxt ?? (await import('node:dns/promises')).resolveTxt;
80
+ const records = (await resolveTxt(txtName)).map((chunks) => chunks.join(''));
81
+ const dids = records.filter((r) => r.startsWith('did=')).map((r) => r.slice(4));
82
+ if (dids.length !== 1)
83
+ throw new Error(`${txtName} holds ${dids.length} did= records, not one`);
84
+ const did = dids[0];
85
+ const pds = await pdsOf(f, did, options.plc ?? DEFAULT_PLC_URL);
86
+ let record;
87
+ try {
88
+ record = (await clientAt(pds, f).com.atproto.repo.getRecord({ repo: did, collection: LEXICON_SCHEMA_COLLECTION, rkey: nsid })).data;
89
+ }
90
+ catch (e) {
91
+ throw new Error(`${pds} has no ${LEXICON_SCHEMA_COLLECTION} record ${nsid} for ${did} (${why(e)})`);
92
+ }
93
+ return { lexicon: asLexicon(record.value, nsid), source: `at://${did}/${LEXICON_SCHEMA_COLLECTION}/${nsid}` };
94
+ }
95
+ catch (e) {
96
+ tried.push(`atproto resolution (${txtName}): ${e.message}`);
97
+ }
98
+ throw new Error(`no lexicon found for ${nsid}:\n ${tried.join('\n ')}`);
99
+ }
@@ -16,12 +16,20 @@ export interface ReadRecord {
16
16
  uri: string;
17
17
  cid: string;
18
18
  value: unknown;
19
+ /**
20
+ * When the app first saw this version (RFC 3339). Read for a credential an operator issued: it counts
21
+ * only if the root names the operator for a period holding then. Without it, only an open period holds.
22
+ */
23
+ firstSeen?: string;
19
24
  }
20
25
  /** What the caller holds to check records against. */
21
26
  export interface Claims {
22
27
  /** The commons root DID. */
23
28
  root?: string;
24
- /** Records read: the root's credentials and revocations, accounts' `publisher/self` declarations. */
29
+ /**
30
+ * Records read: credentials and revocations (the root's and its operators'), the root's
31
+ * `pub.techne.draft.operator` records, and accounts' `publisher/self` declarations.
32
+ */
25
33
  records?: ReadRecord[];
26
34
  /** Roles known: `role` absent when a membership is known but none covered the time. */
27
35
  roles?: {
@@ -35,7 +43,12 @@ export interface Claims {
35
43
  admitted: boolean;
36
44
  }[];
37
45
  }
38
- /** Lexicon validity, and whether the collection may live on the public firehose. */
46
+ /**
47
+ * Lexicon validity, and whether the collection may live on the public firehose. It knows the lexicons built
48
+ * into this version only: a community or requested type (published at run time) answers `valid: false`, "no
49
+ * record lexicon". There is no `validateWith(lexicon, body)` in this release (no consumer yet); the platform
50
+ * checks a runtime type's records against its lexicon when they are written.
51
+ */
39
52
  export declare function validate(collection: string, body: unknown): {
40
53
  valid: boolean;
41
54
  problems: string[];
@@ -64,7 +77,11 @@ export interface Verification {
64
77
  valid: boolean;
65
78
  /** The repo it is from (atproto signs a repo's commits, not each record). */
66
79
  signer: string;
67
- /** The commons root vouches for the signer's `publisher/self` declaration, which covers the collection. */
80
+ /**
81
+ * An admin writer (the commons root, or an operator the root names for a period holding when the
82
+ * credential was first seen) vouches for the signer's `publisher/self` declaration, which covers the
83
+ * collection.
84
+ */
68
85
  chainVerified: boolean;
69
86
  /** Why it is not valid (empty when it is). */
70
87
  problems: string[];
@@ -37,7 +37,12 @@ export function call(fn, args) {
37
37
  instance ??= caller(load());
38
38
  return instance(fn, args);
39
39
  }
40
- /** Lexicon validity, and whether the collection may live on the public firehose. */
40
+ /**
41
+ * Lexicon validity, and whether the collection may live on the public firehose. It knows the lexicons built
42
+ * into this version only: a community or requested type (published at run time) answers `valid: false`, "no
43
+ * record lexicon". There is no `validateWith(lexicon, body)` in this release (no consumer yet); the platform
44
+ * checks a runtime type's records against its lexicon when they are written.
45
+ */
41
46
  export function validate(collection, body) {
42
47
  return call('validate', { collection, body });
43
48
  }