@biolibs/bionet 0.0.0-stage → 1.1.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.
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Finding labs you were never told about, by walking from ones you were.
3
+ *
4
+ * There is no index of labs and nothing here builds one. A lab is found the way a page was found on
5
+ * the early web: somebody you already know points at it. So discovery is a walk — start from
6
+ * addresses a person gave you, fetch each lab's inventory, follow the labs it points at, and stop
7
+ * when you run out of new ones or hit the bounds you set.
8
+ *
9
+ * Three things about that are worth being plain about, because they are properties of the design and
10
+ * not gaps in the implementation.
11
+ *
12
+ * **What you find is what your seeds could reach.** There is no view of the whole network and no way
13
+ * to know what you are missing. Two people starting from different labs will find different sets, and
14
+ * neither is the network. `Discovery` therefore records the path by which each lab was reached, so a
15
+ * person can see *how* they came to be looking at it.
16
+ *
17
+ * **A pointer is not an endorsement.** A lab pointing at another says only that the address exists.
18
+ * Nothing here treats being pointed at as evidence about what that lab holds or who they are.
19
+ *
20
+ * **Only a lab that checks out can introduce anyone.** A document whose signature fails, or that was
21
+ * served from an address it does not claim, is reported and then its pointers are dropped on the
22
+ * floor. Otherwise anyone able to answer for one address could fill a crawl with addresses of their
23
+ * choosing, and the bounds below would be the only thing standing in the way.
24
+ */
25
+ import { fetchInventory, settled, signingKeys, type FetchOptions, type FetchedInventory } from "./fetch.js";
26
+ import { labOrigin } from "./origin.js";
27
+
28
+ /** How far a crawl goes unless told otherwise. */
29
+ export const BY_DEFAULT = { labs: 50, depth: 2 };
30
+
31
+ /** Whether a lab's key is what the lab that pointed at it said it would be. */
32
+ export type AsIntroduced =
33
+ /** Nobody said, either because this was a seed or because the pointer carried no key. */
34
+ | "unsaid"
35
+ /** The key answering is the one the referring lab recorded. */
36
+ | "agrees"
37
+ /** A different key is answering than the referring lab recorded. */
38
+ | "differs";
39
+
40
+ /** A lab the walk reached. */
41
+ export interface Reached {
42
+ /** Its inventory, fetched and checked. */
43
+ found: FetchedInventory;
44
+ /** Whether its signatures hold and it came from the address it claims. */
45
+ settled: boolean;
46
+ /** How many pointers from a seed: 0 for a seed itself. */
47
+ depth: number;
48
+ /** The addresses walked to get here, starting at the seed and ending at this lab. */
49
+ path: string[];
50
+ /** The lab that pointed at this one, or null for a seed. */
51
+ introducedBy: string | null;
52
+ /** Whether the key answering is the one the referring lab recorded. */
53
+ asIntroduced: AsIntroduced;
54
+ }
55
+
56
+ /** A lab the walk could not reach. */
57
+ export interface Unreachable {
58
+ /** The address that was tried. */
59
+ origin: string;
60
+ /** How many pointers from a seed. */
61
+ depth: number;
62
+ /** The lab that pointed at it, or null for a seed. */
63
+ introducedBy: string | null;
64
+ /** What went wrong, in the words the attempt produced. */
65
+ why: string;
66
+ }
67
+
68
+ /** What a walk came to. */
69
+ export interface Discovery {
70
+ /** The labs reached, in the order they were reached. */
71
+ reached: Reached[];
72
+ /** The addresses that were tried and did not answer usefully. */
73
+ unreachable: Unreachable[];
74
+ /** Whether the walk stopped at its bounds with addresses still unvisited. */
75
+ stoppedEarly: boolean;
76
+ }
77
+
78
+ /** How far to walk, and what to walk with. */
79
+ export interface DiscoverOptions extends FetchOptions {
80
+ /** The most labs to fetch. Defaults to 50. */
81
+ maxLabs?: number;
82
+ /** How many pointers from a seed to follow. 0 fetches the seeds only. Defaults to 2. */
83
+ maxDepth?: number;
84
+ /** Called as each lab is reached, for anything that wants to show a walk in progress. */
85
+ onReached?: (one: Reached) => void;
86
+ }
87
+
88
+ /** One address waiting to be visited. */
89
+ interface Pending {
90
+ origin: string;
91
+ depth: number;
92
+ path: string[];
93
+ introducedBy: string | null;
94
+ /** The key the referring lab said would be here. */
95
+ expectedKey: string | null;
96
+ }
97
+
98
+ /**
99
+ * Walk the network from labs you already know.
100
+ *
101
+ * @param seeds - Addresses to start from, which somebody told you.
102
+ * @param options - How far to walk, and what to fetch with.
103
+ * @returns Every lab reached, how it was reached, and what could not be.
104
+ *
105
+ * @example
106
+ * ```ts
107
+ * import { discover, partsNeeded, settledLabs, whoHas } from "@biolibs/bionet";
108
+ *
109
+ * const walk = await discover(["endylab.example"], { maxDepth: 2 });
110
+ * walk.reached.map((one) => `${one.path.join(" → ")}`);
111
+ *
112
+ * whoHas(partsNeeded(plan.document), settledLabs(walk));
113
+ * ```
114
+ */
115
+ export async function discover(seeds: readonly string[], options: DiscoverOptions = {}): Promise<Discovery> {
116
+ const mostLabs = options.maxLabs ?? BY_DEFAULT.labs;
117
+ const deepest = options.maxDepth ?? BY_DEFAULT.depth;
118
+
119
+ const reached: Reached[] = [];
120
+ const unreachable: Unreachable[] = [];
121
+ const seen = new Set<string>();
122
+ const queue: Pending[] = [];
123
+
124
+ for (const seed of seeds) {
125
+ try {
126
+ const origin = labOrigin(seed);
127
+ if (seen.has(origin)) continue;
128
+ seen.add(origin);
129
+ queue.push({ origin, depth: 0, path: [origin], introducedBy: null, expectedKey: null });
130
+ } catch (cause) {
131
+ unreachable.push({ origin: seed, depth: 0, introducedBy: null, why: reason(cause) });
132
+ }
133
+ }
134
+
135
+ let fetched = 0;
136
+ while (queue.length > 0) {
137
+ if (fetched >= mostLabs) return { reached, unreachable, stoppedEarly: true };
138
+ const next = queue.shift()!;
139
+ fetched += 1;
140
+
141
+ let found: FetchedInventory;
142
+ try {
143
+ found = await fetchInventory(next.origin, options);
144
+ } catch (cause) {
145
+ unreachable.push({ origin: next.origin, depth: next.depth, introducedBy: next.introducedBy, why: reason(cause) });
146
+ continue;
147
+ }
148
+
149
+ const keys = signingKeys(found);
150
+ const one: Reached = {
151
+ found,
152
+ settled: settled(found),
153
+ depth: next.depth,
154
+ path: next.path,
155
+ introducedBy: next.introducedBy,
156
+ asIntroduced: next.expectedKey === null ? "unsaid"
157
+ : keys.includes(next.expectedKey) ? "agrees" : "differs",
158
+ };
159
+ reached.push(one);
160
+ options.onReached?.(one);
161
+
162
+ // A lab that does not check out does not get to say who else exists.
163
+ if (!one.settled || next.depth >= deepest) continue;
164
+
165
+ for (const pointer of found.signed.inventory.peers ?? []) {
166
+ let origin: string;
167
+ try {
168
+ origin = labOrigin(pointer.origin);
169
+ } catch (cause) {
170
+ unreachable.push({ origin: pointer.origin, depth: next.depth + 1, introducedBy: next.origin, why: reason(cause) });
171
+ continue;
172
+ }
173
+ if (seen.has(origin)) continue;
174
+ seen.add(origin);
175
+ queue.push({
176
+ origin,
177
+ depth: next.depth + 1,
178
+ path: [...next.path, origin],
179
+ introducedBy: next.origin,
180
+ expectedKey: pointer.key,
181
+ });
182
+ }
183
+ }
184
+ return { reached, unreachable, stoppedEarly: false };
185
+ }
186
+
187
+ /** @param cause - Whatever was thrown. @returns Something a person can read. */
188
+ const reason = (cause: unknown): string => (cause instanceof Error ? cause.message : String(cause));
189
+
190
+ /**
191
+ * The labs from a walk whose signatures hold and which came from their own address.
192
+ *
193
+ * These are the ones worth matching parts against. The rest are in `reached` with `settled` false, so
194
+ * that a walk can say "this address answered and did not check out" rather than quietly skipping it.
195
+ *
196
+ * @param discovery - What a walk came to.
197
+ * @returns Their inventories, in the order they were reached.
198
+ */
199
+ export function settledLabs(discovery: Discovery): FetchedInventory[] {
200
+ return discovery.reached.filter((one) => one.settled).map((one) => one.found);
201
+ }
202
+
203
+ /**
204
+ * The labs a walk reached whose key is not the one that introduced them.
205
+ *
206
+ * Nothing is concluded from this. It is surfaced because it is the one disagreement a walk can notice
207
+ * without an authority: two parties describing the same address differently.
208
+ *
209
+ * @param discovery - What a walk came to.
210
+ * @returns Those labs.
211
+ */
212
+ export function introducedDifferently(discovery: Discovery): Reached[] {
213
+ return discovery.reached.filter((one) => one.asIntroduced === "differs");
214
+ }
package/src/fetch.ts ADDED
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Fetching a lab's inventory, and reporting exactly what came back.
3
+ *
4
+ * Nothing here returns a bare "trusted" flag, because there is no single question being answered. A
5
+ * fetch establishes three separate things, and they are reported separately: whether the document is
6
+ * an inventory at all, whether its signatures hold, and whether it was served from the address it
7
+ * claims. A caller that wants a yes-or-no can ask for `settled`, which is all three at once and says
8
+ * so in its own documentation.
9
+ */
10
+ import { verifyInventory, readInventory, LONGEST } from "./inventory.js";
11
+ import { inventoryUrl, labOrigin, originMatches } from "./origin.js";
12
+ import type { SignedInventory } from "./model.js";
13
+ import type { SignatureCheck } from "@biolibs/opencloning";
14
+
15
+ /** How long to wait for a lab's web server. */
16
+ const PATIENCE = 10_000;
17
+
18
+ /** An inventory, fetched. */
19
+ export interface FetchedInventory {
20
+ /** Where it was actually fetched from. */
21
+ origin: string;
22
+ /** The inventory and its signatures, exactly as served. */
23
+ signed: SignedInventory;
24
+ /** One check per signature. */
25
+ checks: SignatureCheck[];
26
+ /** Whether the document was served from the origin it names. */
27
+ fromItsOwnAddress: boolean;
28
+ }
29
+
30
+ /** How to fetch. */
31
+ export interface FetchOptions {
32
+ /** Something to fetch with. Defaults to the runtime's own `fetch`. */
33
+ fetch?: typeof globalThis.fetch;
34
+ /** How long to wait, in milliseconds. */
35
+ timeoutMs?: number;
36
+ }
37
+
38
+ /**
39
+ * Fetch a lab's inventory and check it.
40
+ *
41
+ * @param address - The lab's address, like `endylab.example`.
42
+ * @param options - What to fetch with, and how long to wait.
43
+ * @returns What came back, with the signatures checked and the address compared.
44
+ * @throws If the address is not usable, nothing answered, or what answered is not an inventory.
45
+ *
46
+ * @example
47
+ * ```ts
48
+ * import { fetchInventory, settled } from "@biolibs/bionet";
49
+ *
50
+ * const found = await fetchInventory("endylab.example");
51
+ * settled(found); // signed, and served from the address it claims
52
+ * found.signed.inventory.parts.length;
53
+ * ```
54
+ */
55
+ export async function fetchInventory(address: string, options: FetchOptions = {}): Promise<FetchedInventory> {
56
+ const origin = labOrigin(address);
57
+ const url = inventoryUrl(origin);
58
+ const get = options.fetch ?? globalThis.fetch;
59
+ const response = await get(url, {
60
+ headers: { accept: "application/json" },
61
+ redirect: "error",
62
+ signal: AbortSignal.timeout(options.timeoutMs ?? PATIENCE),
63
+ });
64
+ if (!response.ok) throw new Error(`${origin} has no inventory to read (${response.status}).`);
65
+ const text = await response.text();
66
+ if (text.length > LONGEST) throw new Error(`${origin} published more inventory than this will read.`);
67
+ let parsed: unknown;
68
+ try {
69
+ parsed = JSON.parse(text);
70
+ } catch {
71
+ throw new Error(`What ${origin} published is not JSON.`);
72
+ }
73
+ const signed = readInventory(parsed);
74
+ return {
75
+ origin,
76
+ signed,
77
+ checks: await verifyInventory(signed),
78
+ fromItsOwnAddress: originMatches(signed.inventory.lab.origin, origin),
79
+ };
80
+ }
81
+
82
+ /**
83
+ * The fingerprints of the keys whose signatures held.
84
+ *
85
+ * These, not the lab's name, are what a lab is recognised by from one visit to the next.
86
+ *
87
+ * @param found - A fetched inventory.
88
+ * @returns The fingerprints, sorted, with duplicates dropped.
89
+ */
90
+ export function signingKeys(found: FetchedInventory): string[] {
91
+ return [...new Set(found.checks.filter((check) => check.ok).map((check) => check.fingerprint))].sort();
92
+ }
93
+
94
+ /**
95
+ * Whether everything a fetch can settle came out right: at least one signature holds, and the document
96
+ * was served from the address it claims.
97
+ *
98
+ * This is not "this lab is who it says it is". It is "this document is internally consistent and came
99
+ * from the address you asked for". Whether that address is the lab you mean is something you knew
100
+ * before you typed it, or do not know at all.
101
+ *
102
+ * @param found - A fetched inventory.
103
+ * @returns Whether it is consistent and from its own address.
104
+ */
105
+ export function settled(found: FetchedInventory): boolean {
106
+ return found.fromItsOwnAddress && found.checks.some((check) => check.ok);
107
+ }
package/src/index.ts ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@biolibs/bionet`: labs publishing what they hold, so a cloning plan can be acted on and not just read.
4
+ *
5
+ * This package is **not a port**. Everything else in biolibs is measured against a Python library
6
+ * case by case; this has no upstream to be measured against. What it has instead is a question it is
7
+ * trying to answer honestly: a plan that replays is a plan you can believe, but belief is not a
8
+ * plasmid. Somebody has to have the parts.
9
+ *
10
+ * So a lab writes down what it holds, names each part by checksum rather than by its own name for it,
11
+ * signs the list with its key, and publishes it at a fixed path on its own web address. Fetch one and
12
+ * three separate things are settled: that the document is an inventory, that its signatures hold, and
13
+ * that it came from the address it claims. None of those is "this lab is who it says it is" — that you
14
+ * knew before you typed the address, or do not know at all. See `origin.ts`, which is blunt about it.
15
+ *
16
+ * - `model.ts` — what an inventory is
17
+ * - `inventory.ts` — writing one, signing one, reading a stranger's
18
+ * - `origin.ts` — where one lives, and what fetching it proves
19
+ * - `fetch.ts` — fetching and checking one
20
+ * - `discover.ts` — finding labs you were never told about, by walking from ones you were
21
+ * - `trust.ts` — remembering which key answered last time, so a change gets noticed
22
+ * - `match.ts` — what a plan needs, and who has it
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * import { fetchInventory, partsNeeded, settled, whoHas } from "@biolibs/bionet";
27
+ *
28
+ * const found = await fetchInventory("endylab.example");
29
+ * const sourcing = whoHas(partsNeeded(plan.document), settled(found) ? [found] : []);
30
+ *
31
+ * for (const { needed, holders } of sourcing) {
32
+ * console.log(needed.name, holders.map((holder) => holder.lab));
33
+ * }
34
+ * ```
35
+ */
36
+
37
+ export * from "./model.js";
38
+ export * from "./inventory.js";
39
+ export * from "./origin.js";
40
+ export * from "./fetch.js";
41
+ export * from "./discover.js";
42
+ export * from "./trust.js";
43
+ export * from "./match.js";
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Writing an inventory, signing one, and reading one a stranger published.
3
+ *
4
+ * Reading is the careful half. What arrives is a file from a web address, so `readInventory` checks
5
+ * its shape and its size before anything else looks at it, and says plainly what is wrong when it is
6
+ * wrong. Nothing here decides whether to believe an inventory — `fetch.ts` and `trust.ts` do that, and
7
+ * they have less to go on than you might like.
8
+ */
9
+ import type { Dseqrecord } from "@biolibs/dseqrecord";
10
+ import { signUnder, verifyUnder, type SignatureCheck, type SignOptions,
11
+ type SigningKey } from "@biolibs/opencloning";
12
+ import { INVENTORY_VERSION, type InventoryDocument, type InventoryPart, type LabModel,
13
+ type PeerModel, type SignedInventory } from "./model.js";
14
+ import { labOrigin } from "./origin.js";
15
+
16
+ /** What the bytes of a signed inventory are for. */
17
+ export const INVENTORY_DOMAIN = "biolibs/bionet signed inventory v1";
18
+
19
+ /** How many parts one inventory may list. */
20
+ export const MOST_PARTS = 5_000;
21
+ /** The longest an inventory may be, as text. */
22
+ export const LONGEST = 4_000_000;
23
+
24
+ /** How many labs one inventory may point at. */
25
+ export const MOST_PEERS = 200;
26
+
27
+ /** What `inventoryFrom` needs to know that the molecules cannot say. */
28
+ export interface InventoryOptions {
29
+ /** When to say it was published. Defaults to now. */
30
+ publishedAt?: string;
31
+ /** Whether the parts are on offer. Defaults to true. */
32
+ available?: boolean;
33
+ /** A note per part, by the part's name. */
34
+ notes?: Record<string, string>;
35
+ /**
36
+ * Other labs to point at, so that whoever reads this can go on to find them.
37
+ *
38
+ * Left out, the inventory carries no list at all rather than an empty one, which is what every
39
+ * inventory written before there were peers looks like.
40
+ */
41
+ peers?: readonly PeerModel[];
42
+ }
43
+
44
+ /**
45
+ * Write an inventory from the molecules a lab holds.
46
+ *
47
+ * @param records - The molecules.
48
+ * @param lab - Who is publishing, and from where.
49
+ * @param options - When, whether the parts are offered, and any notes.
50
+ * @returns The inventory, ready to sign.
51
+ *
52
+ * @example
53
+ * ```ts
54
+ * import { inventoryFrom, signInventory } from "@biolibs/bionet";
55
+ *
56
+ * const inventory = inventoryFrom([pUC19, insert], {
57
+ * name: "Endy lab", origin: "https://endylab.example", contact: null, note: null,
58
+ * });
59
+ * const published = await signInventory(inventory, key, { signer: "Endy lab" });
60
+ * ```
61
+ */
62
+ export function inventoryFrom(records: readonly Dseqrecord[], lab: LabModel,
63
+ options: InventoryOptions = {}): InventoryDocument {
64
+ const parts: InventoryPart[] = records.map((record, at) => {
65
+ const name = record.name === "" ? `part${at + 1}` : record.name;
66
+ return {
67
+ id: record.id === "" || record.id === null ? String(at + 1) : record.id,
68
+ name,
69
+ checksum: record.seguid(),
70
+ length: record.length,
71
+ circular: record.circular,
72
+ available: options.available ?? true,
73
+ note: options.notes?.[name] ?? null,
74
+ };
75
+ });
76
+ return {
77
+ bionet_inventory_version: INVENTORY_VERSION,
78
+ lab,
79
+ parts,
80
+ ...(options.peers === undefined ? {} : { peers: [...options.peers] }),
81
+ published_at: options.publishedAt ?? new Date().toISOString(),
82
+ };
83
+ }
84
+
85
+ /**
86
+ * Point at another lab, for an inventory's `peers`.
87
+ *
88
+ * @param address - Their address, however it was written.
89
+ * @param about - What to call them, the key you saw, and why you are pointing at them.
90
+ * @returns The pointer.
91
+ * @throws If the address is not one an inventory can be fetched from.
92
+ */
93
+ export function peer(address: string, about: { name?: string; key?: string; note?: string } = {}): PeerModel {
94
+ return {
95
+ origin: labOrigin(address),
96
+ name: about.name ?? null,
97
+ key: about.key ?? null,
98
+ note: about.note ?? null,
99
+ };
100
+ }
101
+
102
+ /**
103
+ * Sign an inventory, or add a signature to one already signed.
104
+ *
105
+ * A second signature on someone else's inventory is a lab vouching for it — that they have seen these
106
+ * parts, say. It is not required, and nothing treats it as more than one more key's claim.
107
+ *
108
+ * @param inventory - The inventory, signed or not.
109
+ * @param key - The key to sign with.
110
+ * @param options - A name to sign under, and when.
111
+ * @returns The signed inventory.
112
+ */
113
+ export async function signInventory(inventory: InventoryDocument | SignedInventory, key: SigningKey,
114
+ options: SignOptions = {}): Promise<SignedInventory> {
115
+ const held = isSignedInventory(inventory) ? inventory.inventory : inventory;
116
+ const already = isSignedInventory(inventory) ? inventory.signatures : [];
117
+ return { inventory: held, signatures: [...already, await signUnder(INVENTORY_DOMAIN, held, key, options)] };
118
+ }
119
+
120
+ /**
121
+ * Check every signature on an inventory.
122
+ *
123
+ * @param signed - The signed inventory.
124
+ * @returns One check per signature, in the same order. Never throws over a bad one.
125
+ */
126
+ export async function verifyInventory(signed: SignedInventory): Promise<SignatureCheck[]> {
127
+ return verifyUnder(INVENTORY_DOMAIN, signed.inventory, signed.signatures);
128
+ }
129
+
130
+ /** @param value - Anything. @returns Whether it is an inventory with signatures beside it. */
131
+ export function isSignedInventory(value: unknown): value is SignedInventory {
132
+ const held = value as Partial<SignedInventory> | null;
133
+ return held !== null && typeof held === "object"
134
+ && Array.isArray(held.signatures) && typeof held.inventory === "object" && held.inventory !== null;
135
+ }
136
+
137
+ /**
138
+ * Say whether a field is absent, or text no longer than it is allowed to be.
139
+ *
140
+ * @param value - The field.
141
+ * @param most - How long it may be.
142
+ * @returns Whether it will do.
143
+ */
144
+ const sayable = (value: unknown, most: number): boolean =>
145
+ value === null || value === undefined || (typeof value === "string" && value.length <= most);
146
+
147
+ /**
148
+ * Read a signed inventory somebody else published.
149
+ *
150
+ * What comes back is the document **exactly as it arrived**, not a tidied copy of it. That matters:
151
+ * the signature covers the bytes the lab wrote, so trimming a long note or filling in a missing field
152
+ * here would leave a document that no longer matches its own signature. Anything out of bounds is
153
+ * therefore refused rather than repaired, and anything over-long is a display problem for whatever
154
+ * shows it.
155
+ *
156
+ * @param value - The parsed JSON.
157
+ * @returns The inventory and its signatures, untouched.
158
+ * @throws If it is not an inventory, or holds a field this will not carry.
159
+ */
160
+ export function readInventory(value: unknown): SignedInventory {
161
+ if (!isSignedInventory(value)) throw new Error("This is not a signed inventory.");
162
+ const held = value.inventory as Partial<InventoryDocument>;
163
+ const lab = held.lab as Partial<LabModel> | undefined;
164
+ if (typeof lab?.name !== "string" || typeof lab.origin !== "string") {
165
+ throw new Error("This inventory does not say which lab published it, or from where.");
166
+ }
167
+ if (lab.name.length > 200 || lab.origin.length > 500 || !sayable(lab.contact, 200) || !sayable(lab.note, 2_000)) {
168
+ throw new Error("This inventory says more about the lab than will be carried.");
169
+ }
170
+ if (!Array.isArray(held.parts)) throw new Error("This inventory has no list of parts.");
171
+ if (held.parts.length > MOST_PARTS) throw new Error(`An inventory may list at most ${MOST_PARTS} parts.`);
172
+ for (const part of held.parts as Partial<InventoryPart>[]) {
173
+ if (typeof part?.checksum !== "string" || !Number.isInteger(part.length) || part.length! < 0
174
+ || part.checksum.length > 120 || !sayable(part.id, 200) || !sayable(part.name, 200)
175
+ || !sayable(part.note, 2_000)) {
176
+ throw new Error("This inventory lists something that is not a part.");
177
+ }
178
+ }
179
+ if (held.peers !== undefined) {
180
+ if (!Array.isArray(held.peers)) throw new Error("This inventory's list of other labs is not a list.");
181
+ if (held.peers.length > MOST_PEERS) throw new Error(`An inventory may point at most ${MOST_PEERS} labs.`);
182
+ for (const one of held.peers as Partial<PeerModel>[]) {
183
+ if (typeof one?.origin !== "string" || one.origin.length > 500
184
+ || !sayable(one.name, 200) || !sayable(one.key, 120) || !sayable(one.note, 2_000)) {
185
+ throw new Error("This inventory points at something that is not a lab.");
186
+ }
187
+ }
188
+ }
189
+ if (!sayable(held.published_at, 40)) throw new Error("This inventory's publication time is not a time.");
190
+ return value;
191
+ }
package/src/match.ts ADDED
@@ -0,0 +1,128 @@
1
+ /**
2
+ * What a plan needs before anyone can run it, and which labs have it.
3
+ *
4
+ * A cloning plan bottoms out in molecules nobody made: the parts that were simply had. Replaying the
5
+ * plan proves the product follows from those parts, which is worth a great deal and still leaves the
6
+ * reader holding nothing. This is the step that turns a checked plan into something a lab can act on —
7
+ * take the plan's leaves, and ask who has them.
8
+ *
9
+ * Parts are matched by checksum, never by name. A SEGUID is the same whichever strand the molecule was
10
+ * written from and, for a circle, wherever it was cut open, so two labs that have never spoken publish
11
+ * the same checksum for the same molecule. A name agrees with nothing.
12
+ */
13
+ import { recordFromSequenceModel, type CloningStrategyDocument } from "@biolibs/opencloning";
14
+ import type { FetchedInventory } from "./fetch.js";
15
+ import type { InventoryPart } from "./model.js";
16
+
17
+ /** One molecule a plan starts from. */
18
+ export interface NeededPart {
19
+ /** Its identifier within the plan. */
20
+ id: number;
21
+ /** What the plan calls it. */
22
+ name: string;
23
+ /** Its SEGUID checksum, which is what labs are asked about. */
24
+ checksum: string;
25
+ /** How many base pairs. */
26
+ length: number;
27
+ /** Whether it is a circle. */
28
+ circular: boolean;
29
+ }
30
+
31
+ /** A lab that has a part. */
32
+ export interface Holder {
33
+ /** The lab's address. */
34
+ origin: string;
35
+ /** What the lab calls itself. */
36
+ lab: string;
37
+ /** The part as that lab lists it. */
38
+ part: InventoryPart;
39
+ }
40
+
41
+ /** A part a plan needs, and who has it. */
42
+ export interface Sourcing {
43
+ /** The part. */
44
+ needed: NeededPart;
45
+ /** The labs listing a molecule with this checksum, in the order the inventories were given. */
46
+ holders: Holder[];
47
+ }
48
+
49
+ /**
50
+ * The molecules a plan starts from: the ones no step in it makes.
51
+ *
52
+ * @param document - The plan.
53
+ * @returns One entry per starting molecule, with its checksum.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * import { partsNeeded } from "@biolibs/bionet";
58
+ *
59
+ * partsNeeded(plan.document).map((part) => part.name); // [ "f1", "f2", "f3" ]
60
+ * ```
61
+ */
62
+ export function partsNeeded(document: CloningStrategyDocument): NeededPart[] {
63
+ const made = new Set(document.sources.filter((source) => source.input.length > 0).map((source) => source.id));
64
+ const names = new Map(document.sources.map((source) => [source.id, source.output_name]));
65
+ const needed: NeededPart[] = [];
66
+ for (const sequence of document.sequences) {
67
+ if (made.has(sequence.id)) continue;
68
+ const record = recordFromSequenceModel(sequence);
69
+ needed.push({
70
+ id: sequence.id,
71
+ name: names.get(sequence.id) ?? record.name,
72
+ checksum: record.seguid(),
73
+ length: record.length,
74
+ circular: record.circular,
75
+ });
76
+ }
77
+ return needed;
78
+ }
79
+
80
+ /**
81
+ * Ask a set of inventories who has each of a plan's starting molecules.
82
+ *
83
+ * Inventories whose signatures do not hold, or that were not served from the address they claim, are
84
+ * the caller's to filter out first — `settled` in `fetch.ts` says which those are. This matches what
85
+ * it is given, and says nothing about whether the labs are to be believed.
86
+ *
87
+ * @param needed - What the plan needs.
88
+ * @param inventories - The inventories to ask.
89
+ * @returns One entry per needed part, with the labs that list it.
90
+ */
91
+ export function whoHas(needed: readonly NeededPart[], inventories: readonly FetchedInventory[]): Sourcing[] {
92
+ return needed.map((part) => {
93
+ const holders: Holder[] = [];
94
+ for (const found of inventories) {
95
+ for (const listed of found.signed.inventory.parts) {
96
+ if (listed.checksum === part.checksum) {
97
+ holders.push({ origin: found.origin, lab: found.signed.inventory.lab.name, part: listed });
98
+ }
99
+ }
100
+ }
101
+ return { needed: part, holders };
102
+ });
103
+ }
104
+
105
+ /**
106
+ * The parts nobody asked has.
107
+ *
108
+ * @param sourcing - What `whoHas` worked out.
109
+ * @returns The parts with no holder.
110
+ */
111
+ export function unsourced(sourcing: readonly Sourcing[]): NeededPart[] {
112
+ return sourcing.filter((one) => one.holders.length === 0).map((one) => one.needed);
113
+ }
114
+
115
+ /**
116
+ * The parts a lab has but will not send.
117
+ *
118
+ * Listing a part without offering it is a normal thing for a lab to do, and a reader is better off
119
+ * knowing the molecule exists somewhere than being told nobody has it.
120
+ *
121
+ * @param sourcing - What `whoHas` worked out.
122
+ * @returns The parts whose every holder has them marked unavailable.
123
+ */
124
+ export function heldButNotOffered(sourcing: readonly Sourcing[]): NeededPart[] {
125
+ return sourcing
126
+ .filter((one) => one.holders.length > 0 && one.holders.every((holder) => !holder.part.available))
127
+ .map((one) => one.needed);
128
+ }