@krizaka/orazaka-client 0.1.0 → 0.2.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.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,54 @@
1
+ /** The checks a product may ask for: `POST /api/v1/checks/{purpose}`. Identity checks are not offered to products. */
2
+ declare const CHECK_PURPOSE: {
3
+ readonly courtRecords: "court-records";
4
+ readonly credit: "credit";
5
+ };
6
+ type CheckPurposeKey = (typeof CHECK_PURPOSE)[keyof typeof CHECK_PURPOSE];
7
+ declare const CHECK_OUTCOME: readonly ["MATCH", "NO_MATCH", "PENDING", "PROVIDER_ERROR", "TIMEOUT", "REFUSED"];
8
+ type CheckOutcome = (typeof CHECK_OUTCOME)[number];
9
+ /** Why a check was refused; present exactly when the outcome is `REFUSED`. `NOT_CONFIGURED` means Orazaka has no provider, key or pepper for it: never a result. */
10
+ declare const CHECK_REFUSAL: readonly ["NO_CONSENT", "NO_KEY", "BUDGET_EXHAUSTED", "NOT_CONFIGURED"];
11
+ type CheckRefusal = (typeof CHECK_REFUSAL)[number];
12
+ /** The closed court category of a match; `NONE` for everything else. Never free text, never a record. */
13
+ declare const CHECK_CATEGORY: readonly ["TAL_NON_PAYMENT", "TAL_OTHER", "CRIMINAL", "CIVIL", "NONE"];
14
+ type CheckCategory = (typeof CHECK_CATEGORY)[number];
15
+ interface CheckSubject {
16
+ /** The opaque id of the subject on the product's side: consent and the audit are keyed on it, the names never are. */
17
+ subjectId: string;
18
+ lastName: string;
19
+ firstName: string;
20
+ /** ISO date, optional. */
21
+ birthDate?: string;
22
+ address?: string;
23
+ /** For example `QC`: routes Québec court records to the Québec provider. */
24
+ region?: string;
25
+ }
26
+ interface StartCheckInput {
27
+ subject: CheckSubject;
28
+ /** The product's statement that the subject consented to this purpose. Without it Orazaka answers `REFUSED / NO_CONSENT` and asks nobody. */
29
+ consented: boolean;
30
+ /** The product's run this check belongs to, kept on the audit line. */
31
+ runId?: string;
32
+ }
33
+ interface CollectCheckInput {
34
+ /** The subject the check was for. */
35
+ subjectId: string;
36
+ /** The consent must still stand: it is checked again at every poll. */
37
+ consented: boolean;
38
+ }
39
+ /** The closed answer of a check, as Orazaka's `CheckResult`: an outcome and a category, no record. A refusal is an answer, not an exception. */
40
+ interface CheckResult {
41
+ purpose: "COURT_RECORDS" | "CREDIT" | "IDENTITY";
42
+ outcome: CheckOutcome;
43
+ refusal: CheckRefusal | null;
44
+ category: CheckCategory;
45
+ /** The provider's opaque reference: collect a `PENDING` check with it. */
46
+ providerRef: string | null;
47
+ runId: string | null;
48
+ }
49
+ /** Reads a check's answer from the edge's JSON; anything else is `ORAZAKA_SHAPE`. */
50
+ declare function parseCheck(body: unknown): CheckResult;
51
+
1
52
  interface Clock {
2
53
  now(): Date;
3
54
  }
