@intellectual-frontiers/integrations 0.0.0-stage → 0.1.1

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 (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +8 -2
  3. package/dist/governance/exchange.d.ts +224 -0
  4. package/dist/governance/exchange.js +86 -0
  5. package/dist/governance/ids.d.ts +61 -0
  6. package/dist/governance/ids.js +53 -0
  7. package/dist/governance/mod.d.ts +11 -0
  8. package/dist/governance/mod.js +12 -0
  9. package/dist/governance/observe.d.ts +172 -0
  10. package/dist/governance/observe.js +139 -0
  11. package/dist/logical/conformance.d.ts +44 -0
  12. package/dist/logical/conformance.js +108 -0
  13. package/dist/logical/constraints.d.ts +86 -0
  14. package/dist/logical/constraints.js +112 -0
  15. package/dist/logical/exchange.d.ts +98 -0
  16. package/dist/logical/exchange.js +135 -0
  17. package/dist/logical/ledger.d.ts +94 -0
  18. package/dist/logical/ledger.js +90 -0
  19. package/dist/logical/mapping.d.ts +64 -0
  20. package/dist/logical/mapping.js +99 -0
  21. package/dist/logical/mod.d.ts +18 -0
  22. package/dist/logical/mod.js +19 -0
  23. package/dist/logical/observe.d.ts +222 -0
  24. package/dist/logical/observe.js +156 -0
  25. package/dist/logical/plugin.d.ts +91 -0
  26. package/dist/logical/plugin.js +53 -0
  27. package/dist/logical/ports.d.ts +102 -0
  28. package/dist/logical/ports.js +31 -0
  29. package/dist/logical/registry.d.ts +72 -0
  30. package/dist/logical/registry.js +81 -0
  31. package/dist/logical/tree.d.ts +91 -0
  32. package/dist/logical/tree.js +114 -0
  33. package/dist/mod.d.ts +15 -0
  34. package/dist/mod.js +16 -0
  35. package/dist/physical/http/mod.d.ts +54 -0
  36. package/dist/physical/http/mod.js +114 -0
  37. package/dist/physical/transport/mod.d.ts +79 -0
  38. package/dist/physical/transport/mod.js +61 -0
  39. package/dist/surfaces/headless/mod.d.ts +46 -0
  40. package/dist/surfaces/headless/mod.js +258 -0
  41. package/package.json +67 -4
  42. package/src/governance/exchange.ts +220 -0
  43. package/src/governance/ids.ts +92 -0
  44. package/src/governance/mod.ts +12 -0
  45. package/src/governance/observe.ts +226 -0
  46. package/src/logical/conformance.ts +113 -0
  47. package/src/logical/constraints.ts +154 -0
  48. package/src/logical/exchange.ts +184 -0
  49. package/src/logical/ledger.ts +123 -0
  50. package/src/logical/mapping.ts +114 -0
  51. package/src/logical/mod.ts +19 -0
  52. package/src/logical/observe.ts +314 -0
  53. package/src/logical/plugin.ts +102 -0
  54. package/src/logical/ports.ts +89 -0
  55. package/src/logical/registry.ts +93 -0
  56. package/src/logical/tree.ts +153 -0
  57. package/src/mod.ts +16 -0
  58. package/src/physical/http/mod.ts +134 -0
  59. package/src/physical/transport/mod.ts +85 -0
  60. package/src/surfaces/headless/mod.ts +293 -0
@@ -0,0 +1,93 @@
1
+ // Spec: 0005-integrations-observe FR-009, FR-010, FR-011
2
+ /**
3
+ * The registry of connectors (commons integrations 0005-integrations-observe): a typed map from a connector id to an entry that pins where the connector came
4
+ * from (a tag or a commit, never a branch) and the SHA-256 of what was taken, a lock that is a persisted document, and the verification of a copy against its pin.
5
+ * Which connectors a consumer runs is the consumer's choice; this is what makes a choice safe to keep.
6
+ *
7
+ * @module
8
+ */
9
+ import { array, err, integer, literal, object, ok, string, type DecodeError, type Result } from "@intellectual-frontiers/core";
10
+ import { parseConnectorId, parseInstant, parseSha256, type ConnectorId, type Instant, type Sha256 } from "@intellectual-frontiers/integrations/governance";
11
+
12
+ /** What a source is pinned to: a release tag, or a full commit. Never a branch, which moves. */
13
+ export type PinRef = { readonly kind: "tag"; readonly name: string } | { readonly kind: "commit"; readonly sha: string };
14
+
15
+ /** Where a connector's code comes from, pinned. */
16
+ export type PinnedSource = { readonly url: string; readonly ref: PinRef };
17
+
18
+ /** Why a source is refused. */
19
+ export type SourceError = { readonly kind: "no-pin" } | { readonly kind: "not-https" } | { readonly kind: "branch-not-pinned" };
20
+
21
+ /** A source from `<https url>@<tag or 40-hex commit>`; a ref that is neither a version tag (`v1.2.3`, `1.2.3`) nor a full commit is a branch and is refused. */
22
+ export function pinSource(text: string): Result<PinnedSource, SourceError> {
23
+ const at = text.lastIndexOf("@");
24
+ if (at <= 0) return err({ kind: "no-pin" });
25
+ const url = text.slice(0, at);
26
+ const ref = text.slice(at + 1);
27
+ if (!url.startsWith("https://")) return err({ kind: "not-https" });
28
+ if (/^[0-9a-f]{40}$/.test(ref)) return ok({ url, ref: { kind: "commit", sha: ref } });
29
+ if (/^v?\d+\.\d+\.\d+([-+][0-9A-Za-z.-]+)?$/.test(ref)) return ok({ url, ref: { kind: "tag", name: ref } });
30
+ return err({ kind: "branch-not-pinned" });
31
+ }
32
+
33
+ /** The version of the connector contract an entry was written for. */
34
+ export const CONTRACT = 1;
35
+
36
+ /** One entry of the registry. */
37
+ export type RegistryEntry = { readonly id: ConnectorId; readonly title: string; readonly source: PinnedSource; readonly sha256: Sha256; readonly contract: typeof CONTRACT; readonly added: Instant };
38
+
39
+ /** The registry: entries by connector id. */
40
+ export type ConnectorRegistry = ReadonlyMap<ConnectorId, RegistryEntry>;
41
+
42
+ /** Why an entry is not added or a copy not accepted. */
43
+ export type LockError = { readonly kind: "duplicate"; readonly id: ConnectorId } | { readonly kind: "digest-mismatch"; readonly id: ConnectorId; readonly expected: Sha256; readonly actual: Sha256 } | { readonly kind: "unknown"; readonly id: ConnectorId };
44
+
45
+ /** The registry with one more entry, or why not. */
46
+ export function addEntry(reg: ConnectorRegistry, e: RegistryEntry): Result<ConnectorRegistry, LockError> {
47
+ return reg.has(e.id) ? err({ kind: "duplicate", id: e.id }) : ok(new Map([...reg, [e.id, e]]));
48
+ }
49
+
50
+ /** Whether a copy with the digest `actual` is what the registry pinned for `id`. */
51
+ export function verifyCopy(reg: ConnectorRegistry, id: ConnectorId, actual: Sha256): Result<RegistryEntry, LockError> {
52
+ const e = reg.get(id);
53
+ if (e === undefined) return err({ kind: "unknown", id });
54
+ return e.sha256 === actual ? ok(e) : err({ kind: "digest-mismatch", id, expected: e.sha256, actual });
55
+ }
56
+
57
+ /** The schema id of a persisted lock. */
58
+ export const LOCK_SCHEMA = "integrations/connector-lock/1";
59
+
60
+ /** A lock as the document that is persisted: entries in the order of their ids, so that the same registry is the same text. */
61
+ export function lockDocument(reg: ConnectorRegistry): { readonly kind: "connector-lock"; readonly schema: typeof LOCK_SCHEMA; readonly entries: readonly RegistryEntry[] } {
62
+ return { kind: "connector-lock", schema: LOCK_SCHEMA, entries: [...reg.values()].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)) };
63
+ }
64
+
65
+ const pinRefD = (input: unknown, path = "$"): Result<PinRef, DecodeError> => {
66
+ const o = object({ kind: literal("tag", "commit") }, { name: string, sha: string })(input, path);
67
+ if (o.kind === "err") return o;
68
+ if (o.value.kind === "tag") return o.value.name === undefined ? err({ kind: "decode", path: `${path}.name`, expected: "a tag name", found: "nothing" }) : ok({ kind: "tag", name: o.value.name });
69
+ return o.value.sha === undefined ? err({ kind: "decode", path: `${path}.sha`, expected: "a commit", found: "nothing" }) : ok({ kind: "commit", sha: o.value.sha });
70
+ };
71
+
72
+ /** Reads a persisted lock back into a registry, refusing a document of another kind or schema, an id or digest that is not one, and an id twice. */
73
+ export function parseLock(input: unknown): Result<ConnectorRegistry, DecodeError | LockError> {
74
+ const doc = object({ kind: literal("connector-lock"), schema: literal(LOCK_SCHEMA), entries: array((x) => ok(x)) })(input);
75
+ if (doc.kind === "err") return doc;
76
+ let reg: ConnectorRegistry = new Map();
77
+ for (const [i, raw] of doc.value.entries.entries()) {
78
+ const path = `$.entries[${i}]`;
79
+ const e = object({ id: string, title: string, source: object({ url: string, ref: pinRefD }), sha256: string, contract: integer, added: string })(raw, path);
80
+ if (e.kind === "err") return e;
81
+ const id = parseConnectorId(e.value.id);
82
+ const sha = parseSha256(e.value.sha256);
83
+ const added = parseInstant(e.value.added);
84
+ if (id.kind === "err") return err({ kind: "decode", path: `${path}.id`, expected: id.error.expected, found: "a text that is not that" });
85
+ if (sha.kind === "err") return err({ kind: "decode", path: `${path}.sha256`, expected: sha.error.expected, found: "a text that is not that" });
86
+ if (added.kind === "err") return err({ kind: "decode", path: `${path}.added`, expected: added.error.expected, found: "a text that is not that" });
87
+ if (e.value.contract !== CONTRACT) return err({ kind: "decode", path: `${path}.contract`, expected: String(CONTRACT), found: String(e.value.contract) });
88
+ const next = addEntry(reg, { id: id.value, title: e.value.title, source: e.value.source, sha256: sha.value, contract: CONTRACT, added: added.value });
89
+ if (next.kind === "err") return next;
90
+ reg = next.value;
91
+ }
92
+ return ok(reg);
93
+ }
@@ -0,0 +1,153 @@
1
+ // Spec: 0006-integrations-exchange FR-001, FR-002, FR-003
2
+ /**
3
+ * The abstract typed tree of exchange (commons integrations 0006-integrations-exchange): an interchange of groups of transactions of segments and loops of
4
+ * elements, the one shape that X12, HL7 v2, EDIFACT and FHIR all map to, so that validation, mapping and redaction are written once.
5
+ *
6
+ * @remarks
7
+ * A path is the ids from the transaction down, joined by `.`, an element with an empty id (the value of a segment that is one value, a primitive of FHIR) adding
8
+ * nothing: `Patient.birthDate`, `PID.05`, `NM1.03`. A path with no indices is the path of the schema; an indexed one (`Patient.name[0].family`) is of one instance.
9
+ *
10
+ * @module
11
+ */
12
+ import type { Ref } from "@intellectual-frontiers/integrations/governance";
13
+
14
+ /** An element: one value, which may have components (an HL7 v2 composite, an X12 composite). */
15
+ export type Element = { readonly kind: "element"; readonly id: string; readonly value: string; readonly components: readonly Element[] };
16
+ /** A segment: a named run of elements. */
17
+ export type Segment = { readonly kind: "segment"; readonly id: string; readonly elements: readonly Element[] };
18
+ /** A loop: a named run of segments and loops. */
19
+ export type Loop = { readonly kind: "loop"; readonly id: string; readonly children: readonly Part[] };
20
+ /** What a loop or a transaction holds. */
21
+ export type Part = Segment | Loop;
22
+ /** The segments that open and close a node, where its syntax has them (X12's ISA and IEA, GS and GE, ST and SE): kept so that what was read is written back and its control counts can be checked. */
23
+ export type Envelope = { readonly header: readonly Segment[]; readonly trailer: readonly Segment[] };
24
+ /** A transaction: one message or document (an 837, an ADT^A01, a FHIR resource). */
25
+ export type Transaction = { readonly kind: "transaction"; readonly id: string; readonly control: string; readonly children: readonly Part[]; readonly envelope?: Envelope };
26
+ /** A group of transactions of one kind. */
27
+ export type Group = { readonly kind: "group"; readonly id: string; readonly control: string; readonly transactions: readonly Transaction[]; readonly envelope?: Envelope };
28
+ /** An interchange: what is sent in one go, in one syntax. */
29
+ export type Interchange = { readonly kind: "interchange"; readonly syntax: Ref<"syntax">; readonly control: string; readonly groups: readonly Group[]; readonly envelope?: Envelope };
30
+ /** Any node of the tree. */
31
+ export type TreeNode = Interchange | Group | Transaction | Part | Element;
32
+
33
+ /** An element. */
34
+ export const element = (id: string, value: string, components: readonly Element[] = []): Element => ({ kind: "element", id, value, components });
35
+ /** A segment. */
36
+ export const segment = (id: string, ...elements: readonly Element[]): Segment => ({ kind: "segment", id, elements });
37
+ /** A loop. */
38
+ export const loop = (id: string, ...children: readonly Part[]): Loop => ({ kind: "loop", id, children });
39
+
40
+ /** One value of a tree, with where it is. */
41
+ export type Entry = { readonly path: string; readonly at: string; readonly value: string };
42
+
43
+ const join = (a: string, b: string): string => (a === "" ? b : b === "" ? a : `${a}.${b}`);
44
+
45
+ /** Calls `visit` for each element (components included) of a transaction, with its path and its indexed path. */
46
+ function walkParts(parts: readonly Part[], path: string, at: string, visit: (e: Element, path: string, at: string) => void, node: (kind: "segment" | "loop", path: string, at: string, parent: string) => void): void {
47
+ const seen = new Map<string, number>();
48
+ for (const p of parts) {
49
+ const k = seen.get(`${p.kind}:${p.id}`) ?? 0;
50
+ seen.set(`${p.kind}:${p.id}`, k + 1);
51
+ const here = join(path, p.id);
52
+ const hereAt = `${join(at, p.id)}[${k}]`;
53
+ node(p.kind, here, hereAt, at);
54
+ switch (p.kind) {
55
+ case "segment":
56
+ for (const e of p.elements) walkElement(e, here, hereAt, visit);
57
+ break;
58
+ case "loop":
59
+ walkParts(p.children, here, hereAt, visit, node);
60
+ break;
61
+ }
62
+ }
63
+ }
64
+
65
+ function walkElement(e: Element, path: string, at: string, visit: (e: Element, path: string, at: string) => void): void {
66
+ const here = join(path, e.id);
67
+ const hereAt = e.id === "" ? at : join(at, e.id);
68
+ visit(e, here, hereAt);
69
+ for (const c of e.components) walkElement(c, here, hereAt, visit);
70
+ }
71
+
72
+ /** Every value of a transaction, in order, as entries. */
73
+ export function entries(t: Transaction): readonly Entry[] {
74
+ const out: Entry[] = [];
75
+ walkParts(t.children, t.id, t.id, (e, path, at) => out.push({ path, at, value: e.value }), () => undefined);
76
+ return out;
77
+ }
78
+
79
+ /** Every transaction of an interchange, in order. */
80
+ export const transactionsOf = (i: Interchange): readonly Transaction[] => i.groups.flatMap((g) => g.transactions);
81
+
82
+ /** The paths of a transaction (no indices), each once, in order of first appearance: its segments, loops and elements. */
83
+ export function pathsOf(t: Transaction): readonly string[] {
84
+ const seen = new Set<string>();
85
+ walkParts(t.children, t.id, t.id, (_e, path) => seen.add(path), (_k, path) => seen.add(path));
86
+ return [...seen];
87
+ }
88
+
89
+ /** How many times each node of a path occurs under each instance of its parent: `[parent instance, count]`; the root is the transaction itself. */
90
+ export function occurrences(t: Transaction, path: string): readonly (readonly [string, number])[] {
91
+ const counts = new Map<string, number>();
92
+ const parentOf = path.includes(".") ? path.slice(0, path.lastIndexOf(".")) : "";
93
+ walkParts(
94
+ t.children,
95
+ t.id,
96
+ t.id,
97
+ (e, p, at) => {
98
+ if (p === path && e.id !== "") {
99
+ const parent = at.slice(0, at.lastIndexOf("."));
100
+ counts.set(parent, (counts.get(parent) ?? 0) + 1);
101
+ }
102
+ },
103
+ (_kind, p, at, parent) => {
104
+ if (p === path) counts.set(parent, (counts.get(parent) ?? 0) + 1);
105
+ else if (p === parentOf) counts.set(at, counts.get(at) ?? 0);
106
+ },
107
+ );
108
+ if (path === t.id) return [[t.id, 1]];
109
+ if (parentOf === t.id && counts.size === 0) return [[t.id, 0]];
110
+ return [...counts];
111
+ }
112
+
113
+ /** Every distinct value of a tree, longest first: what a scrub of a text must hide. */
114
+ export function valuesOf(i: Interchange): readonly string[] {
115
+ const out = new Set<string>();
116
+ const envelopes = [i.envelope, ...i.groups.flatMap((g) => [g.envelope, ...g.transactions.map((t) => t.envelope)])];
117
+ for (const env of envelopes) for (const s of [...(env?.header ?? []), ...(env?.trailer ?? [])]) for (const e of s.elements) if (e.value.trim() !== "") out.add(e.value.trim());
118
+ for (const t of transactionsOf(i)) for (const e of entries(t)) if (e.value !== "") out.add(e.value);
119
+ return [...out].sort((a, b) => b.length - a.length);
120
+ }
121
+
122
+ /** The text that stands where a value was hidden. */
123
+ export const HIDDEN = "[redacted]";
124
+
125
+ function redactElement(e: Element, path: string, hide: (path: string) => boolean): Element {
126
+ const here = join(path, e.id);
127
+ const hidden = hide(here);
128
+ return { kind: "element", id: e.id, value: hidden && e.value !== "" ? HIDDEN : e.value, components: e.components.map((c) => redactElement(c, here, hide)) };
129
+ }
130
+
131
+ function redactParts(parts: readonly Part[], path: string, hide: (path: string) => boolean): readonly Part[] {
132
+ return parts.map((p): Part => {
133
+ const here = join(path, p.id);
134
+ switch (p.kind) {
135
+ case "segment":
136
+ return { kind: "segment", id: p.id, elements: p.elements.map((e) => redactElement(e, here, hide)) };
137
+ case "loop":
138
+ return { kind: "loop", id: p.id, children: redactParts(p.children, here, hide) };
139
+ }
140
+ });
141
+ }
142
+
143
+ /** The interchange with every value hidden whose path (no indices) `hide` says, or whose ancestor path it says: redaction is written once for every syntax. */
144
+ export function redactTree(i: Interchange, hide: (path: string) => boolean): Interchange {
145
+ const covered = (path: string): boolean => {
146
+ for (let p = path; p !== ""; p = p.includes(".") ? p.slice(0, p.lastIndexOf(".")) : "") if (hide(p)) return true;
147
+ return false;
148
+ };
149
+ return { ...i, groups: i.groups.map((g) => ({ ...g, transactions: g.transactions.map((t) => ({ ...t, children: redactParts(t.children, t.id, covered) })) })) };
150
+ }
151
+
152
+ /** A predicate that hides every path equal to, or below, one of `paths`: what minimum-necessary does when it lists the elements a recipient may have (`allowed`), hiding the rest. */
153
+ export const hidingAllBut = (allowed: readonly string[]): ((path: string) => boolean) => (path) => !allowed.some((a) => a === path || a.startsWith(`${path}.`) || path.startsWith(`${a}.`));
package/src/mod.ts ADDED
@@ -0,0 +1,16 @@
1
+ // Spec: 0001-integrations-layers FR-001
2
+ /**
3
+ * Integrations (commons integrations 0001-integrations-layers): the governance and logical layers, whole, for a program that wants both families (observe and
4
+ * exchange) through one entry. The physical adapters (`./http`, `./transport`) and the headless verbs (`./headless`) have entries of their own, because each
5
+ * reaches something (a network, Headless) that a pure consumer does not want.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { cadence } from "@intellectual-frontiers/integrations";
10
+ * cadence("15m").kind; // "ok": stale after 30 minutes
11
+ * ```
12
+ *
13
+ * @module
14
+ */
15
+ export * from "./governance/mod.ts";
16
+ export * from "./logical/mod.ts";
@@ -0,0 +1,134 @@
1
+ // Spec: 0001-integrations-layers FR-003; 0004-integrations-physical FR-001, FR-002, FR-003
2
+ /**
3
+ * The HTTP adapter of observation (commons integrations 0004-integrations-physical): the read port of the logical layer made on Net's transport, with the read-only guard
4
+ * (only safe methods, and POST only to the declared token endpoints), backoff on 429 and 503, pages by `Link` or by a cursor of the body, bearer or signed requests, and a
5
+ * digest of what was fetched. It is the physical edge: the only place of observation that reaches a network.
6
+ *
7
+ * @remarks
8
+ * A failure names the path of the request and never its query, its headers or its body, so that no credential or personal datum is said.
9
+ *
10
+ * @module
11
+ */
12
+ import { absurd, err, ok, unknownValue, type Result } from "@intellectual-frontiers/core";
13
+ import { cursorPages, linkPages, readOnly, withBackoff, withSigV4, type ReadError, type SigV4TransportOptions, type Transport } from "@intellectual-frontiers/net/http-client";
14
+ import { parseSha256, type IdError, type Sha256 } from "@intellectual-frontiers/integrations/governance";
15
+ import type { Json, ReadFailure, ReadPort, Secret } from "@intellectual-frontiers/integrations/logical";
16
+
17
+ /** How a list pages: by the `Link` header, or by a cursor in the body (`items` takes a page's items, `next` the next page's path or undefined). */
18
+ export type Paging =
19
+ | { readonly kind: "link" }
20
+ | { readonly kind: "cursor"; readonly items: (body: Json) => readonly Json[]; readonly next: (body: Json, path: string) => string | undefined };
21
+
22
+ /** How the requests are authorized. */
23
+ export type Auth =
24
+ | { readonly kind: "bearer"; readonly secret: Secret; readonly scheme: string }
25
+ | { readonly kind: "header"; readonly name: string; readonly secret: Secret }
26
+ | { readonly kind: "sigv4"; readonly options: SigV4TransportOptions }
27
+ | { readonly kind: "none" };
28
+
29
+ /** What the read port of a system is made of. */
30
+ export type HttpReadOptions = {
31
+ readonly transport: Transport;
32
+ readonly base: string;
33
+ readonly auth: Auth;
34
+ readonly tokenEndpoints?: readonly string[];
35
+ readonly headers?: Readonly<Record<string, string>>;
36
+ readonly paging?: Paging;
37
+ readonly maxPages?: number;
38
+ readonly pause?: (ms: number) => Promise<void>;
39
+ };
40
+
41
+ /** A failure of the read as the logical layer says it: what was asked and what came, never a payload. */
42
+ export function failureOf(e: ReadError): ReadFailure {
43
+ const subject = (url: string): string => {
44
+ try {
45
+ return new URL(url).pathname;
46
+ } catch {
47
+ return "(unparsable url)";
48
+ }
49
+ };
50
+ switch (e.kind) {
51
+ case "refused":
52
+ case "network":
53
+ return { kind: "network", subject: "(request)" };
54
+ case "denied":
55
+ return { kind: "denied", subject: subject(e.url) };
56
+ case "status":
57
+ return e.status === 404 ? { kind: "not-found", subject: subject(e.url) } : e.status === 429 ? { kind: "rate-limited", subject: subject(e.url) } : { kind: "server", subject: subject(e.url), status: e.status };
58
+ case "decode":
59
+ return { kind: "decode", subject: subject(e.url) };
60
+ default:
61
+ return absurd(e);
62
+ }
63
+ }
64
+
65
+ function headersOf(auth: Auth, extra: Readonly<Record<string, string>>): Readonly<Record<string, string>> {
66
+ switch (auth.kind) {
67
+ case "bearer":
68
+ return { ...extra, authorization: `${auth.scheme} ${auth.secret.reveal()}` };
69
+ case "header":
70
+ return { ...extra, [auth.name]: auth.secret.reveal() };
71
+ case "sigv4":
72
+ case "none":
73
+ return extra;
74
+ default:
75
+ return absurd(auth);
76
+ }
77
+ }
78
+
79
+ /** The read port of a system over a transport: read-only, backing off, paged, authorized; no write is possible through it. */
80
+ export function httpReadPort(o: HttpReadOptions): ReadPort {
81
+ const guarded = readOnly(o.transport, o.tokenEndpoints ?? []);
82
+ const signed = o.auth.kind === "sigv4" ? withSigV4(guarded, o.auth.options) : guarded;
83
+ const t = withBackoff(signed, o.pause === undefined ? {} : { pause: o.pause });
84
+ const headers = headersOf(o.auth, o.headers ?? {});
85
+ const url = (path: string): string => (path.startsWith("https://") ? path : `${o.base}${path}`);
86
+ const paging = o.paging ?? { kind: "link" };
87
+ const maxPages = o.maxPages === undefined ? {} : { maxPages: o.maxPages };
88
+ return {
89
+ get: async (path) => {
90
+ const x = await t.send({ method: "GET", url: url(path), headers: { accept: "application/json", ...headers } });
91
+ if (x.kind === "err") return err({ kind: "network", subject: "(request)" });
92
+ const status = x.value.status;
93
+ if (status === 401 || status === 403) return err({ kind: "denied", subject: path.split("?")[0] ?? path });
94
+ if (status === 404) return err({ kind: "not-found", subject: path.split("?")[0] ?? path });
95
+ if (status === 429) return err({ kind: "rate-limited", subject: path.split("?")[0] ?? path });
96
+ if (status >= 400) return err({ kind: "server", subject: path.split("?")[0] ?? path, status });
97
+ try {
98
+ const body: Json = JSON.parse(x.value.body) as Json;
99
+ return ok(body);
100
+ } catch {
101
+ return err({ kind: "decode", subject: path.split("?")[0] ?? path });
102
+ }
103
+ },
104
+ pages: async function* (path) {
105
+ switch (paging.kind) {
106
+ case "link": {
107
+ const g = linkPages(t, url(path), unknownValue, { headers, ...maxPages });
108
+ for (;;) {
109
+ const n = await g.next();
110
+ if (n.done === true) return n.value.kind === "ok" ? n.value : err(failureOf(n.value.error));
111
+ yield n.value as Json;
112
+ }
113
+ }
114
+ case "cursor": {
115
+ const g = cursorPages(t, url(path), unknownValue, (b) => paging.items(b as Json), (b, u) => paging.next(b as Json, u), { headers, ...maxPages });
116
+ for (;;) {
117
+ const n = await g.next();
118
+ if (n.done === true) return n.value.kind === "ok" ? n.value : err(failureOf(n.value.error));
119
+ yield n.value as Json;
120
+ }
121
+ }
122
+ default:
123
+ return absurd(paging);
124
+ }
125
+ },
126
+ };
127
+ }
128
+
129
+ /** The SHA-256 of a text, as the library's digest. */
130
+ export async function sha256Of(text: string): Promise<Result<Sha256, IdError>> {
131
+ const bytes = new TextEncoder().encode(text);
132
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
133
+ return parseSha256([...digest].map((b) => b.toString(16).padStart(2, "0")).join(""));
134
+ }
@@ -0,0 +1,85 @@
1
+ // Spec: 0004-integrations-physical FR-004, FR-005, FR-006
2
+ /**
3
+ * The transports of exchange (commons integrations 0004-integrations-physical): an `ExchangeTransport` is a port, a record of functions, and this module gives HTTPS on
4
+ * Net's transport (a POST of a document to a partner's endpoint, with a bearer secret), the token request of OAuth2 backend services in the manner of SMART (a client
5
+ * credentials grant with a signed assertion, the signing a port), and the framing of MLLP over TCP. SFTP, AS2 and AS4 are specified and Planned.
6
+ *
7
+ * @remarks
8
+ * What a partner answers is a payload: it is returned to the caller and never put in a failure, a log or a trace; a failure holds a kind and a status.
9
+ *
10
+ * @module
11
+ */
12
+ import { err, ok, type Result } from "@intellectual-frontiers/core";
13
+ import type { Transport } from "@intellectual-frontiers/net/http-client";
14
+ import type { Secret } from "@intellectual-frontiers/integrations/logical";
15
+ import { secretOf } from "@intellectual-frontiers/integrations/logical";
16
+
17
+ /** A document to send. */
18
+ export type Outbound = { readonly contentType: string; readonly body: string };
19
+
20
+ /** What a partner gave back: a status and a body, which is a payload. */
21
+ export type Delivered = { readonly status: number; readonly body: string };
22
+
23
+ /** Why nothing was delivered. */
24
+ export type TransportFailure = { readonly kind: "refused" } | { readonly kind: "network" } | { readonly kind: "rejected"; readonly status: number };
25
+
26
+ /** The transport port of exchange. */
27
+ export type ExchangeTransport = { readonly send: (message: Outbound) => Promise<Result<Delivered, TransportFailure>> };
28
+
29
+ /** HTTPS: a POST of the document to the endpoint, authorized by a bearer secret; a status of 400 or more is `rejected`, with the status only. */
30
+ export function httpsTransport(t: Transport, endpoint: string, bearer: Secret): ExchangeTransport {
31
+ return {
32
+ send: async (m) => {
33
+ const x = await t.send({ method: "POST", url: endpoint, headers: { "content-type": m.contentType, authorization: `Bearer ${bearer.reveal()}` }, body: m.body });
34
+ if (x.kind === "err") return err({ kind: x.error.kind });
35
+ return x.value.status >= 400 ? err({ kind: "rejected", status: x.value.status }) : ok({ status: x.value.status, body: x.value.body });
36
+ },
37
+ };
38
+ }
39
+
40
+ /** The claims of the assertion that proves the client to a token endpoint. */
41
+ export type AssertionClaims = { readonly iss: string; readonly sub: string; readonly aud: string; readonly jti: string; readonly exp: number };
42
+
43
+ /** The port that signs an assertion with the client's key: the key never leaves it. */
44
+ export type AssertionSigner = { readonly sign: (claims: AssertionClaims) => Promise<Result<Secret, { readonly kind: "signing-failed" }>> };
45
+
46
+ /** Why a token was not obtained. */
47
+ export type TokenFailure = { readonly kind: "signing-failed" } | { readonly kind: "refused" } | { readonly kind: "network" } | { readonly kind: "rejected"; readonly status: number } | { readonly kind: "malformed" };
48
+
49
+ /** The form of a client credentials request that carries a signed assertion (RFC 7523, as SMART Backend Services uses it). */
50
+ export function backendServicesForm(assertion: Secret, scope: string): string {
51
+ const pairs: readonly (readonly [string, string])[] = [
52
+ ["grant_type", "client_credentials"],
53
+ ["client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"],
54
+ ["client_assertion", assertion.reveal()],
55
+ ["scope", scope],
56
+ ];
57
+ return pairs.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&");
58
+ }
59
+
60
+ /** A bearer secret from the token endpoint: it signs an assertion, posts the form and reads `access_token` of the answer. */
61
+ export async function requestToken(t: Transport, tokenUrl: string, signer: AssertionSigner, claims: AssertionClaims, scope: string): Promise<Result<Secret, TokenFailure>> {
62
+ const signed = await signer.sign(claims);
63
+ if (signed.kind === "err") return err(signed.error);
64
+ const x = await t.send({ method: "POST", url: tokenUrl, headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" }, body: backendServicesForm(signed.value, scope) });
65
+ if (x.kind === "err") return err({ kind: x.error.kind });
66
+ if (x.value.status >= 400) return err({ kind: "rejected", status: x.value.status });
67
+ try {
68
+ const body: unknown = JSON.parse(x.value.body);
69
+ const token = typeof body === "object" && body !== null && "access_token" in body ? body.access_token : undefined;
70
+ return typeof token === "string" && token !== "" ? ok(secretOf(token)) : err({ kind: "malformed" });
71
+ } catch {
72
+ return err({ kind: "malformed" });
73
+ }
74
+ }
75
+
76
+ /** MLLP start block, end block and carriage return. */
77
+ export const MLLP = { start: "\u000b", end: "\u001c", cr: "\r" } as const;
78
+
79
+ /** A message in the framing of MLLP. */
80
+ export const mllpFrame = (message: string): string => `${MLLP.start}${message}${MLLP.end}${MLLP.cr}`;
81
+
82
+ /** The message of a frame, or `undefined` where the text is not one whole frame. */
83
+ export function mllpUnframe(frame: string): string | undefined {
84
+ return frame.startsWith(MLLP.start) && frame.endsWith(`${MLLP.end}${MLLP.cr}`) ? frame.slice(1, -2) : undefined;
85
+ }