@wiconnect/sdk 0.0.0-stage → 1.0.0-rc.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 (61) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +35 -2
  3. package/dist/cjs/client.d.ts +79 -0
  4. package/dist/cjs/client.js +128 -0
  5. package/dist/cjs/contract.d.ts +53 -0
  6. package/dist/cjs/contract.js +76 -0
  7. package/dist/cjs/enums.d.ts +29 -0
  8. package/dist/cjs/enums.js +48 -0
  9. package/dist/cjs/environment.d.ts +6 -0
  10. package/dist/cjs/environment.js +15 -0
  11. package/dist/cjs/errors.d.ts +99 -0
  12. package/dist/cjs/errors.js +144 -0
  13. package/dist/cjs/index.d.ts +13 -0
  14. package/dist/cjs/index.js +53 -0
  15. package/dist/cjs/members.d.ts +61 -0
  16. package/dist/cjs/members.js +100 -0
  17. package/dist/cjs/package.json +1 -0
  18. package/dist/cjs/paging.d.ts +12 -0
  19. package/dist/cjs/paging.js +35 -0
  20. package/dist/cjs/presence.d.ts +42 -0
  21. package/dist/cjs/presence.js +108 -0
  22. package/dist/cjs/resource.d.ts +17 -0
  23. package/dist/cjs/resource.js +30 -0
  24. package/dist/cjs/transport.d.ts +64 -0
  25. package/dist/cjs/transport.js +332 -0
  26. package/dist/cjs/types.d.ts +246 -0
  27. package/dist/cjs/types.js +2 -0
  28. package/dist/cjs/validate.d.ts +11 -0
  29. package/dist/cjs/validate.js +67 -0
  30. package/dist/cjs/version.d.ts +4 -0
  31. package/dist/cjs/version.js +7 -0
  32. package/dist/esm/client.d.ts +79 -0
  33. package/dist/esm/client.js +120 -0
  34. package/dist/esm/contract.d.ts +53 -0
  35. package/dist/esm/contract.js +73 -0
  36. package/dist/esm/enums.d.ts +29 -0
  37. package/dist/esm/enums.js +45 -0
  38. package/dist/esm/environment.d.ts +6 -0
  39. package/dist/esm/environment.js +12 -0
  40. package/dist/esm/errors.d.ts +99 -0
  41. package/dist/esm/errors.js +116 -0
  42. package/dist/esm/index.d.ts +13 -0
  43. package/dist/esm/index.js +7 -0
  44. package/dist/esm/members.d.ts +61 -0
  45. package/dist/esm/members.js +96 -0
  46. package/dist/esm/package.json +1 -0
  47. package/dist/esm/paging.d.ts +12 -0
  48. package/dist/esm/paging.js +31 -0
  49. package/dist/esm/presence.d.ts +42 -0
  50. package/dist/esm/presence.js +104 -0
  51. package/dist/esm/resource.d.ts +17 -0
  52. package/dist/esm/resource.js +24 -0
  53. package/dist/esm/transport.d.ts +64 -0
  54. package/dist/esm/transport.js +326 -0
  55. package/dist/esm/types.d.ts +246 -0
  56. package/dist/esm/types.js +1 -0
  57. package/dist/esm/validate.d.ts +11 -0
  58. package/dist/esm/validate.js +56 -0
  59. package/dist/esm/version.d.ts +4 -0
  60. package/dist/esm/version.js +4 -0
  61. package/package.json +43 -4
@@ -0,0 +1,64 @@
1
+ export interface RetryOptions {
2
+ /** Retries after the first attempt. Default 3, 0 to 10. */
3
+ maxRetries?: number;
4
+ /** First backoff step, ms. Default 250. */
5
+ baseDelayMs?: number;
6
+ /** Backoff ceiling, ms. Default 4000. */
7
+ maxDelayMs?: number;
8
+ /** Jitter source (0 to 1). For tests. */
9
+ random?: () => number;
10
+ /** Wait function. For tests. */
11
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
12
+ }
13
+ export interface ClientOptions {
14
+ /** The cloud origin, for example https://cloud.example.com . https only (loopback may use http, for local stand-ins). */
15
+ baseUrl: string;
16
+ /** Total time for one call, all attempts and waits included. Default 15000 ms. */
17
+ timeoutMs?: number;
18
+ retry?: RetryOptions;
19
+ /** A fetch implementation; default the global one. */
20
+ fetch?: typeof fetch;
21
+ /** Appended to the User-Agent, for example your application name. */
22
+ userAgentSuffix?: string;
23
+ }
24
+ /** Options every call accepts. */
25
+ export interface CallOptions {
26
+ /** Cancels the call. A cancelled write is "unknown", not "failed". */
27
+ signal?: AbortSignal;
28
+ /** Total time for this call, overriding the instance default. */
29
+ timeoutMs?: number;
30
+ }
31
+ export type Method = "GET" | "POST" | "PUT" | "PATCH";
32
+ export interface RequestSpec extends CallOptions {
33
+ method: Method;
34
+ /** Path below the origin, already escaped. */
35
+ path: string;
36
+ query?: Record<string, string | number | undefined>;
37
+ body?: unknown;
38
+ /** A POST's Idempotency-Key. Present on every POST the SDK sends, and the same on every retry of it. */
39
+ idempotencyKey?: string;
40
+ /** Reported in "no such endpoint" messages. */
41
+ what?: string;
42
+ }
43
+ export interface Reply<T> {
44
+ data: T;
45
+ status: number;
46
+ headers: Headers;
47
+ }
48
+ export declare function checkBaseUrl(raw: unknown): string;
49
+ export declare function parseRetryAfter(h: string | null, now?: number): number | undefined;
50
+ export declare class Transport {
51
+ private readonly secret;
52
+ readonly origin: string;
53
+ readonly timeoutMs: number;
54
+ private readonly retry;
55
+ private readonly fetchImpl;
56
+ private readonly userAgent;
57
+ private readonly secrets;
58
+ constructor(opts: ClientOptions, secret: () => string | Promise<string>);
59
+ request<T>(spec: RequestSpec): Promise<Reply<T>>;
60
+ private once;
61
+ private interpret;
62
+ private apiError;
63
+ private byStatus;
64
+ }
@@ -0,0 +1,332 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Transport = void 0;
4
+ exports.checkBaseUrl = checkBaseUrl;
5
+ exports.parseRetryAfter = parseRetryAfter;
6
+ // The one place that talks HTTP: timeout, cancellation, retry, idempotency, error mapping, redaction.
7
+ // Contract 3.8 is implemented here and only here, so no endpoint has a rule of its own.
8
+ const version_js_1 = require("./version.js");
9
+ const contract_js_1 = require("./contract.js");
10
+ const errors_js_1 = require("./errors.js");
11
+ const validate_js_1 = require("./validate.js");
12
+ const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
13
+ const MAX_BODY = 16 * 1024;
14
+ function checkBaseUrl(raw) {
15
+ if (typeof raw !== "string")
16
+ throw new errors_js_1.InvalidArgumentError("baseUrl must be a string such as https://cloud.example.com");
17
+ let u;
18
+ try {
19
+ u = new URL(raw);
20
+ }
21
+ catch {
22
+ throw new errors_js_1.InvalidArgumentError("baseUrl is not a valid URL (expected https://<cloud host>)");
23
+ }
24
+ const loopback = LOOPBACK.has(u.hostname) || u.hostname.endsWith(".localhost");
25
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && loopback))
26
+ throw new errors_js_1.InvalidArgumentError("baseUrl must be https (plain http is accepted only for localhost stand-ins)");
27
+ if (u.username || u.password)
28
+ throw new errors_js_1.InvalidArgumentError("baseUrl must not contain a user name or password");
29
+ if (u.search || u.hash)
30
+ throw new errors_js_1.InvalidArgumentError("baseUrl must not contain a query or fragment: secrets never travel in a URL");
31
+ return u.origin + u.pathname.replace(/\/+$/, "");
32
+ }
33
+ function checkRetry(r) {
34
+ const o = r ?? {};
35
+ const maxRetries = o.maxRetries ?? contract_js_1.CONTRACT.limits.maxRetries;
36
+ if (!Number.isInteger(maxRetries) || maxRetries < 0 || maxRetries > 10)
37
+ throw new errors_js_1.InvalidArgumentError("retry.maxRetries must be an integer from 0 to 10");
38
+ const baseDelayMs = o.baseDelayMs ?? 250;
39
+ const maxDelayMs = o.maxDelayMs ?? 4000;
40
+ if (!(baseDelayMs > 0) || !(maxDelayMs > 0))
41
+ throw new errors_js_1.InvalidArgumentError("retry delays must be positive");
42
+ return { maxRetries, baseDelayMs, maxDelayMs, random: o.random ?? Math.random, sleep: o.sleep ?? defaultSleep };
43
+ }
44
+ function defaultSleep(ms, signal) {
45
+ return new Promise((resolve, reject) => {
46
+ if (signal?.aborted)
47
+ return reject(signal.reason);
48
+ const t = setTimeout(() => {
49
+ signal?.removeEventListener("abort", onAbort);
50
+ resolve();
51
+ }, ms);
52
+ const onAbort = () => {
53
+ clearTimeout(t);
54
+ reject(signal?.reason);
55
+ };
56
+ signal?.addEventListener("abort", onAbort, { once: true });
57
+ });
58
+ }
59
+ function parseRetryAfter(h, now = Date.now()) {
60
+ if (!h)
61
+ return undefined;
62
+ const t = h.trim();
63
+ if (/^\d+$/.test(t))
64
+ return Number(t);
65
+ const d = Date.parse(t);
66
+ if (Number.isNaN(d))
67
+ return undefined;
68
+ return Math.max(0, Math.ceil((d - now) / 1000));
69
+ }
70
+ // Errors raised before an attempt went out: they count as no attempt and leave nothing unknown.
71
+ const notSent = new WeakSet();
72
+ function unsent(e) {
73
+ notSent.add(e);
74
+ return e;
75
+ }
76
+ // Settles with the token, or rejects as soon as the signal aborts; the token function is not waited for after that.
77
+ function untilAborted(get, signal) {
78
+ return new Promise((resolve, reject) => {
79
+ if (signal.aborted)
80
+ return reject(signal.reason);
81
+ const onAbort = () => reject(signal.reason);
82
+ signal.addEventListener("abort", onAbort, { once: true });
83
+ const done = () => signal.removeEventListener("abort", onAbort);
84
+ Promise.resolve()
85
+ .then(get)
86
+ .then((v) => {
87
+ done();
88
+ resolve(v);
89
+ }, (e) => {
90
+ done();
91
+ reject(e);
92
+ });
93
+ });
94
+ }
95
+ class Transport {
96
+ secret;
97
+ origin;
98
+ timeoutMs;
99
+ retry;
100
+ fetchImpl;
101
+ userAgent;
102
+ secrets = new Set();
103
+ constructor(opts, secret) {
104
+ this.secret = secret;
105
+ this.origin = checkBaseUrl(opts.baseUrl);
106
+ this.timeoutMs = opts.timeoutMs ?? contract_js_1.CONTRACT.limits.defaultTimeoutMs;
107
+ if (typeof this.timeoutMs !== "number" || !Number.isFinite(this.timeoutMs) || this.timeoutMs <= 0)
108
+ throw new errors_js_1.InvalidArgumentError("timeoutMs must be a positive number of milliseconds");
109
+ this.retry = checkRetry(opts.retry);
110
+ this.fetchImpl = opts.fetch ?? globalThis.fetch;
111
+ if (typeof this.fetchImpl !== "function")
112
+ throw new errors_js_1.InvalidArgumentError("no fetch available: use Node.js 22 or newer, or pass options.fetch");
113
+ this.userAgent = opts.userAgentSuffix ? `${version_js_1.USER_AGENT} ${opts.userAgentSuffix}` : version_js_1.USER_AGENT;
114
+ }
115
+ async request(spec) {
116
+ const { method } = spec;
117
+ const total = spec.timeoutMs ?? this.timeoutMs;
118
+ if (typeof total !== "number" || !Number.isFinite(total) || total <= 0)
119
+ throw new errors_js_1.InvalidArgumentError("timeoutMs must be a positive number of milliseconds");
120
+ const started = Date.now();
121
+ const deadline = started + total;
122
+ const user = spec.signal;
123
+ const canRepeat = method === "GET" || method === "POST"; // POST always carries an Idempotency-Key; PUT/PATCH never repeat // POST always carries an Idempotency-Key
124
+ const stamp = (e, attempts) => {
125
+ e.attempts = attempts;
126
+ if (spec.idempotencyKey)
127
+ e.idempotencyKey = spec.idempotencyKey;
128
+ return e;
129
+ };
130
+ if (user?.aborted)
131
+ throw stamp(new errors_js_1.AbortedError("the call was cancelled before it was sent"), 0);
132
+ let body;
133
+ if (spec.body !== undefined) {
134
+ body = JSON.stringify(spec.body);
135
+ if (Buffer.byteLength(body) > MAX_BODY)
136
+ throw new errors_js_1.InvalidArgumentError("request body is larger than the 16 KiB the cloud accepts");
137
+ }
138
+ // Sticky across the attempts of this call: once one attempt of a write may have run, a later 401 or 409 only
139
+ // says that attempt was refused, not that the earlier one did nothing (#1320).
140
+ let unknown = false;
141
+ for (let attempt = 0;; attempt++) {
142
+ let err;
143
+ try {
144
+ return await this.once(spec, body, deadline, user);
145
+ }
146
+ catch (e) {
147
+ if (!(e instanceof errors_js_1.WiConnectError))
148
+ throw e;
149
+ err = e;
150
+ }
151
+ const sent = !notSent.has(err);
152
+ stamp(err, sent ? attempt + 1 : attempt);
153
+ const write = method !== "GET";
154
+ const status = err.status;
155
+ const isThrottle = err instanceof errors_js_1.RateLimitedError;
156
+ const isServer = err instanceof errors_js_1.ServerError && (status === 500 || status === 502 || status === 503 || status === 504);
157
+ const isNet = err instanceof errors_js_1.NetworkError;
158
+ // Unknown outcome: a write that may have been carried out. 429 means it did not run; 4xx means it was refused;
159
+ // an attempt stopped before it went out ran nothing.
160
+ if (write && sent && (isNet || err instanceof errors_js_1.TimeoutError || err instanceof errors_js_1.AbortedError || err instanceof errors_js_1.ServerError || err instanceof errors_js_1.ProtocolError))
161
+ unknown = true;
162
+ err.outcomeUnknown = unknown;
163
+ // Contract 3.8: GET and POST retry network errors, 429 and 500/502/503/504; PUT and PATCH retry only 429.
164
+ const retryable = isThrottle || (canRepeat && (isNet || isServer));
165
+ if (!retryable || attempt >= this.retry.maxRetries)
166
+ throw err;
167
+ const remaining = deadline - Date.now();
168
+ const asked = err.retryAfterSeconds !== undefined && (isThrottle || status === 503) ? err.retryAfterSeconds * 1000 : undefined;
169
+ const cap = Math.min(this.retry.maxDelayMs, this.retry.baseDelayMs * 2 ** attempt);
170
+ const wait = asked ?? Math.floor(this.retry.random() * cap);
171
+ if (wait >= remaining)
172
+ throw err; // never wait past the budget: tell the caller now
173
+ try {
174
+ await this.retry.sleep(wait, user);
175
+ }
176
+ catch {
177
+ // Cancelled while waiting.
178
+ }
179
+ if (user?.aborted) {
180
+ const a = stamp(new errors_js_1.AbortedError("the call was cancelled while waiting to retry"), attempt + 1);
181
+ a.outcomeUnknown = unknown; // what the earlier attempts left behind is still what it was
182
+ throw a;
183
+ }
184
+ }
185
+ }
186
+ async once(spec, body, deadline, user) {
187
+ const left = deadline - Date.now();
188
+ if (left <= 0)
189
+ throw unsent(new errors_js_1.TimeoutError("the call ran out of time before it could be sent again"));
190
+ if (user?.aborted)
191
+ throw unsent(new errors_js_1.AbortedError("the call was cancelled before it was sent"));
192
+ // The timer and the cancel listener are in place before the token is fetched: a token function that is slow
193
+ // (a vault, a refresh) is part of the call, so the total budget and the caller's signal cover it too (#1320).
194
+ const ctl = new AbortController();
195
+ let timedOut = false;
196
+ let cancelled = false;
197
+ const timer = setTimeout(() => {
198
+ timedOut = true;
199
+ ctl.abort();
200
+ }, left);
201
+ const onUser = () => {
202
+ cancelled = true;
203
+ ctl.abort();
204
+ };
205
+ user?.addEventListener("abort", onUser, { once: true });
206
+ try {
207
+ let token;
208
+ try {
209
+ token = await untilAborted(() => this.secret(), ctl.signal);
210
+ }
211
+ catch (e) {
212
+ if (timedOut)
213
+ throw unsent(new errors_js_1.TimeoutError("the call ran out of time while waiting for the token function; nothing was sent"));
214
+ if (cancelled)
215
+ throw unsent(new errors_js_1.AbortedError("the call was cancelled while waiting for the token function; nothing was sent"));
216
+ throw e;
217
+ }
218
+ this.secrets.add(token);
219
+ const url = new URL(this.origin + spec.path);
220
+ for (const [k, v] of Object.entries(spec.query ?? {}))
221
+ if (v !== undefined)
222
+ url.searchParams.set(k, String(v));
223
+ const headers = { authorization: `Bearer ${token}`, accept: "application/json", "user-agent": this.userAgent };
224
+ if (body !== undefined)
225
+ headers["content-type"] = "application/json";
226
+ if (spec.idempotencyKey)
227
+ headers["idempotency-key"] = spec.idempotencyKey;
228
+ let res;
229
+ let text;
230
+ try {
231
+ res = await this.fetchImpl(url, { method: spec.method, headers, body, signal: ctl.signal, redirect: "manual" });
232
+ text = await res.text();
233
+ }
234
+ catch (e) {
235
+ if (timedOut)
236
+ throw new errors_js_1.TimeoutError("the call did not finish within the time allowed and was stopped");
237
+ if (cancelled)
238
+ throw new errors_js_1.AbortedError("the call was cancelled");
239
+ const n = new errors_js_1.NetworkError("could not reach the WiConnect cloud (no response received)");
240
+ n.reason = (0, errors_js_1.redact)(String(e?.cause?.code ?? e?.name ?? "error"), this.secrets);
241
+ throw n;
242
+ }
243
+ return this.interpret(res, text, spec);
244
+ }
245
+ finally {
246
+ clearTimeout(timer);
247
+ user?.removeEventListener("abort", onUser);
248
+ }
249
+ }
250
+ interpret(res, text, spec) {
251
+ const requestIdHeader = res.headers.get("x-request-id") || undefined;
252
+ if (res.status >= 300 && res.status < 400)
253
+ throw new errors_js_1.ProtocolError(`unexpected redirect (HTTP ${res.status}); the cloud does not redirect API calls`, { status: res.status, requestId: requestIdHeader });
254
+ if (res.status >= 200 && res.status < 300) {
255
+ let data;
256
+ try {
257
+ data = JSON.parse(text);
258
+ }
259
+ catch {
260
+ throw new errors_js_1.ProtocolError(`the cloud answered HTTP ${res.status} with a body that is not JSON`, { status: res.status, requestId: requestIdHeader });
261
+ }
262
+ return { data: data, status: res.status, headers: res.headers };
263
+ }
264
+ throw this.apiError(res, text, spec, requestIdHeader);
265
+ }
266
+ apiError(res, text, spec, headerId) {
267
+ const status = res.status;
268
+ let parsed;
269
+ try {
270
+ parsed = JSON.parse(text);
271
+ }
272
+ catch {
273
+ parsed = undefined;
274
+ }
275
+ const apiBody = (0, validate_js_1.isObject)(parsed) && typeof parsed.error === "string" ? parsed : undefined;
276
+ const bodyId = apiBody && typeof apiBody.request_id === "string" && apiBody.request_id ? apiBody.request_id : undefined;
277
+ const fields = {
278
+ status,
279
+ requestId: headerId || bodyId,
280
+ retryAfterSeconds: parseRetryAfter(res.headers.get("retry-after")),
281
+ };
282
+ if (!apiBody) {
283
+ if (status === 404) {
284
+ return new errors_js_1.EndpointNotAvailableError(`this WiConnect cloud does not offer ${spec.method} ${spec.what ?? spec.path} (HTTP 404 without an API error body). ` +
285
+ `The cloud is probably older than this SDK and does not have this endpoint yet. ` +
286
+ `Ask your WiConnect contact which cloud version you are on, or use an SDK version that matches it.`, fields);
287
+ }
288
+ return this.byStatus(status, undefined, `HTTP ${status}`, fields);
289
+ }
290
+ const code = apiBody.error;
291
+ const said = typeof apiBody.message === "string" ? (0, errors_js_1.redact)(apiBody.message, this.secrets) : "";
292
+ const e = this.byStatus(status, code, `${code}${said ? `: ${said}` : ""} (HTTP ${status}${fields.requestId ? `, request ${fields.requestId}` : ""})`, { ...fields, code });
293
+ if (e instanceof errors_js_1.AmbiguousPersonError && Array.isArray(apiBody.candidates)) {
294
+ e.candidates = apiBody.candidates
295
+ .filter((c) => (0, validate_js_1.isObject)(c))
296
+ .map((c) => ({ issuer: String(c.issuer ?? ""), id: String(c.id ?? "") }));
297
+ }
298
+ return e;
299
+ }
300
+ byStatus(status, code, message, f) {
301
+ const msg = `WiConnect API error: ${message}`;
302
+ if (status === 400)
303
+ return code === "member_identity_invalid" ? new errors_js_1.MemberIdentityInvalidError(msg, f) : new errors_js_1.BadRequestError(msg, f);
304
+ if (status === 401)
305
+ return new errors_js_1.CredentialInvalidError(msg, f);
306
+ if (status === 403)
307
+ return new errors_js_1.ForbiddenError(msg, f);
308
+ if (status === 404)
309
+ return new errors_js_1.NotFoundError(msg, f);
310
+ if (status === 409) {
311
+ if (code === "version_conflict")
312
+ return new errors_js_1.VersionConflictError(msg, f);
313
+ if (code === "ambiguous_person")
314
+ return new errors_js_1.AmbiguousPersonError(msg, f);
315
+ if (code === "local_membership_disabled")
316
+ return new errors_js_1.LocalMembershipDisabledError(msg, f);
317
+ if (code === "member_exists")
318
+ return new errors_js_1.MemberExistsError(msg, f);
319
+ return new errors_js_1.ConflictError(msg, f);
320
+ }
321
+ if (status === 422 && code === "idempotency_key_reuse")
322
+ return new errors_js_1.IdempotencyKeyReuseError(msg, f);
323
+ if (status === 428)
324
+ return new errors_js_1.VersionRequiredError(msg, f);
325
+ if (status === 429)
326
+ return new errors_js_1.RateLimitedError(msg, f);
327
+ if (status >= 500)
328
+ return new errors_js_1.ServerError(msg, f);
329
+ return new errors_js_1.ApiError(msg, f);
330
+ }
331
+ }
332
+ exports.Transport = Transport;
@@ -0,0 +1,246 @@
1
+ import type { APPLIED_BY, APPLIED_STATES, AUTHORIZED_STATES, CAPABILITIES_ENFORCER_KINDS, CAPABILITY_STATES, CREDENTIAL_STATES, DIAGNOSTICS_ENFORCER_STATES, DISCONNECT_OUTCOMES, ENDED_REASONS, ENFORCER_KINDS, GRANT_STATES, MEMBER_STATES, Open, PRESENCE_INTENTS, PRESENCE_SOURCES, PRESENCE_STATES, REVOCATION_CONFIRMED_BY, REVOCATION_STATES, SCOPES, WAN_SOURCES, WAN_STATES } from "./enums.js";
2
+ export type GrantState = Open<(typeof GRANT_STATES)[number]>;
3
+ export type Scope = Open<(typeof SCOPES)[number]>;
4
+ export type MemberState = Open<(typeof MEMBER_STATES)[number]>;
5
+ export type PresenceIntent = Open<(typeof PRESENCE_INTENTS)[number]>;
6
+ /** `limit` default 50, at most 200. `next_cursor` is opaque; "" on the last page. Never build or parse one. */
7
+ export interface Page<T> {
8
+ items: T[];
9
+ limit: number;
10
+ next_cursor: string;
11
+ }
12
+ export interface Credential {
13
+ id: string;
14
+ name: string;
15
+ organization: string;
16
+ sites: string[];
17
+ scopes: Scope[];
18
+ org_wide: boolean;
19
+ state: Open<(typeof CREDENTIAL_STATES)[number]>;
20
+ created_at: number;
21
+ expires_at: number;
22
+ last_used_at?: number;
23
+ issued_by?: string;
24
+ previous_secret_ends_at?: number;
25
+ version: number;
26
+ }
27
+ export interface Site {
28
+ id: string;
29
+ slug: string;
30
+ display_name: string;
31
+ network_name?: string;
32
+ landing_url?: string;
33
+ theme?: string;
34
+ timezone?: string;
35
+ contact?: string;
36
+ consent: {
37
+ text: string;
38
+ version: number;
39
+ };
40
+ has_logo?: boolean;
41
+ /** Read only. */
42
+ disabled?: boolean;
43
+ /** Read only. */
44
+ grant_scope?: Open<"organization" | "site">;
45
+ created?: number;
46
+ version: number;
47
+ }
48
+ /** One effect layer that is only ever "saved". */
49
+ export interface SavedLayer {
50
+ state: "saved";
51
+ version?: number;
52
+ at: number;
53
+ }
54
+ /**
55
+ * The five effect states, answered separately (contract section 4). Nothing is inferred upward:
56
+ * `applied.state === "confirmed"` means the executor says it carried the decision out, not that the internet works;
57
+ * `observed.wan` is always `unknown` in the first release (`no_wan_evidence_source`).
58
+ */
59
+ export interface SessionState {
60
+ saved: {
61
+ state: "saved";
62
+ at: number;
63
+ };
64
+ authorized: {
65
+ state: Open<(typeof AUTHORIZED_STATES)[number]>;
66
+ expires_at: number;
67
+ ended_reason?: Open<(typeof ENDED_REASONS)[number]>;
68
+ };
69
+ applied: {
70
+ state: Open<(typeof APPLIED_STATES)[number]>;
71
+ at?: number;
72
+ by?: Open<(typeof APPLIED_BY)[number]>;
73
+ reason?: string;
74
+ };
75
+ observed: {
76
+ presence: {
77
+ state: Open<(typeof PRESENCE_STATES)[number]>;
78
+ at?: number;
79
+ source?: Open<(typeof PRESENCE_SOURCES)[number]>;
80
+ reason?: string;
81
+ };
82
+ wan: {
83
+ state: Open<(typeof WAN_STATES)[number]>;
84
+ at?: number;
85
+ source?: Open<(typeof WAN_SOURCES)[number]>;
86
+ reason: string;
87
+ };
88
+ };
89
+ }
90
+ /**
91
+ * What is known about ending a session. `pending` is NOT "disconnected": the executor has not confirmed.
92
+ * `unconfirmed_expired` is "the time ran out", also not a confirmation.
93
+ */
94
+ export interface Revocation {
95
+ state: Open<(typeof REVOCATION_STATES)[number]>;
96
+ requested_at: number;
97
+ confirmed_at?: number;
98
+ confirmed_by?: Open<(typeof REVOCATION_CONFIRMED_BY)[number]>;
99
+ /** null: no known bound (a gateway that has not been heard from). Never a guess. */
100
+ latest_effect_at?: number | null;
101
+ disconnect?: {
102
+ attempted?: boolean;
103
+ outcome?: Open<(typeof DISCONNECT_OUTCOMES)[number]>;
104
+ };
105
+ request_id?: string;
106
+ }
107
+ export interface Session {
108
+ id: string;
109
+ site_id: string;
110
+ subject: {
111
+ issuer: string;
112
+ subject: string;
113
+ };
114
+ /** Masked: the first three bytes only. No IP. */
115
+ device: {
116
+ mac_masked: string;
117
+ };
118
+ class?: string;
119
+ synthetic?: boolean;
120
+ issued_at: number;
121
+ expires_at: number;
122
+ enforcer: Open<(typeof ENFORCER_KINDS)[number]>;
123
+ grant_state: GrantState;
124
+ state: SessionState;
125
+ revocation?: Revocation | null;
126
+ }
127
+ export interface Capability {
128
+ key: string;
129
+ state: Open<(typeof CAPABILITY_STATES)[number]>;
130
+ value?: number | null;
131
+ reason?: string;
132
+ source?: string;
133
+ reported_at?: number;
134
+ }
135
+ export interface Capabilities {
136
+ site_id: string;
137
+ enforcer: Open<(typeof CAPABILITIES_ENFORCER_KINDS)[number]>;
138
+ items: Capability[];
139
+ }
140
+ export interface Diagnostics {
141
+ site_id: string;
142
+ generated_at: number;
143
+ enforcer: {
144
+ kind: Open<(typeof CAPABILITIES_ENFORCER_KINDS)[number]>;
145
+ state: Open<(typeof DIAGNOSTICS_ENFORCER_STATES)[number]>;
146
+ last_seen?: number;
147
+ };
148
+ /** Gateway sites only. */
149
+ config?: {
150
+ desired_version?: number;
151
+ applied_version?: number;
152
+ applied?: string;
153
+ last_ack_at?: number;
154
+ };
155
+ /** Sites served by their own access points only. */
156
+ native_setup?: {
157
+ checks?: Array<{
158
+ key: string;
159
+ state: string;
160
+ last_seen?: number;
161
+ }>;
162
+ };
163
+ last_identity_test?: {
164
+ id: string;
165
+ status: string;
166
+ at: number;
167
+ } | null;
168
+ observed: {
169
+ wan: {
170
+ state: Open<(typeof WAN_STATES)[number]>;
171
+ at?: number;
172
+ reason: string;
173
+ };
174
+ };
175
+ }
176
+ export interface Member {
177
+ id: string;
178
+ /** With `subject`, the stable identity. Never an e-mail address or phone number. */
179
+ issuer: string;
180
+ /** Shown case-folded, as the existing member key is. */
181
+ subject: string;
182
+ state: MemberState;
183
+ /** Unix seconds; null or absent for no deadline. */
184
+ expires_at?: number | null;
185
+ created_at: number;
186
+ updated_at: number;
187
+ version: number;
188
+ }
189
+ /**
190
+ * The answer to a member write. Three different facts, not one "success":
191
+ * `saved` — eligibility was changed in the cloud;
192
+ * `sessions.revocation` — whether this call asked for any session to end (`not_requested`: it did not;
193
+ * ending sessions is `sessions.revoke`, a separate operation with its own answer).
194
+ */
195
+ export interface MemberSaved {
196
+ member: Member;
197
+ saved: SavedLayer;
198
+ sessions: {
199
+ revocation: Open<"not_requested">;
200
+ };
201
+ }
202
+ export interface PresenceEntry {
203
+ id: string;
204
+ issuer: string;
205
+ email?: string;
206
+ phone?: string;
207
+ intent?: PresenceIntent;
208
+ online: boolean;
209
+ device: Open<"phone" | "computer" | "unknown">;
210
+ /** Unix seconds: when the venue gateway last saw this person's device. */
211
+ last_seen: number;
212
+ }
213
+ /**
214
+ * Who is here and willing to be known. **An empty `items` is not "the room is empty"**: the list holds only
215
+ * people who were seen in the last 15 minutes AND agreed to be known; a gateway with observation off, an offline
216
+ * gateway, or nobody consenting all give the same empty list.
217
+ */
218
+ export interface PresenceList {
219
+ items: PresenceEntry[];
220
+ /** How many people are visible in `items`. Not a head count of the room. */
221
+ visibleCount: number;
222
+ /** When this SDK received the answer (ms since epoch). */
223
+ fetchedAt: number;
224
+ /** From Cache-Control: asking more often than this learns nothing new. */
225
+ cacheMaxAgeSeconds?: number;
226
+ /** A reminder that travels with the data. */
227
+ note: string;
228
+ }
229
+ export interface ConsentResult {
230
+ id: string;
231
+ issuer: string;
232
+ consent: boolean;
233
+ intent: PresenceIntent;
234
+ }
235
+ export type PersonRef = {
236
+ id: string;
237
+ issuer?: string;
238
+ } | {
239
+ email: string;
240
+ } | {
241
+ phone: string;
242
+ };
243
+ export interface AmbiguousCandidate {
244
+ issuer: string;
245
+ id: string;
246
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,11 @@
1
+ export declare function isObject(v: unknown): v is Record<string, unknown>;
2
+ export declare function bad(message: string): never;
3
+ export declare function requireObject(v: unknown, what: string): Record<string, unknown>;
4
+ /** Refuses keys the cloud would reject as unknown (and so catches typos like `emial`). */
5
+ export declare function onlyKeys(o: object, allowed: readonly string[], what: string): void;
6
+ export declare function nonEmptyString(v: unknown, what: string, max?: number): string;
7
+ export declare function limitOf(v: unknown): number | undefined;
8
+ export declare function idempotencyKeyOf(v: unknown): string | undefined;
9
+ /** Unix seconds. A value in milliseconds is the usual mistake, so values beyond year 2100 are refused. */
10
+ export declare function unixSeconds(v: unknown, what: string): number;
11
+ export declare function versionOf(v: unknown): number;