@@ -99,6 +150,14 @@ interface OrazakaClient {
99
150
  getRun(runId: string): Promise<OrazakaRun>;
100
151
  /** Reads the run until it is over (succeeded, failed or cancelled) and answers it; a failed run is returned, not thrown. */
101
152
  waitForRun(runId: string, options?: WaitOptions): Promise<OrazakaRun>;
153
+ /**
154
+ * Starts an external check (`POST /api/v1/checks/{purpose}`): court records or credit, through Orazaka's one door.
155
+ * Orazaka, not the product, decides consent, key, budget and provider; a refusal (`NO_CONSENT`, `NO_KEY`,
156
+ * `BUDGET_EXHAUSTED`, `NOT_CONFIGURED`) is the answer, with outcome `REFUSED`. Answers `PENDING` with a `providerRef` when the provider replies later.
157
+ */
158
+ startCheck(purpose: CheckPurposeKey, input: StartCheckInput): Promise<CheckResult>;
159
+ /** Collects a `PENDING` check by its provider reference (`GET /api/v1/checks/{providerRef}`); `PENDING` again while the provider works. */
160
+ collectCheck(providerRef: string, input: CollectCheckInput): Promise<CheckResult>;
102
161
  /** The Studios this key has installed — also the cheapest call that proves the key and the connection. */
103
162
  studios(): Promise<string[]>;
104
163
  /** The circuit breaker, for diagnostics. */
@@ -169,4 +228,4 @@ declare class OrazakaError extends Error {
169
228
  get retryAfterSeconds(): number | undefined;
170
229
  }
171
230
 
172
- export { type Circuit, type CircuitOptions, type Clock, ORAZAKA_CODE, type OrazakaClient, type OrazakaClientOptions, type OrazakaCode, OrazakaError, type OrazakaRun, RUN_STATUS, type RunOutput, type StartRunOptions, type StartedRun, type WaitOptions, createCircuit, createOrazakaClient, isTerminal, orazakaRefusal, outputOf, parseInstallations, parseRun };
231
+ export { CHECK_CATEGORY, CHECK_OUTCOME, CHECK_PURPOSE, CHECK_REFUSAL, type CheckCategory, type CheckOutcome, type CheckPurposeKey, type CheckRefusal, type CheckResult, type CheckSubject, type Circuit, type CircuitOptions, type Clock, type CollectCheckInput, ORAZAKA_CODE, type OrazakaClient, type OrazakaClientOptions, type OrazakaCode, OrazakaError, type OrazakaRun, RUN_STATUS, type RunOutput, type StartCheckInput, type StartRunOptions, type StartedRun, type WaitOptions, createCircuit, createOrazakaClient, isTerminal, orazakaRefusal, outputOf, parseCheck, parseInstallations, parseRun };
package/dist/index.js CHANGED
@@ -1,6 +1,3 @@
1
- // src/circuit.ts
2
- import { addSeconds, differenceInSeconds, isBefore } from "date-fns";
3
-
4
1
  // src/errors.ts
5
2
  var ORAZAKA_CODE = {
6
3
  /** No API key was given. */
@@ -62,7 +59,28 @@ var OrazakaError = class extends Error {
62
59
  }
63
60
  };
64
61
 
62
+ // src/checks.ts
63
+ var CHECK_PURPOSE = { courtRecords: "court-records", credit: "credit" };
64
+ var CHECK_OUTCOME = ["MATCH", "NO_MATCH", "PENDING", "PROVIDER_ERROR", "TIMEOUT", "REFUSED"];
65
+ var CHECK_REFUSAL = ["NO_CONSENT", "NO_KEY", "BUDGET_EXHAUSTED", "NOT_CONFIGURED"];
66
+ var CHECK_CATEGORY = ["TAL_NON_PAYMENT", "TAL_OTHER", "CRIMINAL", "CIVIL", "NONE"];
67
+ var PURPOSES = ["COURT_RECORDS", "CREDIT", "IDENTITY"];
68
+ var shape = (what) => new OrazakaError(ORAZAKA_CODE.shape, `Orazaka's answer has an unexpected shape: ${what}`);
69
+ var text = (v) => typeof v === "string" ? v : null;
70
+ var oneOf = (list, v) => list.includes(v) ? v : null;
71
+ function parseCheck(body) {
72
+ const o = body ?? {};
73
+ const purpose = oneOf(PURPOSES, o.purpose);
74
+ const outcome = oneOf(CHECK_OUTCOME, o.outcome);
75
+ const category = oneOf(CHECK_CATEGORY, o.category ?? "NONE");
76
+ if (!purpose || !outcome || !category) throw shape("a check needs a known purpose, outcome and category");
77
+ const refusal = o.refusal === void 0 || o.refusal === null ? null : oneOf(CHECK_REFUSAL, o.refusal);
78
+ if (outcome === "REFUSED" !== (refusal !== null)) throw shape("a refusal comes with REFUSED, and REFUSED with a refusal");
79
+ return { purpose, outcome, refusal, category, providerRef: text(o.providerRef), runId: text(o.runId) };
80
+ }
81
+
65
82
  // src/circuit.ts
83
+ import { addSeconds, differenceInSeconds, isBefore } from "date-fns";
66
84
  function createCircuit(options, clock) {
67
85
  let failures = 0;
68
86
  let openUntil = null;
@@ -112,33 +130,33 @@ var RUN_STATUS = {
112
130
  var TERMINAL = [RUN_STATUS.succeeded, RUN_STATUS.failed, RUN_STATUS.cancelled];
113
131
  var isTerminal = (run) => TERMINAL.includes(run.status);
114
132
  var outputOf = (run, key) => run.outputs.find((o) => o.key === key)?.value ?? null;
115
- var shape = (what) => new OrazakaError(ORAZAKA_CODE.shape, `Orazaka's answer has an unexpected shape: ${what}`);
116
- var text = (v) => typeof v === "string" ? v : null;
133
+ var shape2 = (what) => new OrazakaError(ORAZAKA_CODE.shape, `Orazaka's answer has an unexpected shape: ${what}`);
134
+ var text2 = (v) => typeof v === "string" ? v : null;
117
135
  var parseOutput = (raw) => {
118
136
  const o = raw ?? {};
119
- if (typeof o.key !== "string" || typeof o.type !== "string") throw shape("an output without key and type");
120
- return { key: o.key, label: text(o.label), type: o.type, value: text(o.value) };
137
+ if (typeof o.key !== "string" || typeof o.type !== "string") throw shape2("an output without key and type");
138
+ return { key: o.key, label: text2(o.label), type: o.type, value: text2(o.value) };
121
139
  };
122
140
  function parseRun(body) {
123
141
  const o = body ?? {};
124
- if (typeof o.id !== "string" || typeof o.studioKey !== "string" || typeof o.status !== "string") throw shape("a run needs id, studioKey and status");
125
- if (o.outputs !== void 0 && o.outputs !== null && !Array.isArray(o.outputs)) throw shape("outputs is not a list");
142
+ if (typeof o.id !== "string" || typeof o.studioKey !== "string" || typeof o.status !== "string") throw shape2("a run needs id, studioKey and status");
143
+ if (o.outputs !== void 0 && o.outputs !== null && !Array.isArray(o.outputs)) throw shape2("outputs is not a list");
126
144
  return {
127
145
  id: o.id,
128
146
  studioKey: o.studioKey,
129
- blueprintVersion: text(o.blueprintVersion),
147
+ blueprintVersion: text2(o.blueprintVersion),
130
148
  status: o.status,
131
149
  outputs: (o.outputs ?? []).map(parseOutput),
132
- errorMessage: text(o.errorMessage),
133
- startedAt: text(o.startedAt),
134
- finishedAt: text(o.finishedAt)
150
+ errorMessage: text2(o.errorMessage),
151
+ startedAt: text2(o.startedAt),
152
+ finishedAt: text2(o.finishedAt)
135
153
  };
136
154
  }
137
155
  function parseInstallations(body) {
138
- if (!Array.isArray(body)) throw shape("installations is not a list");
156
+ if (!Array.isArray(body)) throw shape2("installations is not a list");
139
157
  return body.map((i) => {
140
158
  const key = i?.studioKey;
141
- if (typeof key !== "string") throw shape("an installation without studioKey");
159
+ if (typeof key !== "string") throw shape2("an installation without studioKey");
142
160
  return key;
143
161
  });
144
162
  }
@@ -146,6 +164,8 @@ function parseInstallations(body) {
146
164
  // src/client.ts
147
165
  var STUDIO_KEY = /^[a-z0-9][a-z0-9-]{0,79}$/i;
148
166
  var RUN_ID = /^[0-9a-f-]{36}$/i;
167
+ var CHECK_PURPOSES = ["court-records", "credit"];
168
+ var PROVIDER_REF = /^[A-Za-z0-9._:~-]{1,120}$/;
149
169
  var IDEMPOTENCY_KEY = /^[!-~]{1,255}$/;
150
170
  var KEY_REUSED = "idempotency_key_reused";
151
171
  var DEFAULT_TIMEOUT_MS = 2e4;
@@ -231,6 +251,16 @@ function createOrazakaClient(options) {
231
251
  const res = await call(`/api/v1/studios/${studio}/runs`, { method: "POST", body: { inputs }, headers: idempotencyKey ? { "idempotency-key": idempotencyKey } : {} });
232
252
  return { run: parseRun(await json(res)), replayed: res.headers.get("idempotent-replayed") === "true" };
233
253
  },
254
+ async startCheck(purpose, { subject, consented, runId }) {
255
+ if (!CHECK_PURPOSES.includes(purpose)) throw new OrazakaError(ORAZAKA_CODE.input, "Not a check purpose", { status: 422 });
256
+ const res = await call(`/api/v1/checks/${purpose}`, { method: "POST", body: { ...subject, runId, consented } });
257
+ return parseCheck(await json(res));
258
+ },
259
+ async collectCheck(providerRef, { subjectId, consented }) {
260
+ if (!PROVIDER_REF.test(providerRef)) throw new OrazakaError(ORAZAKA_CODE.input, "Not a provider reference", { status: 422 });
261
+ const query = new URLSearchParams({ subjectId, consented: String(consented) });
262
+ return parseCheck(await json(await call(`/api/v1/checks/${providerRef}?${query}`)));
263
+ },
234
264
  async waitForRun(runId, { intervalMs = DEFAULT_WAIT_INTERVAL_MS, timeoutMs: waitMs = DEFAULT_WAIT_TIMEOUT_MS } = {}) {
235
265
  const deadline = addMilliseconds(options.clock.now(), waitMs);
236
266
  for (; ; ) {
@@ -243,6 +273,10 @@ function createOrazakaClient(options) {
243
273
  };
244
274
  }
245
275
  export {
276
+ CHECK_CATEGORY,
277
+ CHECK_OUTCOME,
278
+ CHECK_PURPOSE,
279
+ CHECK_REFUSAL,
246
280
  ORAZAKA_CODE,
247
281
  OrazakaError,
248
282
  RUN_STATUS,
@@ -251,6 +285,7 @@ export {
251
285
  isTerminal,
252
286
  orazakaRefusal,
253
287
  outputOf,
288
+ parseCheck,
254
289
  parseInstallations,
255
290
  parseRun
256
291
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/circuit.ts","../src/errors.ts","../src/client.ts","../src/run.ts"],"sourcesContent":["import { addSeconds, differenceInSeconds, isBefore } from \"date-fns\";\n\nimport { ORAZAKA_CODE, OrazakaError } from \"./errors\";\n\nexport interface Clock {\n now(): Date;\n}\n\nexport interface CircuitOptions {\n /** Consecutive failures (no answer, timeout, 5xx) that open the circuit. */\n failureThreshold: number;\n /** How long it stays open before one call is let through to probe. */\n openSeconds: number;\n}\n\n/**\n * A circuit breaker over a dependency that may be down: after `failureThreshold` failures in a row it refuses at once (no waiting on\n * a timeout, no load on a struggling service) for `openSeconds`, then lets ONE call through; its success closes the circuit, its\n * failure opens it again. A refusal of the edge (401, 402, 404…) is an answer, not a failure: only the caller reports failures.\n */\nexport function createCircuit(options: CircuitOptions, clock: Clock) {\n let failures = 0;\n let openUntil: Date | null = null;\n let probing = false;\n return {\n /** Throws `ORAZAKA_CIRCUIT_OPEN` while the circuit is open (or its probe is in flight). */\n check(): void {\n if (openUntil === null) return;\n const now = clock.now();\n if (isBefore(now, openUntil)) throw open(Math.max(1, differenceInSeconds(openUntil, now)));\n if (probing) throw open(1);\n probing = true;\n },\n success(): void {\n failures = 0;\n openUntil = null;\n probing = false;\n },\n failure(): void {\n failures += 1;\n if (probing || failures >= options.failureThreshold) {\n openUntil = addSeconds(clock.now(), options.openSeconds);\n probing = false;\n }\n },\n /** Test and diagnostics: is it refusing now? */\n get isOpen(): boolean {\n return openUntil !== null;\n },\n };\n}\n\nexport type Circuit = ReturnType<typeof createCircuit>;\n\nconst open = (retryAfterSeconds: number) => new OrazakaError(ORAZAKA_CODE.circuitOpen, \"Orazaka failed several times in a row: not calling it for a moment\", { retryAfterSeconds, status: 502 });\n","/** The stable codes of a refusal or a failure of Orazaka's edge — a product translates them; none is a sentence. */\nexport const ORAZAKA_CODE = {\n /** No API key was given. */\n notConfigured: \"ORAZAKA_NOT_CONFIGURED\",\n /** 401/403: the key is wrong, revoked or lacks the right. */\n key: \"ORAZAKA_KEY\",\n /** 402: the run is not affordable now. */\n credits: \"ORAZAKA_CREDITS\",\n /** 409: the Studio is locked (to buy, or already installed). */\n locked: \"ORAZAKA_LOCKED\",\n /** 400/422: the inputs are not what the Studio asks for. */\n input: \"ORAZAKA_INPUT\",\n /** 404: no such Studio or run (or not the caller's). */\n notFound: \"ORAZAKA_NOT_FOUND\",\n /** 429: too many runs at once; `retryAfterSeconds` says when to come back. Not a failure of the document. */\n busy: \"ORAZAKA_BUSY\",\n /** 422 `idempotency_key_reused`: the key already started a different request. */\n keyReused: \"ORAZAKA_KEY_REUSED\",\n /** 451: a consent is to be agreed to first. */\n consent: \"ORAZAKA_CONSENT\",\n /** The edge did not answer, or answered 5xx. */\n unavailable: \"ORAZAKA_UNAVAILABLE\",\n /** The edge did not answer within the time given. */\n timeout: \"ORAZAKA_TIMEOUT\",\n /** The edge answered something that is not a run (or a list of installations). */\n shape: \"ORAZAKA_SHAPE\",\n /** Too many failures in a row: the client does not call until the pause is over. */\n circuitOpen: \"ORAZAKA_CIRCUIT_OPEN\",\n /** A run id that is not one: refused before any call. */\n badRun: \"ORAZAKA_BAD_RUN\",\n /** `waitForRun` gave up: the run was still going. */\n waitExpired: \"ORAZAKA_WAIT_EXPIRED\",\n} as const;\nexport type OrazakaCode = (typeof ORAZAKA_CODE)[keyof typeof ORAZAKA_CODE];\n\n/** What the edge's status means for a product that answers its own caller: the status to send back and the code. */\nexport function orazakaRefusal(status: number): { status: number; code: OrazakaCode } {\n if (status === 401 || status === 403) return { status: 502, code: ORAZAKA_CODE.key };\n if (status === 402) return { status: 502, code: ORAZAKA_CODE.credits };\n if (status === 409) return { status: 502, code: ORAZAKA_CODE.locked };\n if (status === 400 || status === 422) return { status: 422, code: ORAZAKA_CODE.input };\n if (status === 404) return { status: 502, code: ORAZAKA_CODE.notFound };\n if (status === 429) return { status: 429, code: ORAZAKA_CODE.busy };\n if (status === 451) return { status: 502, code: ORAZAKA_CODE.consent };\n return { status: 502, code: ORAZAKA_CODE.unavailable };\n}\n\nexport class OrazakaError extends Error {\n constructor(\n readonly code: OrazakaCode,\n message: string,\n readonly details: {\n /** What the edge answered, when it answered. */\n upstreamStatus?: number;\n /** The status a product should answer its own caller with. */\n status?: number;\n /** For `ORAZAKA_BUSY` and `ORAZAKA_CIRCUIT_OPEN`: seconds to wait. */\n retryAfterSeconds?: number;\n } = {},\n ) {\n super(message);\n this.name = \"OrazakaError\";\n }\n\n /** The HTTP status a product answers its own caller with (502 for a failure upstream, 429 when busy). */\n get status(): number {\n return this.details.status ?? 502;\n }\n\n get retryAfterSeconds(): number | undefined {\n return this.details.retryAfterSeconds;\n }\n}\n","import { addMilliseconds, isAfter } from \"date-fns\";\n\nimport { type Circuit, type CircuitOptions, type Clock, createCircuit } from \"./circuit\";\nimport { ORAZAKA_CODE, OrazakaError, orazakaRefusal } from \"./errors\";\nimport { isTerminal, type OrazakaRun, parseInstallations, parseRun } from \"./run\";\n\ntype Fetch = typeof fetch;\n\nexport interface OrazakaClientOptions {\n /** `https://api.orazaka.com` — the edge. A parameter: this package reads no environment. */\n baseUrl: string;\n /** The product's service key (`oz_…`). Without one every call throws `ORAZAKA_NOT_CONFIGURED`. */\n apiKey: string | undefined;\n /** Time is injected: the circuit and `waitForRun` read it from here. */\n clock: Clock;\n fetch?: Fetch;\n /** One call's time limit, in milliseconds (default 20 000). */\n timeoutMs?: number;\n /** The breaker: `false` for none; default 5 failures in a row open it for 30 seconds. */\n circuit?: CircuitOptions | false;\n /** Install the Studio on the account before its first run (default true: the edge asks for it). */\n autoInstall?: boolean;\n /** How `waitForRun` waits between two reads (default `setTimeout`); tests give their own. */\n sleep?: (milliseconds: number) => Promise<void>;\n}\n\nexport interface StartRunOptions {\n /** Retrying with the same key (and the same inputs) answers the run already started instead of paying for a second one. */\n idempotencyKey?: string;\n}\n\nexport interface StartedRun {\n run: OrazakaRun;\n /** The edge answered a run it had already started for this key (`Idempotent-Replayed`). */\n replayed: boolean;\n}\n\nexport interface WaitOptions {\n /** Between two reads, in milliseconds (default 2 000). */\n intervalMs?: number;\n /** Give up after this long, in milliseconds (default 120 000): `ORAZAKA_WAIT_EXPIRED`. */\n timeoutMs?: number;\n}\n\nexport interface OrazakaClient {\n /** Starts a Studio run (`POST /api/v1/studios/{studio}/runs`, 202). Pass an idempotency key to make the retry safe. */\n startRun(studio: string, inputs: Record<string, unknown>, options?: StartRunOptions): Promise<StartedRun>;\n /** The run, its status and its outputs (`GET /api/v1/studios/runs/{id}`). */\n getRun(runId: string): Promise<OrazakaRun>;\n /** Reads the run until it is over (succeeded, failed or cancelled) and answers it; a failed run is returned, not thrown. */\n waitForRun(runId: string, options?: WaitOptions): Promise<OrazakaRun>;\n /** The Studios this key has installed — also the cheapest call that proves the key and the connection. */\n studios(): Promise<string[]>;\n /** The circuit breaker, for diagnostics. */\n readonly circuit: Circuit | null;\n}\n\nconst STUDIO_KEY = /^[a-z0-9][a-z0-9-]{0,79}$/i;\nconst RUN_ID = /^[0-9a-f-]{36}$/i;\nconst IDEMPOTENCY_KEY = /^[!-~]{1,255}$/;\n/** The stable code the edge answers (HTTP 422) when an idempotency key already started a different request. */\nconst KEY_REUSED = \"idempotency_key_reused\";\nconst DEFAULT_TIMEOUT_MS = 20_000;\nconst DEFAULT_CIRCUIT: CircuitOptions = { failureThreshold: 5, openSeconds: 30 };\nconst DEFAULT_WAIT_INTERVAL_MS = 2000;\nconst DEFAULT_WAIT_TIMEOUT_MS = 120_000;\nconst BUSY_MIN_SECONDS = 1;\nconst BUSY_MAX_SECONDS = 300;\nconst BUSY_DEFAULT_SECONDS = 15;\n\n/** Never served from a framework's fetch cache: a run's status changes. (`cache` is a runtime option the Node typings do not list.) */\nconst NO_STORE = { cache: \"no-store\" } as RequestInit;\n\nconst sleepFor = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));\n\ninterface Call {\n method?: \"GET\" | \"POST\";\n body?: unknown;\n headers?: Record<string, string>;\n}\n\n/** Orazaka's edge, for every TypeScript product: one client instead of one copy per product. */\nexport function createOrazakaClient(options: OrazakaClientOptions): OrazakaClient {\n const doFetch = options.fetch ?? fetch;\n const base = options.baseUrl.replace(/\\/+$/, \"\");\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const circuit = options.circuit === false ? null : createCircuit(options.circuit ?? DEFAULT_CIRCUIT, options.clock);\n const sleep = options.sleep ?? sleepFor;\n const installed = new Set<string>();\n\n /** The edge answered with a refusal: a stable error. A refusal is an answer, so the circuit stays closed. */\n async function refusal(res: Response, method: string, path: string): Promise<OrazakaError> {\n const where = `${method} ${path.split(\"?\")[0]}`;\n const body = (await res.json().catch(() => null)) as { status?: unknown; code?: unknown; retryAfterSeconds?: unknown } | null;\n if (res.status === 429) {\n const asked = Number(res.headers.get(\"retry-after\") ?? body?.retryAfterSeconds);\n const wait = Math.min(BUSY_MAX_SECONDS, Math.max(BUSY_MIN_SECONDS, asked || BUSY_DEFAULT_SECONDS));\n return new OrazakaError(ORAZAKA_CODE.busy, `Orazaka is busy on ${where}`, { upstreamStatus: 429, status: 429, retryAfterSeconds: wait });\n }\n if (res.status === 422 && (body?.status === KEY_REUSED || body?.code === KEY_REUSED)) {\n return new OrazakaError(ORAZAKA_CODE.keyReused, `The idempotency key already started a different request on ${where}`, { upstreamStatus: 422, status: 409 });\n }\n const { status, code } = orazakaRefusal(res.status);\n return new OrazakaError(code, `Orazaka answered ${res.status} on ${where}`, { upstreamStatus: res.status, status });\n }\n\n async function call(path: string, init: Call = {}): Promise<Response> {\n if (!options.apiKey) throw new OrazakaError(ORAZAKA_CODE.notConfigured, \"The Orazaka API key is not set\", { status: 503 });\n circuit?.check();\n const method = init.method ?? \"GET\";\n let res: Response;\n try {\n res = await doFetch(`${base}${path}`, {\n method,\n headers: { authorization: `Bearer ${options.apiKey}`, accept: \"application/json\", ...(init.body === undefined ? {} : { \"content-type\": \"application/json\" }), ...init.headers },\n body: init.body === undefined ? undefined : JSON.stringify(init.body),\n signal: AbortSignal.timeout(timeoutMs),\n ...NO_STORE,\n });\n } catch (cause) {\n circuit?.failure();\n const timedOut = cause instanceof Error && (cause.name === \"TimeoutError\" || cause.name === \"AbortError\");\n throw new OrazakaError(timedOut ? ORAZAKA_CODE.timeout : ORAZAKA_CODE.unavailable, timedOut ? \"Orazaka did not answer in time\" : \"Orazaka did not answer\", { status: 502 });\n }\n if (res.status >= 500) {\n circuit?.failure();\n throw new OrazakaError(ORAZAKA_CODE.unavailable, `Orazaka answered ${res.status} on ${method} ${path.split(\"?\")[0]}`, { upstreamStatus: res.status, status: 502 });\n }\n circuit?.success();\n if (!res.ok) throw await refusal(res, method, path);\n return res;\n }\n\n const json = (res: Response): Promise<unknown> => res.json().catch(() => undefined);\n\n async function studios(): Promise<string[]> {\n return parseInstallations(await json(await call(\"/api/v1/studios/installations\")));\n }\n\n async function ensureInstalled(studio: string): Promise<void> {\n if (installed.has(studio)) return;\n if (!(await studios()).includes(studio)) await call(`/api/v1/studios/${studio}/installations?locale=en`, { method: \"POST\", body: { config: {} } });\n installed.add(studio);\n }\n\n const checkRunId = (runId: string) => {\n if (!RUN_ID.test(runId)) throw new OrazakaError(ORAZAKA_CODE.badRun, \"Not a run id\", { status: 400 });\n };\n\n async function getRun(runId: string): Promise<OrazakaRun> {\n checkRunId(runId);\n return parseRun(await json(await call(`/api/v1/studios/runs/${runId}`)));\n }\n\n return {\n circuit,\n studios,\n getRun,\n async startRun(studio, inputs, { idempotencyKey } = {}) {\n if (!STUDIO_KEY.test(studio)) throw new OrazakaError(ORAZAKA_CODE.input, \"Not a Studio key\", { status: 422 });\n if (idempotencyKey !== undefined && !IDEMPOTENCY_KEY.test(idempotencyKey)) throw new OrazakaError(ORAZAKA_CODE.input, \"An idempotency key is 1 to 255 printable characters\", { status: 422 });\n if (options.autoInstall !== false) await ensureInstalled(studio);\n const res = await call(`/api/v1/studios/${studio}/runs`, { method: \"POST\", body: { inputs }, headers: idempotencyKey ? { \"idempotency-key\": idempotencyKey } : {} });\n return { run: parseRun(await json(res)), replayed: res.headers.get(\"idempotent-replayed\") === \"true\" };\n },\n async waitForRun(runId, { intervalMs = DEFAULT_WAIT_INTERVAL_MS, timeoutMs: waitMs = DEFAULT_WAIT_TIMEOUT_MS } = {}) {\n const deadline = addMilliseconds(options.clock.now(), waitMs);\n for (;;) {\n const run = await getRun(runId);\n if (isTerminal(run)) return run;\n if (isAfter(options.clock.now(), deadline)) throw new OrazakaError(ORAZAKA_CODE.waitExpired, `The run is still ${run.status} after ${waitMs} ms`, { status: 504 });\n await sleep(intervalMs);\n }\n },\n };\n}\n","import { ORAZAKA_CODE, OrazakaError } from \"./errors\";\n\n/** One output of a run (orazaka-studio `RunArtefactResponse`): `type` is a rendering hint (`TEXT`, `IMAGE`, `VIDEO`…). */\nexport interface RunOutput {\n key: string;\n label: string | null;\n type: string;\n value: string | null;\n}\n\n/** Where a run sits (orazaka-studio `RunStatus`). The client keeps the string the edge sent, so a new status is not a failure. */\nexport const RUN_STATUS = {\n pendingApproval: \"PENDING_APPROVAL\",\n running: \"RUNNING\",\n awaitingInput: \"AWAITING_INPUT\",\n succeeded: \"SUCCEEDED\",\n failed: \"FAILED\",\n cancelled: \"CANCELLED\",\n compensating: \"COMPENSATING\",\n} as const;\n\nconst TERMINAL: readonly string[] = [RUN_STATUS.succeeded, RUN_STATUS.failed, RUN_STATUS.cancelled];\n\n/** A run, as the edge answers it (`GET /api/v1/studios/runs/{id}`). Only what a product reads. */\nexport interface OrazakaRun {\n id: string;\n studioKey: string;\n blueprintVersion: string | null;\n status: string;\n outputs: RunOutput[];\n errorMessage: string | null;\n startedAt: string | null;\n finishedAt: string | null;\n}\n\n/** The run is over, green or not: nothing more will change. */\nexport const isTerminal = (run: Pick<OrazakaRun, \"status\">): boolean => TERMINAL.includes(run.status);\n\n/** The value of one output, or null when the run did not produce it (yet). */\nexport const outputOf = (run: Pick<OrazakaRun, \"outputs\">, key: string): string | null => run.outputs.find((o) => o.key === key)?.value ?? null;\n\nconst shape = (what: string) => new OrazakaError(ORAZAKA_CODE.shape, `Orazaka's answer has an unexpected shape: ${what}`);\nconst text = (v: unknown): string | null => (typeof v === \"string\" ? v : null);\n\nconst parseOutput = (raw: unknown): RunOutput => {\n const o = (raw ?? {}) as Record<string, unknown>;\n if (typeof o.key !== \"string\" || typeof o.type !== \"string\") throw shape(\"an output without key and type\");\n return { key: o.key, label: text(o.label), type: o.type, value: text(o.value) };\n};\n\n/** Reads a run from the edge's JSON; anything else is `ORAZAKA_SHAPE`. */\nexport function parseRun(body: unknown): OrazakaRun {\n const o = (body ?? {}) as Record<string, unknown>;\n if (typeof o.id !== \"string\" || typeof o.studioKey !== \"string\" || typeof o.status !== \"string\") throw shape(\"a run needs id, studioKey and status\");\n if (o.outputs !== undefined && o.outputs !== null && !Array.isArray(o.outputs)) throw shape(\"outputs is not a list\");\n return {\n id: o.id,\n studioKey: o.studioKey,\n blueprintVersion: text(o.blueprintVersion),\n status: o.status,\n outputs: ((o.outputs as unknown[] | null | undefined) ?? []).map(parseOutput),\n errorMessage: text(o.errorMessage),\n startedAt: text(o.startedAt),\n finishedAt: text(o.finishedAt),\n };\n}\n\n/** The Studios an account installed: `GET /api/v1/studios/installations`. */\nexport function parseInstallations(body: unknown): string[] {\n if (!Array.isArray(body)) throw shape(\"installations is not a list\");\n return body.map((i) => {\n const key = (i as Record<string, unknown> | null)?.studioKey;\n if (typeof key !== \"string\") throw shape(\"an installation without studioKey\");\n return key;\n });\n}\n"],"mappings":";AAAA,SAAS,YAAY,qBAAqB,gBAAgB;;;ACCnD,IAAM,eAAe;AAAA;AAAA,EAE1B,eAAe;AAAA;AAAA,EAEf,KAAK;AAAA;AAAA,EAEL,SAAS;AAAA;AAAA,EAET,QAAQ;AAAA;AAAA,EAER,OAAO;AAAA;AAAA,EAEP,UAAU;AAAA;AAAA,EAEV,MAAM;AAAA;AAAA,EAEN,WAAW;AAAA;AAAA,EAEX,SAAS;AAAA;AAAA,EAET,aAAa;AAAA;AAAA,EAEb,SAAS;AAAA;AAAA,EAET,OAAO;AAAA;AAAA,EAEP,aAAa;AAAA;AAAA,EAEb,QAAQ;AAAA;AAAA,EAER,aAAa;AACf;AAIO,SAAS,eAAe,QAAuD;AACpF,MAAI,WAAW,OAAO,W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AC9B,YAAI,WAAW,GAAG,EAAG,QAAO;AAC5B,YAAI,QAAQ,QAAQ,MAAM,IAAI,GAAG,QAAQ,EAAG,OAAM,IAAI,aAAa,aAAa,aAAa,oBAAoB,IAAI,MAAM,UAAU,MAAM,OAAO,EAAE,QAAQ,IAAI,CAAC;AACjK,cAAM,MAAM,UAAU;AAAA,MACxB;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/checks.ts","../src/circuit.ts","../src/client.ts","../src/run.ts"],"sourcesContent":["/** The stable codes of a refusal or a failure of Orazaka's edge — a product translates them; none is a sentence. */\nexport const ORAZAKA_CODE = {\n /** No API key was given. */\n notConfigured: \"ORAZAKA_NOT_CONFIGURED\",\n /** 401/403: the key is wrong, revoked or lacks the right. */\n key: \"ORAZAKA_KEY\",\n /** 402: the run is not affordable now. */\n credits: \"ORAZAKA_CREDITS\",\n /** 409: the Studio is locked (to buy, or already installed). */\n locked: \"ORAZAKA_LOCKED\",\n /** 400/422: the inputs are not what the Studio asks for. */\n input: \"ORAZAKA_INPUT\",\n /** 404: no such Studio or run (or not the caller's). */\n notFound: \"ORAZAKA_NOT_FOUND\",\n /** 429: too many runs at once; `retryAfterSeconds` says when to come back. Not a failure of the document. */\n busy: \"ORAZAKA_BUSY\",\n /** 422 `idempotency_key_reused`: the key already started a different request. */\n keyReused: \"ORAZAKA_KEY_REUSED\",\n /** 451: a consent is to be agreed to first. */\n consent: \"ORAZAKA_CONSENT\",\n /** The edge did not answer, or answered 5xx. */\n unavailable: \"ORAZAKA_UNAVAILABLE\",\n /** The edge did not answer within the time given. */\n timeout: \"ORAZAKA_TIMEOUT\",\n /** The edge answered something that is not a run (or a list of installations). */\n shape: \"ORAZAKA_SHAPE\",\n /** Too many failures in a row: the client does not call until the pause is over. */\n circuitOpen: \"ORAZAKA_CIRCUIT_OPEN\",\n /** A run id that is not one: refused before any call. */\n badRun: \"ORAZAKA_BAD_RUN\",\n /** `waitForRun` gave up: the run was still going. */\n waitExpired: \"ORAZAKA_WAIT_EXPIRED\",\n} as const;\nexport type OrazakaCode = (typeof ORAZAKA_CODE)[keyof typeof ORAZAKA_CODE];\n\n/** What the edge's status means for a product that answers its own caller: the status to send back and the code. */\nexport function orazakaRefusal(status: number): { status: number; code: OrazakaCode } {\n if (status === 401 || status === 403) return { status: 502, code: ORAZAKA_CODE.key };\n if (status === 402) return { status: 502, code: ORAZAKA_CODE.credits };\n if (status === 409) return { status: 502, code: ORAZAKA_CODE.locked };\n if (status === 400 || status === 422) return { status: 422, code: ORAZAKA_CODE.input };\n if (status === 404) return { status: 502, code: ORAZAKA_CODE.notFound };\n if (status === 429) return { status: 429, code: ORAZAKA_CODE.busy };\n if (status === 451) return { status: 502, code: ORAZAKA_CODE.consent };\n return { status: 502, code: ORAZAKA_CODE.unavailable };\n}\n\nexport class OrazakaError extends Error {\n constructor(\n readonly code: OrazakaCode,\n message: string,\n readonly details: {\n /** What the edge answered, when it answered. */\n upstreamStatus?: number;\n /** The status a product should answer its own caller with. */\n status?: number;\n /** For `ORAZAKA_BUSY` and `ORAZAKA_CIRCUIT_OPEN`: seconds to wait. */\n retryAfterSeconds?: number;\n } = {},\n ) {\n super(message);\n this.name = \"OrazakaError\";\n }\n\n /** The HTTP status a product answers its own caller with (502 for a failure upstream, 429 when busy). */\n get status(): number {\n return this.details.status ?? 502;\n }\n\n get retryAfterSeconds(): number | undefined {\n return this.details.retryAfterSeconds;\n }\n}\n","import { ORAZAKA_CODE, OrazakaError } from \"./errors\";\n\n/** The checks a product may ask for: `POST /api/v1/checks/{purpose}`. Identity checks are not offered to products. */\nexport const CHECK_PURPOSE = { courtRecords: \"court-records\", credit: \"credit\" } as const;\nexport type CheckPurposeKey = (typeof CHECK_PURPOSE)[keyof typeof CHECK_PURPOSE];\n\nexport const CHECK_OUTCOME = [\"MATCH\", \"NO_MATCH\", \"PENDING\", \"PROVIDER_ERROR\", \"TIMEOUT\", \"REFUSED\"] as const;\nexport type CheckOutcome = (typeof CHECK_OUTCOME)[number];\n\n/** Why a check was refused; present exactly when the outcome is `REFUSED`. `NOT_CONFIGURED` means Orazaka has no provider, key or pepper for it: never a result. */\nexport const CHECK_REFUSAL = [\"NO_CONSENT\", \"NO_KEY\", \"BUDGET_EXHAUSTED\", \"NOT_CONFIGURED\"] as const;\nexport type CheckRefusal = (typeof CHECK_REFUSAL)[number];\n\n/** The closed court category of a match; `NONE` for everything else. Never free text, never a record. */\nexport const CHECK_CATEGORY = [\"TAL_NON_PAYMENT\", \"TAL_OTHER\", \"CRIMINAL\", \"CIVIL\", \"NONE\"] as const;\nexport type CheckCategory = (typeof CHECK_CATEGORY)[number];\n\nexport interface CheckSubject {\n /** The opaque id of the subject on the product's side: consent and the audit are keyed on it, the names never are. */\n subjectId: string;\n lastName: string;\n firstName: string;\n /** ISO date, optional. */\n birthDate?: string;\n address?: string;\n /** For example `QC`: routes Québec court records to the Québec provider. */\n region?: string;\n}\n\nexport interface StartCheckInput {\n subject: CheckSubject;\n /** The product's statement that the subject consented to this purpose. Without it Orazaka answers `REFUSED / NO_CONSENT` and asks nobody. */\n consented: boolean;\n /** The product's run this check belongs to, kept on the audit line. */\n runId?: string;\n}\n\nexport interface CollectCheckInput {\n /** The subject the check was for. */\n subjectId: string;\n /** The consent must still stand: it is checked again at every poll. */\n consented: boolean;\n}\n\n/** The closed answer of a check, as Orazaka's `CheckResult`: an outcome and a category, no record. A refusal is an answer, not an exception. */\nexport interface CheckResult {\n purpose: \"COURT_RECORDS\" | \"CREDIT\" | \"IDENTITY\";\n outcome: CheckOutcome;\n refusal: CheckRefusal | null;\n category: CheckCategory;\n /** The provider's opaque reference: collect a `PENDING` check with it. */\n providerRef: string | null;\n runId: string | null;\n}\n\nconst PURPOSES = [\"COURT_RECORDS\", \"CREDIT\", \"IDENTITY\"] as const;\nconst shape = (what: string) => new OrazakaError(ORAZAKA_CODE.shape, `Orazaka's answer has an unexpected shape: ${what}`);\nconst text = (v: unknown): string | null => (typeof v === \"string\" ? v : null);\nconst oneOf = <T extends string>(list: readonly T[], v: unknown): T | null => (list as readonly unknown[]).includes(v) ? (v as T) : null;\n\n/** Reads a check's answer from the edge's JSON; anything else is `ORAZAKA_SHAPE`. */\nexport function parseCheck(body: unknown): CheckResult {\n const o = (body ?? {}) as Record<string, unknown>;\n const purpose = oneOf(PURPOSES, o.purpose);\n const outcome = oneOf(CHECK_OUTCOME, o.outcome);\n const category = oneOf(CHECK_CATEGORY, o.category ?? \"NONE\");\n if (!purpose || !outcome || !category) throw shape(\"a check needs a known purpose, outcome and category\");\n const refusal = o.refusal === undefined || o.refusal === null ? null : oneOf(CHECK_REFUSAL, o.refusal);\n if ((outcome === \"REFUSED\") !== (refusal !== null)) throw shape(\"a refusal comes with REFUSED, and REFUSED with a refusal\");\n return { purpose, outcome, refusal, category, providerRef: text(o.providerRef), runId: text(o.runId) };\n}\n","import { addSeconds, differenceInSeconds, isBefore } from \"date-fns\";\n\nimport { ORAZAKA_CODE, OrazakaError } from \"./errors\";\n\nexport interface Clock {\n now(): Date;\n}\n\nexport interface CircuitOptions {\n /** Consecutive failures (no answer, timeout, 5xx) that open the circuit. */\n failureThreshold: number;\n /** How long it stays open before one call is let through to probe. */\n openSeconds: number;\n}\n\n/**\n * A circuit breaker over a dependency that may be down: after `failureThreshold` failures in a row it refuses at once (no waiting on\n * a timeout, no load on a struggling service) for `openSeconds`, then lets ONE call through; its success closes the circuit, its\n * failure opens it again. A refusal of the edge (401, 402, 404…) is an answer, not a failure: only the caller reports failures.\n */\nexport function createCircuit(options: CircuitOptions, clock: Clock) {\n let failures = 0;\n let openUntil: Date | null = null;\n let probing = false;\n return {\n /** Throws `ORAZAKA_CIRCUIT_OPEN` while the circuit is open (or its probe is in flight). */\n check(): void {\n if (openUntil === null) return;\n const now = clock.now();\n if (isBefore(now, openUntil)) throw open(Math.max(1, differenceInSeconds(openUntil, now)));\n if (probing) throw open(1);\n probing = true;\n },\n success(): void {\n failures = 0;\n openUntil = null;\n probing = false;\n },\n failure(): void {\n failures += 1;\n if (probing || failures >= options.failureThreshold) {\n openUntil = addSeconds(clock.now(), options.openSeconds);\n probing = false;\n }\n },\n /** Test and diagnostics: is it refusing now? */\n get isOpen(): boolean {\n return openUntil !== null;\n },\n };\n}\n\nexport type Circuit = ReturnType<typeof createCircuit>;\n\nconst open = (retryAfterSeconds: number) => new OrazakaError(ORAZAKA_CODE.circuitOpen, \"Orazaka failed several times in a row: not calling it for a moment\", { retryAfterSeconds, status: 502 });\n","import { addMilliseconds, isAfter } from \"date-fns\";\n\nimport { type CheckPurposeKey, type CheckResult, type CollectCheckInput, parseCheck, type StartCheckInput } from \"./checks\";\nimport { type Circuit, type CircuitOptions, type Clock, createCircuit } from \"./circuit\";\nimport { ORAZAKA_CODE, OrazakaError, orazakaRefusal } from \"./errors\";\nimport { isTerminal, type OrazakaRun, parseInstallations, parseRun } from \"./run\";\n\ntype Fetch = typeof fetch;\n\nexport interface OrazakaClientOptions {\n /** `https://api.orazaka.com` — the edge. A parameter: this package reads no environment. */\n baseUrl: string;\n /** The product's service key (`oz_…`). Without one every call throws `ORAZAKA_NOT_CONFIGURED`. */\n apiKey: string | undefined;\n /** Time is injected: the circuit and `waitForRun` read it from here. */\n clock: Clock;\n fetch?: Fetch;\n /** One call's time limit, in milliseconds (default 20 000). */\n timeoutMs?: number;\n /** The breaker: `false` for none; default 5 failures in a row open it for 30 seconds. */\n circuit?: CircuitOptions | false;\n /** Install the Studio on the account before its first run (default true: the edge asks for it). */\n autoInstall?: boolean;\n /** How `waitForRun` waits between two reads (default `setTimeout`); tests give their own. */\n sleep?: (milliseconds: number) => Promise<void>;\n}\n\nexport interface StartRunOptions {\n /** Retrying with the same key (and the same inputs) answers the run already started instead of paying for a second one. */\n idempotencyKey?: string;\n}\n\nexport interface StartedRun {\n run: OrazakaRun;\n /** The edge answered a run it had already started for this key (`Idempotent-Replayed`). */\n replayed: boolean;\n}\n\nexport interface WaitOptions {\n /** Between two reads, in milliseconds (default 2 000). */\n intervalMs?: number;\n /** Give up after this long, in milliseconds (default 120 000): `ORAZAKA_WAIT_EXPIRED`. */\n timeoutMs?: number;\n}\n\nexport interface OrazakaClient {\n /** Starts a Studio run (`POST /api/v1/studios/{studio}/runs`, 202). Pass an idempotency key to make the retry safe. */\n startRun(studio: string, inputs: Record<string, unknown>, options?: StartRunOptions): Promise<StartedRun>;\n /** The run, its status and its outputs (`GET /api/v1/studios/runs/{id}`). */\n getRun(runId: string): Promise<OrazakaRun>;\n /** Reads the run until it is over (succeeded, failed or cancelled) and answers it; a failed run is returned, not thrown. */\n waitForRun(runId: string, options?: WaitOptions): Promise<OrazakaRun>;\n /**\n * Starts an external check (`POST /api/v1/checks/{purpose}`): court records or credit, through Orazaka's one door.\n * Orazaka, not the product, decides consent, key, budget and provider; a refusal (`NO_CONSENT`, `NO_KEY`,\n * `BUDGET_EXHAUSTED`, `NOT_CONFIGURED`) is the answer, with outcome `REFUSED`. Answers `PENDING` with a `providerRef` when the provider replies later.\n */\n startCheck(purpose: CheckPurposeKey, input: StartCheckInput): Promise<CheckResult>;\n /** Collects a `PENDING` check by its provider reference (`GET /api/v1/checks/{providerRef}`); `PENDING` again while the provider works. */\n collectCheck(providerRef: string, input: CollectCheckInput): Promise<CheckResult>;\n /** The Studios this key has installed — also the cheapest call that proves the key and the connection. */\n studios(): Promise<string[]>;\n /** The circuit breaker, for diagnostics. */\n readonly circuit: Circuit | null;\n}\n\nconst STUDIO_KEY = /^[a-z0-9][a-z0-9-]{0,79}$/i;\nconst RUN_ID = /^[0-9a-f-]{36}$/i;\nconst CHECK_PURPOSES: readonly string[] = [\"court-records\", \"credit\"];\n/** A provider's opaque reference: printable, no slash, so it cannot change the path. */\nconst PROVIDER_REF = /^[A-Za-z0-9._:~-]{1,120}$/;\nconst IDEMPOTENCY_KEY = /^[!-~]{1,255}$/;\n/** The stable code the edge answers (HTTP 422) when an idempotency key already started a different request. */\nconst KEY_REUSED = \"idempotency_key_reused\";\nconst DEFAULT_TIMEOUT_MS = 20_000;\nconst DEFAULT_CIRCUIT: CircuitOptions = { failureThreshold: 5, openSeconds: 30 };\nconst DEFAULT_WAIT_INTERVAL_MS = 2000;\nconst DEFAULT_WAIT_TIMEOUT_MS = 120_000;\nconst BUSY_MIN_SECONDS = 1;\nconst BUSY_MAX_SECONDS = 300;\nconst BUSY_DEFAULT_SECONDS = 15;\n\n/** Never served from a framework's fetch cache: a run's status changes. (`cache` is a runtime option the Node typings do not list.) */\nconst NO_STORE = { cache: \"no-store\" } as RequestInit;\n\nconst sleepFor = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));\n\ninterface Call {\n method?: \"GET\" | \"POST\";\n body?: unknown;\n headers?: Record<string, string>;\n}\n\n/** Orazaka's edge, for every TypeScript product: one client instead of one copy per product. */\nexport function createOrazakaClient(options: OrazakaClientOptions): OrazakaClient {\n const doFetch = options.fetch ?? fetch;\n const base = options.baseUrl.replace(/\\/+$/, \"\");\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const circuit = options.circuit === false ? null : createCircuit(options.circuit ?? DEFAULT_CIRCUIT, options.clock);\n const sleep = options.sleep ?? sleepFor;\n const installed = new Set<string>();\n\n /** The edge answered with a refusal: a stable error. A refusal is an answer, so the circuit stays closed. */\n async function refusal(res: Response, method: string, path: string): Promise<OrazakaError> {\n const where = `${method} ${path.split(\"?\")[0]}`;\n const body = (await res.json().catch(() => null)) as { status?: unknown; code?: unknown; retryAfterSeconds?: unknown } | null;\n if (res.status === 429) {\n const asked = Number(res.headers.get(\"retry-after\") ?? body?.retryAfterSeconds);\n const wait = Math.min(BUSY_MAX_SECONDS, Math.max(BUSY_MIN_SECONDS, asked || BUSY_DEFAULT_SECONDS));\n return new OrazakaError(ORAZAKA_CODE.busy, `Orazaka is busy on ${where}`, { upstreamStatus: 429, status: 429, retryAfterSeconds: wait });\n }\n if (res.status === 422 && (body?.status === KEY_REUSED || body?.code === KEY_REUSED)) {\n return new OrazakaError(ORAZAKA_CODE.keyReused, `The idempotency key already started a different request on ${where}`, { upstreamStatus: 422, status: 409 });\n }\n const { status, code } = orazakaRefusal(res.status);\n return new OrazakaError(code, `Orazaka answered ${res.status} on ${where}`, { upstreamStatus: res.status, status });\n }\n\n async function call(path: string, init: Call = {}): Promise<Response> {\n if (!options.apiKey) throw new OrazakaError(ORAZAKA_CODE.notConfigured, \"The Orazaka API key is not set\", { status: 503 });\n circuit?.check();\n const method = init.method ?? \"GET\";\n let res: Response;\n try {\n res = await doFetch(`${base}${path}`, {\n method,\n headers: { authorization: `Bearer ${options.apiKey}`, accept: \"application/json\", ...(init.body === undefined ? {} : { \"content-type\": \"application/json\" }), ...init.headers },\n body: init.body === undefined ? undefined : JSON.stringify(init.body),\n signal: AbortSignal.timeout(timeoutMs),\n ...NO_STORE,\n });\n } catch (cause) {\n circuit?.failure();\n const timedOut = cause instanceof Error && (cause.name === \"TimeoutError\" || cause.name === \"AbortError\");\n throw new OrazakaError(timedOut ? ORAZAKA_CODE.timeout : ORAZAKA_CODE.unavailable, timedOut ? \"Orazaka did not answer in time\" : \"Orazaka did not answer\", { status: 502 });\n }\n if (res.status >= 500) {\n circuit?.failure();\n throw new OrazakaError(ORAZAKA_CODE.unavailable, `Orazaka answered ${res.status} on ${method} ${path.split(\"?\")[0]}`, { upstreamStatus: res.status, status: 502 });\n }\n circuit?.success();\n if (!res.ok) throw await refusal(res, method, path);\n return res;\n }\n\n const json = (res: Response): Promise<unknown> => res.json().catch(() => undefined);\n\n async function studios(): Promise<string[]> {\n return parseInstallations(await json(await call(\"/api/v1/studios/installations\")));\n }\n\n async function ensureInstalled(studio: string): Promise<void> {\n if (installed.has(studio)) return;\n if (!(await studios()).includes(studio)) await call(`/api/v1/studios/${studio}/installations?locale=en`, { method: \"POST\", body: { config: {} } });\n installed.add(studio);\n }\n\n const checkRunId = (runId: string) => {\n if (!RUN_ID.test(runId)) throw new OrazakaError(ORAZAKA_CODE.badRun, \"Not a run id\", { status: 400 });\n };\n\n async function getRun(runId: string): Promise<OrazakaRun> {\n checkRunId(runId);\n return parseRun(await json(await call(`/api/v1/studios/runs/${runId}`)));\n }\n\n return {\n circuit,\n studios,\n getRun,\n async startRun(studio, inputs, { idempotencyKey } = {}) {\n if (!STUDIO_KEY.test(studio)) throw new OrazakaError(ORAZAKA_CODE.input, \"Not a Studio key\", { status: 422 });\n if (idempotencyKey !== undefined && !IDEMPOTENCY_KEY.test(idempotencyKey)) throw new OrazakaError(ORAZAKA_CODE.input, \"An idempotency key is 1 to 255 printable characters\", { status: 422 });\n if (options.autoInstall !== false) await ensureInstalled(studio);\n const res = await call(`/api/v1/studios/${studio}/runs`, { method: \"POST\", body: { inputs }, headers: idempotencyKey ? { \"idempotency-key\": idempotencyKey } : {} });\n return { run: parseRun(await json(res)), replayed: res.headers.get(\"idempotent-replayed\") === \"true\" };\n },\n async startCheck(purpose, { subject, consented, runId }) {\n if (!CHECK_PURPOSES.includes(purpose)) throw new OrazakaError(ORAZAKA_CODE.input, \"Not a check purpose\", { status: 422 });\n const res = await call(`/api/v1/checks/${purpose}`, { method: \"POST\", body: { ...subject, runId, consented } });\n return parseCheck(await json(res));\n },\n async collectCheck(providerRef, { subjectId, consented }) {\n if (!PROVIDER_REF.test(providerRef)) throw new OrazakaError(ORAZAKA_CODE.input, \"Not a provider reference\", { status: 422 });\n const query = new URLSearchParams({ subjectId, consented: String(consented) });\n return parseCheck(await json(await call(`/api/v1/checks/${providerRef}?${query}`)));\n },\n async waitForRun(runId, { intervalMs = DEFAULT_WAIT_INTERVAL_MS, timeoutMs: waitMs = DEFAULT_WAIT_TIMEOUT_MS } = {}) {\n const deadline = addMilliseconds(options.clock.now(), waitMs);\n for (;;) {\n const run = await getRun(runId);\n if (isTerminal(run)) return run;\n if (isAfter(options.clock.now(), deadline)) throw new OrazakaError(ORAZAKA_CODE.waitExpired, `The run is still ${run.status} after ${waitMs} ms`, { status: 504 });\n await sleep(intervalMs);\n }\n },\n };\n}\n","import { ORAZAKA_CODE, OrazakaError } from \"./errors\";\n\n/** One output of a run (orazaka-studio `RunArtefactResponse`): `type` is a rendering hint (`TEXT`, `IMAGE`, `VIDEO`…). */\nexport interface RunOutput {\n key: string;\n label: string | null;\n type: string;\n value: string | null;\n}\n\n/** Where a run sits (orazaka-studio `RunStatus`). The client keeps the string the edge sent, so a new status is not a failure. */\nexport const RUN_STATUS = {\n pendingApproval: \"PENDING_APPROVAL\",\n running: \"RUNNING\",\n awaitingInput: \"AWAITING_INPUT\",\n succeeded: \"SUCCEEDED\",\n failed: \"FAILED\",\n cancelled: \"CANCELLED\",\n compensating: \"COMPENSATING\",\n} as const;\n\nconst TERMINAL: readonly string[] = [RUN_STATUS.succeeded, RUN_STATUS.failed, RUN_STATUS.cancelled];\n\n/** A run, as the edge answers it (`GET /api/v1/studios/runs/{id}`). Only what a product reads. */\nexport interface OrazakaRun {\n id: string;\n studioKey: string;\n blueprintVersion: string | null;\n status: string;\n outputs: RunOutput[];\n errorMessage: string | null;\n startedAt: string | null;\n finishedAt: string | null;\n}\n\n/** The run is over, green or not: nothing more will change. */\nexport const isTerminal = (run: Pick<OrazakaRun, \"status\">): boolean => TERMINAL.includes(run.status);\n\n/** The value of one output, or null when the run did not produce it (yet). */\nexport const outputOf = (run: Pick<OrazakaRun, \"outputs\">, key: string): string | null => run.outputs.find((o) => o.key === key)?.value ?? null;\n\nconst shape = (what: string) => new OrazakaError(ORAZAKA_CODE.shape, `Orazaka's answer has an unexpected shape: ${what}`);\nconst text = (v: unknown): string | null => (typeof v === \"string\" ? v : null);\n\nconst parseOutput = (raw: unknown): RunOutput => {\n const o = (raw ?? {}) as Record<string, unknown>;\n if (typeof o.key !== \"string\" || typeof o.type !== \"string\") throw shape(\"an output without key and type\");\n return { key: o.key, label: text(o.label), type: o.type, value: text(o.value) };\n};\n\n/** Reads a run from the edge's JSON; anything else is `ORAZAKA_SHAPE`. */\nexport function parseRun(body: unknown): OrazakaRun {\n const o = (body ?? {}) as Record<string, unknown>;\n if (typeof o.id !== \"string\" || typeof o.studioKey !== \"string\" || typeof o.status !== \"string\") throw shape(\"a run needs id, studioKey and status\");\n if (o.outputs !== undefined && o.outputs !== null && !Array.isArray(o.outputs)) throw shape(\"outputs is not a list\");\n return {\n id: o.id,\n studioKey: o.studioKey,\n blueprintVersion: text(o.blueprintVersion),\n status: o.status,\n outputs: ((o.outputs as unknown[] | null | undefined) ?? []).map(parseOutput),\n errorMessage: text(o.errorMessage),\n startedAt: text(o.startedAt),\n finishedAt: text(o.finishedAt),\n };\n}\n\n/** The Studios an account installed: `GET /api/v1/studios/installations`. */\nexport function parseInstallations(body: unknown): string[] {\n if (!Array.isArray(body)) throw shape(\"installations is not a list\");\n return body.map((i) => {\n const key = (i as Record<string, unknown> | null)?.studioKey;\n if (typeof key !== \"string\") throw shape(\"an installation without studioKey\");\n return key;\n });\n}\n"],"mappings":";AACO,IAAM,eAAe;AAAA;AAAA,EAE1B,eAAe;AAAA;AAAA,EAEf,KAAK;AAAA;AAAA,EAEL,SAAS;AAAA;AAAA,EAET,QAAQ;AAAA;AAAA,EAER,OAAO;AAAA;AAAA,EAEP,UAAU;AAAA;AAAA,EAEV,MAAM;AAAA;AAAA,EAEN,WAAW;AAAA;AAAA,EAEX,SAAS;AAAA;AAAA,EAET,aAAa;AAAA;AAAA,EAEb,SAAS;AAAA;AAAA,EAET,OAAO;AAAA;AAAA,EAEP,aAAa;AAAA;AAAA,EAEb,QAAQ;AAAA;AAAA,EAER,aAAa;AACf;AAIO,SAAS,eAAe,QAAuD;AACpF,MAAI,WAAW,OAAO,WAAW,IAAK,QAAO,EAAE,QAAQ,KAAK,MAAM,aAAa,IAAI;AACnF,MAAI,WAAW,IAAK,QAAO,EAAE,QAAQ,KAAK,MAAM,aAAa,QAAQ;AACrE,MAAI,WAAW,IAAK,QAAO,EAAE,QAAQ,KAAK,MAAM,aAAa,OAAO;AACpE,MAAI,WAAW,OAAO,WAAW,IAAK,QAAO,EAAE,QAAQ,KAAK,MAAM,aAAa,MA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AAC7E,aAAO,WAAW,MAAM,KAAK,MAAM,KAAK,kBAAkB,WAAW,IAAI,KAAK,EAAE,CAAC,CAAC;AAAA,IACpF;AAAA,IACA,MAAM,WAAW,OAAO,EAAE,aAAa,0BAA0B,WAAW,SAAS,wBAAwB,IAAI,CAAC,GAAG;AACnH,YAAM,WAAW,gBAAgB,QAAQ,MAAM,IAAI,GAAG,MAAM;AAC5D,iBAAS;AACP,cAAM,MAAM,MAAM,OAAO,KAAK;AAC9B,YAAI,WAAW,GAAG,EAAG,QAAO;AAC5B,YAAI,QAAQ,QAAQ,MAAM,IAAI,GAAG,QAAQ,EAAG,OAAM,IAAI,aAAa,aAAa,aAAa,oBAAoB,IAAI,MAAM,UAAU,MAAM,OAAO,EAAE,QAAQ,IAAI,CAAC;AACjK,cAAM,MAAM,UAAU;AAAA,MACxB;AAAA,IACF;AAAA,EACF;AACF;","names":["shape","text"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krizaka/orazaka-client",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "One Orazaka client for the TypeScript products: start a Studio run (safe to retry with an idempotency key), read its status and outputs, wait for it, with typed errors with stable codes, a time limit and a circuit breaker. Base URL, key and clock are parameters; no environment, no framework.",
5
5
  "keywords": [
6
6
  "krizaka",
@@ -47,7 +47,7 @@
47
47
  "tsup": "^8.5.0",
48
48
  "typescript": "^5.9.3",
49
49
  "vitest": "^4.1.11",
50
- "@krizaka/config": "^0.8.0"
50
+ "@krizaka/config": "^0.10.0"
51
51
  },
52
52
  "scripts": {
53
53
  "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup",