@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.
- package/CHANGELOG.md +43 -0
- package/README.md +35 -2
- package/dist/cjs/client.d.ts +79 -0
- package/dist/cjs/client.js +128 -0
- package/dist/cjs/contract.d.ts +53 -0
- package/dist/cjs/contract.js +76 -0
- package/dist/cjs/enums.d.ts +29 -0
- package/dist/cjs/enums.js +48 -0
- package/dist/cjs/environment.d.ts +6 -0
- package/dist/cjs/environment.js +15 -0
- package/dist/cjs/errors.d.ts +99 -0
- package/dist/cjs/errors.js +144 -0
- package/dist/cjs/index.d.ts +13 -0
- package/dist/cjs/index.js +53 -0
- package/dist/cjs/members.d.ts +61 -0
- package/dist/cjs/members.js +100 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/paging.d.ts +12 -0
- package/dist/cjs/paging.js +35 -0
- package/dist/cjs/presence.d.ts +42 -0
- package/dist/cjs/presence.js +108 -0
- package/dist/cjs/resource.d.ts +17 -0
- package/dist/cjs/resource.js +30 -0
- package/dist/cjs/transport.d.ts +64 -0
- package/dist/cjs/transport.js +332 -0
- package/dist/cjs/types.d.ts +246 -0
- package/dist/cjs/types.js +2 -0
- package/dist/cjs/validate.d.ts +11 -0
- package/dist/cjs/validate.js +67 -0
- package/dist/cjs/version.d.ts +4 -0
- package/dist/cjs/version.js +7 -0
- package/dist/esm/client.d.ts +79 -0
- package/dist/esm/client.js +120 -0
- package/dist/esm/contract.d.ts +53 -0
- package/dist/esm/contract.js +73 -0
- package/dist/esm/enums.d.ts +29 -0
- package/dist/esm/enums.js +45 -0
- package/dist/esm/environment.d.ts +6 -0
- package/dist/esm/environment.js +12 -0
- package/dist/esm/errors.d.ts +99 -0
- package/dist/esm/errors.js +116 -0
- package/dist/esm/index.d.ts +13 -0
- package/dist/esm/index.js +7 -0
- package/dist/esm/members.d.ts +61 -0
- package/dist/esm/members.js +96 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/paging.d.ts +12 -0
- package/dist/esm/paging.js +31 -0
- package/dist/esm/presence.d.ts +42 -0
- package/dist/esm/presence.js +104 -0
- package/dist/esm/resource.d.ts +17 -0
- package/dist/esm/resource.js +24 -0
- package/dist/esm/transport.d.ts +64 -0
- package/dist/esm/transport.js +326 -0
- package/dist/esm/types.d.ts +246 -0
- package/dist/esm/types.js +1 -0
- package/dist/esm/validate.d.ts +11 -0
- package/dist/esm/validate.js +56 -0
- package/dist/esm/version.d.ts +4 -0
- package/dist/esm/version.js +4 -0
- package/package.json +43 -4
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/** Base class of every error thrown by this SDK. */
|
|
2
|
+
export class WiConnectError extends Error {
|
|
3
|
+
/** HTTP status; undefined when no response was received. */
|
|
4
|
+
status;
|
|
5
|
+
/** Stable machine code from the cloud (`version_conflict`, `rate_limited`, …). Do not parse `message`. */
|
|
6
|
+
code;
|
|
7
|
+
/** The cloud's X-Request-ID: quote it when asking for support. */
|
|
8
|
+
requestId;
|
|
9
|
+
/**
|
|
10
|
+
* True when a WRITE may or may not have happened (timeout, cancel, network loss, 5xx). It is not "failed":
|
|
11
|
+
* re-read before deciding, or repeat a POST with the same `idempotencyKey`. A 429 means it did not run.
|
|
12
|
+
*/
|
|
13
|
+
outcomeUnknown = false;
|
|
14
|
+
retryAfterSeconds;
|
|
15
|
+
/** The Idempotency-Key of a POST, so the same request can be repeated safely. */
|
|
16
|
+
idempotencyKey;
|
|
17
|
+
/** How many HTTP attempts were made. */
|
|
18
|
+
attempts;
|
|
19
|
+
constructor(message, fields = {}) {
|
|
20
|
+
super(message);
|
|
21
|
+
this.name = new.target.name;
|
|
22
|
+
Object.assign(this, fields);
|
|
23
|
+
this.outcomeUnknown = fields.outcomeUnknown ?? false;
|
|
24
|
+
}
|
|
25
|
+
/** Only plain fields: no cause, no headers. */
|
|
26
|
+
toJSON() {
|
|
27
|
+
const o = { name: this.name, message: this.message };
|
|
28
|
+
for (const k of ["status", "code", "requestId", "retryAfterSeconds", "idempotencyKey", "attempts"])
|
|
29
|
+
if (this[k] !== undefined)
|
|
30
|
+
o[k] = this[k];
|
|
31
|
+
o.outcomeUnknown = this.outcomeUnknown;
|
|
32
|
+
return o;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** The call was refused locally, before anything was sent. */
|
|
36
|
+
export class InvalidArgumentError extends WiConnectError {
|
|
37
|
+
}
|
|
38
|
+
/** The cloud answered with an error status. */
|
|
39
|
+
export class ApiError extends WiConnectError {
|
|
40
|
+
}
|
|
41
|
+
export class BadRequestError extends ApiError {
|
|
42
|
+
}
|
|
43
|
+
/** 400 member_identity_invalid: the issuer/subject cannot form a member identity (empty, over length, not canonical). */
|
|
44
|
+
export class MemberIdentityInvalidError extends BadRequestError {
|
|
45
|
+
}
|
|
46
|
+
/** 401 credential_invalid: absent, unknown, expired or revoked (deliberately not told apart). Do not retry. */
|
|
47
|
+
export class CredentialInvalidError extends ApiError {
|
|
48
|
+
}
|
|
49
|
+
/** 403: `scope_forbidden`, `site_forbidden` (this API) or `site_required` / `write_scope_required` (presence). */
|
|
50
|
+
export class ForbiddenError extends ApiError {
|
|
51
|
+
}
|
|
52
|
+
/** 404 with an API error body: it does not exist, or belongs to another organization (not told apart). */
|
|
53
|
+
export class NotFoundError extends ApiError {
|
|
54
|
+
}
|
|
55
|
+
/** 404 without an API error body: this cloud does not have the endpoint at all (an older cloud than this SDK). */
|
|
56
|
+
export class EndpointNotAvailableError extends ApiError {
|
|
57
|
+
}
|
|
58
|
+
export class ConflictError extends ApiError {
|
|
59
|
+
}
|
|
60
|
+
/** 409 local_membership_disabled: the site has no enabled local-membership rule, so a member entry would do
|
|
61
|
+
* nothing. Nothing was changed. Enable the rule in the console (an administrator's step), then repeat. */
|
|
62
|
+
export class LocalMembershipDisabledError extends ConflictError {
|
|
63
|
+
}
|
|
64
|
+
/** 409 member_exists: that issuer+subject already has an entry. Read it and update it instead. */
|
|
65
|
+
export class MemberExistsError extends ConflictError {
|
|
66
|
+
}
|
|
67
|
+
/** 409 version_conflict: someone changed it first. Re-read, then decide; do not overwrite blindly. */
|
|
68
|
+
export class VersionConflictError extends ConflictError {
|
|
69
|
+
}
|
|
70
|
+
/** 409 ambiguous_person: one e-mail/phone matches two identities. Nobody was changed. Name one candidate. */
|
|
71
|
+
export class AmbiguousPersonError extends ConflictError {
|
|
72
|
+
candidates = [];
|
|
73
|
+
toJSON() {
|
|
74
|
+
return { ...super.toJSON(), candidates: this.candidates };
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
export class IdempotencyKeyReuseError extends ApiError {
|
|
78
|
+
}
|
|
79
|
+
export class VersionRequiredError extends ApiError {
|
|
80
|
+
}
|
|
81
|
+
/** 429: it did NOT run. `retryAfterSeconds` says when to try again. */
|
|
82
|
+
export class RateLimitedError extends ApiError {
|
|
83
|
+
}
|
|
84
|
+
export class ServerError extends ApiError {
|
|
85
|
+
}
|
|
86
|
+
/** No usable response arrived. */
|
|
87
|
+
export class TransportError extends WiConnectError {
|
|
88
|
+
}
|
|
89
|
+
export class NetworkError extends TransportError {
|
|
90
|
+
/** A short, redacted reason such as ECONNRESET. */
|
|
91
|
+
reason;
|
|
92
|
+
toJSON() {
|
|
93
|
+
return this.reason ? { ...super.toJSON(), reason: this.reason } : super.toJSON();
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
export class TimeoutError extends TransportError {
|
|
97
|
+
}
|
|
98
|
+
export class AbortedError extends TransportError {
|
|
99
|
+
}
|
|
100
|
+
/** The cloud answered 2xx with something that is not the documented shape. */
|
|
101
|
+
export class ProtocolError extends WiConnectError {
|
|
102
|
+
}
|
|
103
|
+
export function isWiConnectError(e) {
|
|
104
|
+
return e instanceof WiConnectError;
|
|
105
|
+
}
|
|
106
|
+
const SECRET_SHAPES = [/wci_[A-Za-z0-9_-]*/g, /Bearer\s+[^\s"',;]+/gi];
|
|
107
|
+
/** Removes known secrets and anything shaped like an integration credential from text that may be shown. */
|
|
108
|
+
export function redact(text, secrets) {
|
|
109
|
+
let out = text;
|
|
110
|
+
for (const s of secrets)
|
|
111
|
+
if (s.length >= 4)
|
|
112
|
+
out = out.split(s).join("[redacted]");
|
|
113
|
+
for (const re of SECRET_SHAPES)
|
|
114
|
+
out = out.replace(re, (m) => (m.toLowerCase().startsWith("bearer") ? "Bearer [redacted]" : "[redacted]"));
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export { VERSION } from "./version.js";
|
|
2
|
+
export { WiConnect } from "./client.js";
|
|
3
|
+
export type { WiConnectOptions, ListOptions, ListSessionsOptions, RevokeOptions, Sites, Sessions, CapabilitiesApi, DiagnosticsApi } from "./client.js";
|
|
4
|
+
export { Members } from "./members.js";
|
|
5
|
+
export type { CreateMemberInput, CreateMemberOptions, ListMembersOptions, MemberKey, UpdateMemberInput } from "./members.js";
|
|
6
|
+
export { PresenceClient } from "./presence.js";
|
|
7
|
+
export type { PresenceOptions, UpdateConsentInput } from "./presence.js";
|
|
8
|
+
export type { IterateOptions } from "./paging.js";
|
|
9
|
+
export type { CallOptions, ClientOptions, RetryOptions } from "./transport.js";
|
|
10
|
+
export { AbortedError, AmbiguousPersonError, ApiError, BadRequestError, ConflictError, CredentialInvalidError, EndpointNotAvailableError, ForbiddenError, IdempotencyKeyReuseError, InvalidArgumentError, LocalMembershipDisabledError, MemberExistsError, MemberIdentityInvalidError, NetworkError, NotFoundError, ProtocolError, RateLimitedError, ServerError, TimeoutError, TransportError, VersionConflictError, VersionRequiredError, WiConnectError, isWiConnectError, } from "./errors.js";
|
|
11
|
+
export { CONTRACT } from "./contract.js";
|
|
12
|
+
export * from "./enums.js";
|
|
13
|
+
export type * from "./types.js";
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { VERSION } from "./version.js";
|
|
2
|
+
export { WiConnect } from "./client.js";
|
|
3
|
+
export { Members } from "./members.js";
|
|
4
|
+
export { PresenceClient } from "./presence.js";
|
|
5
|
+
export { AbortedError, AmbiguousPersonError, ApiError, BadRequestError, ConflictError, CredentialInvalidError, EndpointNotAvailableError, ForbiddenError, IdempotencyKeyReuseError, InvalidArgumentError, LocalMembershipDisabledError, MemberExistsError, MemberIdentityInvalidError, NetworkError, NotFoundError, ProtocolError, RateLimitedError, ServerError, TimeoutError, TransportError, VersionConflictError, VersionRequiredError, WiConnectError, isWiConnectError, } from "./errors.js";
|
|
6
|
+
export { CONTRACT } from "./contract.js";
|
|
7
|
+
export * from "./enums.js";
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { type IterateOptions } from "./paging.js";
|
|
2
|
+
import { Resource, type ListOptions } from "./resource.js";
|
|
3
|
+
import type { CallOptions } from "./transport.js";
|
|
4
|
+
import type { Member, MemberSaved, MemberState, Page } from "./types.js";
|
|
5
|
+
export interface MemberKey {
|
|
6
|
+
/** The identity provider that vouches for the subject, as it appears on the session. */
|
|
7
|
+
issuer: string;
|
|
8
|
+
/** The provider's stable subject id. Not an e-mail address or phone number. */
|
|
9
|
+
subject: string;
|
|
10
|
+
}
|
|
11
|
+
export interface CreateMemberInput extends MemberKey {
|
|
12
|
+
/** Unix seconds when eligibility ends; omit for no expiry. */
|
|
13
|
+
expiresAt?: number;
|
|
14
|
+
}
|
|
15
|
+
export interface CreateMemberOptions extends CallOptions {
|
|
16
|
+
/** Default: a fresh key per call, reused across automatic retries so the member is created once. */
|
|
17
|
+
idempotencyKey?: string;
|
|
18
|
+
}
|
|
19
|
+
export interface ListMembersOptions extends ListOptions {
|
|
20
|
+
/** With `subject`, finds one entry. `subject` alone is refused (the cloud rejects it too). */
|
|
21
|
+
issuer?: string;
|
|
22
|
+
subject?: string;
|
|
23
|
+
state?: MemberState;
|
|
24
|
+
}
|
|
25
|
+
export interface UpdateMemberInput {
|
|
26
|
+
/** The `version` you read. Required: a stale one is refused with VersionConflictError. */
|
|
27
|
+
version: number;
|
|
28
|
+
/** Unix seconds; `null` removes the expiry. */
|
|
29
|
+
expiresAt?: number | null;
|
|
30
|
+
/** `active` or `disabled`. `expired` is decided by time, not written. */
|
|
31
|
+
state?: "active" | "disabled";
|
|
32
|
+
}
|
|
33
|
+
export declare class Members extends Resource {
|
|
34
|
+
/**
|
|
35
|
+
* Make `issuer`+`subject` eligible. 409 `member_exists` if the identity already has an entry;
|
|
36
|
+
* 409 `local_membership_disabled` if the site has no enabled local-membership rule (nothing is changed).
|
|
37
|
+
*/
|
|
38
|
+
create(input: CreateMemberInput, options?: CreateMemberOptions): Promise<MemberSaved>;
|
|
39
|
+
get(memberId: string, options?: CallOptions): Promise<Member>;
|
|
40
|
+
list(options?: ListMembersOptions): Promise<Page<Member>>;
|
|
41
|
+
iterate(options?: ListMembersOptions & IterateOptions): AsyncGenerator<Member, void, undefined>;
|
|
42
|
+
/**
|
|
43
|
+
* Convenience for `list({issuer, subject})`: the entry for one identity, or null. Both fields are required.
|
|
44
|
+
* The cloud folds case in the member key, so the comparison does too.
|
|
45
|
+
*/
|
|
46
|
+
find(key: MemberKey, options?: CallOptions): Promise<Member | null>;
|
|
47
|
+
/**
|
|
48
|
+
* Change expiry and/or state. PATCH is protected by `version`, not by an idempotency key, and an automatic retry
|
|
49
|
+
* happens only for 429. After a timeout or 5xx the error says `outcomeUnknown`: read the member, then decide.
|
|
50
|
+
* This changes ELIGIBILITY only; it does not end sessions that are already online (see `sessions.revoke`).
|
|
51
|
+
*/
|
|
52
|
+
update(memberId: string, input: UpdateMemberInput, options?: CallOptions): Promise<MemberSaved>;
|
|
53
|
+
/** Convenience for `update(id, {version, state:"disabled"})`. Live sessions are untouched until `sessions.revoke`. */
|
|
54
|
+
disable(memberId: string, input: {
|
|
55
|
+
version: number;
|
|
56
|
+
}, options?: CallOptions): Promise<MemberSaved>;
|
|
57
|
+
/** Convenience for `update(id, {version, state:"active"})`. */
|
|
58
|
+
enable(memberId: string, input: {
|
|
59
|
+
version: number;
|
|
60
|
+
}, options?: CallOptions): Promise<MemberSaved>;
|
|
61
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// Local membership: who may use the network by the venue's own rule (contract 6.8).
|
|
2
|
+
// Organization-wide resource at /integration/v1/members; the scopes members:read / members:write are
|
|
3
|
+
// organization scopes (an owner issues them).
|
|
4
|
+
//
|
|
5
|
+
// Principles:
|
|
6
|
+
// - the stable identity is issuer + subject. There is no way to name a member by e-mail, phone number or a
|
|
7
|
+
// Social Layer group claim, and an identity provider's membership facts cannot be forged from here;
|
|
8
|
+
// - changing eligibility and ending live sessions are different operations with different answers. Disabling a
|
|
9
|
+
// member does NOT end a session; call `sessions.revoke` for that and read its own answer.
|
|
10
|
+
import { randomUUID } from "node:crypto";
|
|
11
|
+
import { ProtocolError } from "./errors.js";
|
|
12
|
+
import { asPage, walk } from "./paging.js";
|
|
13
|
+
import { BASE, CALL_KEYS, callOf, checkCursor, enc, Resource } from "./resource.js";
|
|
14
|
+
import { bad, idempotencyKeyOf, isObject, limitOf, nonEmptyString, onlyKeys, requireObject, unixSeconds, versionOf } from "./validate.js";
|
|
15
|
+
const PATH = `${BASE}/members`;
|
|
16
|
+
const fold = (s) => s.toLowerCase();
|
|
17
|
+
export class Members extends Resource {
|
|
18
|
+
/**
|
|
19
|
+
* Make `issuer`+`subject` eligible. 409 `member_exists` if the identity already has an entry;
|
|
20
|
+
* 409 `local_membership_disabled` if the site has no enabled local-membership rule (nothing is changed).
|
|
21
|
+
*/
|
|
22
|
+
async create(input, options = {}) {
|
|
23
|
+
requireObject(input, "member");
|
|
24
|
+
onlyKeys(input, ["issuer", "subject", "expiresAt"], "members.create()");
|
|
25
|
+
requireObject(options, "options");
|
|
26
|
+
onlyKeys(options, ["idempotencyKey", ...CALL_KEYS], "members.create()");
|
|
27
|
+
const body = { issuer: nonEmptyString(input.issuer, "issuer"), subject: nonEmptyString(input.subject, "subject", 256) };
|
|
28
|
+
if (input.expiresAt !== undefined && input.expiresAt !== null)
|
|
29
|
+
body.expires_at = unixSeconds(input.expiresAt, "expiresAt");
|
|
30
|
+
const key = idempotencyKeyOf(options.idempotencyKey) ?? randomUUID();
|
|
31
|
+
return (await this.t.request({ method: "POST", path: PATH, body, idempotencyKey: key, ...callOf(options) })).data;
|
|
32
|
+
}
|
|
33
|
+
async get(memberId, options = {}) {
|
|
34
|
+
onlyKeys(options, CALL_KEYS, "members.get()");
|
|
35
|
+
return this.getJson(`${PATH}/${enc(nonEmptyString(memberId, "memberId"))}`, {}, callOf(options));
|
|
36
|
+
}
|
|
37
|
+
async list(options = {}) {
|
|
38
|
+
onlyKeys(options, ["limit", "cursor", "issuer", "subject", "state", ...CALL_KEYS], "members.list()");
|
|
39
|
+
if (options.subject !== undefined && options.issuer === undefined)
|
|
40
|
+
bad("subject needs issuer: a subject alone can collide between identity providers");
|
|
41
|
+
return asPage(await this.getJson(PATH, { limit: limitOf(options.limit), cursor: checkCursor(options.cursor), issuer: options.issuer, subject: options.subject, state: options.state }, callOf(options)));
|
|
42
|
+
}
|
|
43
|
+
iterate(options = {}) {
|
|
44
|
+
const { maxPages, ...rest } = options;
|
|
45
|
+
return walk((cursor) => this.list({ ...rest, cursor }), { maxPages });
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Convenience for `list({issuer, subject})`: the entry for one identity, or null. Both fields are required.
|
|
49
|
+
* The cloud folds case in the member key, so the comparison does too.
|
|
50
|
+
*/
|
|
51
|
+
async find(key, options = {}) {
|
|
52
|
+
requireObject(key, "key");
|
|
53
|
+
onlyKeys(key, ["issuer", "subject"], "members.find()");
|
|
54
|
+
const issuer = nonEmptyString(key.issuer, "issuer");
|
|
55
|
+
const subject = nonEmptyString(key.subject, "subject", 256);
|
|
56
|
+
const page = await this.list({ issuer, subject, limit: 2, ...callOf(options) });
|
|
57
|
+
// Trust the key, not the filter: only matches count, and two of them is a fault, not a coin toss.
|
|
58
|
+
const hits = page.items.filter((m) => isObject(m) && fold(String(m.issuer)) === fold(issuer) && fold(String(m.subject)) === fold(subject));
|
|
59
|
+
if (hits.length > 1)
|
|
60
|
+
throw new ProtocolError("the cloud returned more than one member for one issuer+subject");
|
|
61
|
+
return hits[0] ?? null;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Change expiry and/or state. PATCH is protected by `version`, not by an idempotency key, and an automatic retry
|
|
65
|
+
* happens only for 429. After a timeout or 5xx the error says `outcomeUnknown`: read the member, then decide.
|
|
66
|
+
* This changes ELIGIBILITY only; it does not end sessions that are already online (see `sessions.revoke`).
|
|
67
|
+
*/
|
|
68
|
+
async update(memberId, input, options = {}) {
|
|
69
|
+
requireObject(input, "changes");
|
|
70
|
+
onlyKeys(input, ["version", "expiresAt", "state"], "members.update()");
|
|
71
|
+
onlyKeys(options, CALL_KEYS, "members.update()");
|
|
72
|
+
const body = { version: versionOf(input.version) };
|
|
73
|
+
if (input.expiresAt !== undefined)
|
|
74
|
+
body.expires_at = input.expiresAt === null ? null : unixSeconds(input.expiresAt, "expiresAt");
|
|
75
|
+
if (input.state !== undefined) {
|
|
76
|
+
if (input.state !== "active" && input.state !== "disabled")
|
|
77
|
+
bad('state can be set to "active" or "disabled" only (expiry is a date, not a state you set)');
|
|
78
|
+
body.state = input.state;
|
|
79
|
+
}
|
|
80
|
+
if (Object.keys(body).length === 1)
|
|
81
|
+
bad("nothing to change: give expiresAt and/or state");
|
|
82
|
+
return (await this.t.request({ method: "PATCH", path: `${PATH}/${enc(nonEmptyString(memberId, "memberId"))}`, body, ...callOf(options) })).data;
|
|
83
|
+
}
|
|
84
|
+
/** Convenience for `update(id, {version, state:"disabled"})`. Live sessions are untouched until `sessions.revoke`. */
|
|
85
|
+
disable(memberId, input, options = {}) {
|
|
86
|
+
requireObject(input, "input");
|
|
87
|
+
onlyKeys(input, ["version"], "members.disable()");
|
|
88
|
+
return this.update(memberId, { version: input.version, state: "disabled" }, options);
|
|
89
|
+
}
|
|
90
|
+
/** Convenience for `update(id, {version, state:"active"})`. */
|
|
91
|
+
enable(memberId, input, options = {}) {
|
|
92
|
+
requireObject(input, "input");
|
|
93
|
+
onlyKeys(input, ["version"], "members.enable()");
|
|
94
|
+
return this.update(memberId, { version: input.version, state: "active" }, options);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"module"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Page } from "./types.js";
|
|
2
|
+
export interface IterateOptions {
|
|
3
|
+
/** Stop with an error after this many pages (a guard against a misbehaving server). Default 1000. */
|
|
4
|
+
maxPages?: number;
|
|
5
|
+
}
|
|
6
|
+
/** A page must have an items array; a missing next_cursor is read as the last page. */
|
|
7
|
+
export declare function asPage<T>(data: unknown): Page<T>;
|
|
8
|
+
/**
|
|
9
|
+
* Walks every page. The cursor is opaque and passed back exactly as received. A cursor that comes back unchanged,
|
|
10
|
+
* or more pages than `maxPages`, is a server fault and ends the walk with a ProtocolError instead of looping.
|
|
11
|
+
*/
|
|
12
|
+
export declare function walk<T>(fetchPage: (cursor: string | undefined) => Promise<Page<T>>, opts?: IterateOptions): AsyncGenerator<T, void, undefined>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { ProtocolError } from "./errors.js";
|
|
2
|
+
import { isObject } from "./validate.js";
|
|
3
|
+
/** A page must have an items array; a missing next_cursor is read as the last page. */
|
|
4
|
+
export function asPage(data) {
|
|
5
|
+
if (!isObject(data) || !Array.isArray(data.items))
|
|
6
|
+
throw new ProtocolError("the cloud returned a list without an `items` array");
|
|
7
|
+
const next = data.next_cursor;
|
|
8
|
+
if (next !== undefined && typeof next !== "string")
|
|
9
|
+
throw new ProtocolError("the cloud returned a non-string next_cursor");
|
|
10
|
+
return { ...data, items: data.items, limit: typeof data.limit === "number" ? data.limit : data.items.length, next_cursor: next ?? "" };
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Walks every page. The cursor is opaque and passed back exactly as received. A cursor that comes back unchanged,
|
|
14
|
+
* or more pages than `maxPages`, is a server fault and ends the walk with a ProtocolError instead of looping.
|
|
15
|
+
*/
|
|
16
|
+
export async function* walk(fetchPage, opts = {}) {
|
|
17
|
+
const maxPages = opts.maxPages ?? 1000;
|
|
18
|
+
let cursor;
|
|
19
|
+
for (let pages = 1;; pages++) {
|
|
20
|
+
const page = await fetchPage(cursor);
|
|
21
|
+
yield* page.items;
|
|
22
|
+
const next = page.next_cursor;
|
|
23
|
+
if (next === "")
|
|
24
|
+
return;
|
|
25
|
+
if (next === cursor)
|
|
26
|
+
throw new ProtocolError("the cloud returned the same page cursor again; stopping instead of looping");
|
|
27
|
+
if (pages >= maxPages)
|
|
28
|
+
throw new ProtocolError(`stopped after maxPages=${maxPages} pages and there are more`);
|
|
29
|
+
cursor = next;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { type CallOptions, type ClientOptions } from "./transport.js";
|
|
2
|
+
import type { ConsentResult, PersonRef, PresenceList, PresenceIntent } from "./types.js";
|
|
3
|
+
export interface PresenceOptions extends ClientOptions {
|
|
4
|
+
/** The venue site whose token this is. */
|
|
5
|
+
siteId: string;
|
|
6
|
+
/**
|
|
7
|
+
* The site's presence token. A function is called for every request, so a rotated token (the old one stays
|
|
8
|
+
* valid for 24 hours) can be picked up without restarting.
|
|
9
|
+
*/
|
|
10
|
+
token: string | (() => string | Promise<string>);
|
|
11
|
+
}
|
|
12
|
+
export interface UpdateConsentInput {
|
|
13
|
+
/** Exactly one way to name the person: `{ id, issuer? }`, `{ email }` or `{ phone }`. */
|
|
14
|
+
person: PersonRef;
|
|
15
|
+
/**
|
|
16
|
+
* Whether the person agreed to share their presence. There is no default: pass it only when THE PERSON chose it
|
|
17
|
+
* in your own system. `true` extends their login and remembers their device, exactly as if they had tapped
|
|
18
|
+
* "agree" themselves; that is why it must come from them.
|
|
19
|
+
*/
|
|
20
|
+
consent?: boolean;
|
|
21
|
+
/** `chat`, `focus` or `private` (private hides them from the list). */
|
|
22
|
+
intent?: PresenceIntent;
|
|
23
|
+
}
|
|
24
|
+
export declare class PresenceClient {
|
|
25
|
+
private readonly t;
|
|
26
|
+
private readonly site;
|
|
27
|
+
constructor(options: PresenceOptions);
|
|
28
|
+
/**
|
|
29
|
+
* Who is here now and willing to be known. See `PresenceList.note`: an empty list is not an empty room.
|
|
30
|
+
* Asking more often than `cacheMaxAgeSeconds` (60) learns nothing new.
|
|
31
|
+
*/
|
|
32
|
+
list(options?: CallOptions): Promise<PresenceList>;
|
|
33
|
+
/**
|
|
34
|
+
* Change one person's sharing or status. Needs a `write` token. Call it only when the person made the choice
|
|
35
|
+
* themselves in your system. A PUT is retried only on 429; after a timeout or 5xx the error is
|
|
36
|
+
* `outcomeUnknown`: look at the list before repeating.
|
|
37
|
+
*
|
|
38
|
+
* 409 `ambiguous_person` (AmbiguousPersonError) means one e-mail/phone matches two identities: nobody was
|
|
39
|
+
* changed; ask again with one of `candidates` as `{ id, issuer }`.
|
|
40
|
+
*/
|
|
41
|
+
updateConsent(input: UpdateConsentInput, options?: CallOptions): Promise<ConsentResult>;
|
|
42
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// Presence: a thin, faithful wrapper over today's venue-token API (docs/integrations/presence-api.md,
|
|
2
|
+
// GET /v1/sites/{site}/presence and PUT /v1/sites/{site}/presence/people). Its meaning is unchanged.
|
|
3
|
+
//
|
|
4
|
+
// The token here is NOT the integration credential. It is issued per site (scope `read` or `write`) and works for
|
|
5
|
+
// that site only; it belongs on your server, never in a page or a mini-program.
|
|
6
|
+
import { assertServerSide } from "./environment.js";
|
|
7
|
+
import { InvalidArgumentError, ProtocolError } from "./errors.js";
|
|
8
|
+
import { CALL_KEYS, callOf, enc } from "./resource.js";
|
|
9
|
+
import { Transport } from "./transport.js";
|
|
10
|
+
import { PRESENCE_INTENTS } from "./enums.js";
|
|
11
|
+
import { bad, isObject, nonEmptyString, onlyKeys, requireObject } from "./validate.js";
|
|
12
|
+
const NOTE = "An empty list does not mean the room is empty: it holds only people seen in the last 15 minutes who agreed to be known. " +
|
|
13
|
+
"A gateway with observation off, an offline gateway, or nobody consenting give the same empty list.";
|
|
14
|
+
export class PresenceClient {
|
|
15
|
+
t;
|
|
16
|
+
site;
|
|
17
|
+
constructor(options) {
|
|
18
|
+
assertServerSide();
|
|
19
|
+
const o = requireObject(options, "options");
|
|
20
|
+
this.site = nonEmptyString(o.siteId, "siteId", 256);
|
|
21
|
+
const tokenOf = o.token;
|
|
22
|
+
if (typeof tokenOf === "string") {
|
|
23
|
+
if (tokenOf.trim() === "")
|
|
24
|
+
bad("token must be a non-empty string or a function returning one");
|
|
25
|
+
if (tokenOf.startsWith("wci_"))
|
|
26
|
+
bad("that is an integration credential (wci_…), not a presence token: use new WiConnect({ credential }) for it");
|
|
27
|
+
}
|
|
28
|
+
else if (typeof tokenOf !== "function")
|
|
29
|
+
bad("token must be a non-empty string or a function returning one");
|
|
30
|
+
const { baseUrl, timeoutMs, retry, fetch, userAgentSuffix } = o;
|
|
31
|
+
this.t = new Transport({ baseUrl, timeoutMs, retry, fetch, userAgentSuffix }, async () => {
|
|
32
|
+
const v = typeof tokenOf === "function" ? await tokenOf() : tokenOf;
|
|
33
|
+
if (typeof v !== "string" || v.trim() === "")
|
|
34
|
+
throw new InvalidArgumentError("the token function returned an empty value");
|
|
35
|
+
if (v.startsWith("wci_"))
|
|
36
|
+
throw new InvalidArgumentError("the token function returned an integration credential (wci_…): presence takes its own token");
|
|
37
|
+
return v;
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Who is here now and willing to be known. See `PresenceList.note`: an empty list is not an empty room.
|
|
42
|
+
* Asking more often than `cacheMaxAgeSeconds` (60) learns nothing new.
|
|
43
|
+
*/
|
|
44
|
+
async list(options = {}) {
|
|
45
|
+
onlyKeys(options, CALL_KEYS, "presence.list()");
|
|
46
|
+
const r = await this.t.request({ method: "GET", path: `/v1/sites/${enc(this.site)}/presence`, ...callOf(options) });
|
|
47
|
+
if (!isObject(r.data) || !Array.isArray(r.data.items))
|
|
48
|
+
throw new ProtocolError("the cloud returned a presence answer without an `items` array");
|
|
49
|
+
const age = /max-age=(\d+)/i.exec(r.headers.get("cache-control") ?? "")?.[1];
|
|
50
|
+
return {
|
|
51
|
+
items: r.data.items,
|
|
52
|
+
visibleCount: r.data.items.length,
|
|
53
|
+
fetchedAt: Date.now(),
|
|
54
|
+
...(age !== undefined ? { cacheMaxAgeSeconds: Number(age) } : {}),
|
|
55
|
+
note: NOTE,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Change one person's sharing or status. Needs a `write` token. Call it only when the person made the choice
|
|
60
|
+
* themselves in your system. A PUT is retried only on 429; after a timeout or 5xx the error is
|
|
61
|
+
* `outcomeUnknown`: look at the list before repeating.
|
|
62
|
+
*
|
|
63
|
+
* 409 `ambiguous_person` (AmbiguousPersonError) means one e-mail/phone matches two identities: nobody was
|
|
64
|
+
* changed; ask again with one of `candidates` as `{ id, issuer }`.
|
|
65
|
+
*/
|
|
66
|
+
async updateConsent(input, options = {}) {
|
|
67
|
+
requireObject(input, "input");
|
|
68
|
+
onlyKeys(input, ["person", "consent", "intent"], "presence.updateConsent()");
|
|
69
|
+
onlyKeys(options, CALL_KEYS, "presence.updateConsent()");
|
|
70
|
+
const body = { ...personBody(input.person) };
|
|
71
|
+
if (input.consent !== undefined) {
|
|
72
|
+
if (typeof input.consent !== "boolean")
|
|
73
|
+
bad("consent must be exactly true or false, chosen by the person (no default, no coercion)");
|
|
74
|
+
body.consent = input.consent;
|
|
75
|
+
}
|
|
76
|
+
if (input.intent !== undefined) {
|
|
77
|
+
if (!PRESENCE_INTENTS.includes(input.intent))
|
|
78
|
+
bad(`intent must be one of ${PRESENCE_INTENTS.join(", ")}`);
|
|
79
|
+
body.intent = input.intent;
|
|
80
|
+
}
|
|
81
|
+
if (body.consent === undefined && body.intent === undefined)
|
|
82
|
+
bad("give consent and/or intent: there is nothing to change otherwise");
|
|
83
|
+
const r = await this.t.request({ method: "PUT", path: `/v1/sites/${enc(this.site)}/presence/people`, body, ...callOf(options) });
|
|
84
|
+
if (!isObject(r.data))
|
|
85
|
+
throw new ProtocolError("the cloud returned an unexpected consent answer");
|
|
86
|
+
return r.data;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function personBody(person) {
|
|
90
|
+
if (!isObject(person))
|
|
91
|
+
bad("person must be { id, issuer? }, { email } or { phone }");
|
|
92
|
+
onlyKeys(person, ["id", "issuer", "email", "phone"], "person");
|
|
93
|
+
const named = ["id", "email", "phone"].filter((k) => person[k] !== undefined);
|
|
94
|
+
if (named.length !== 1)
|
|
95
|
+
bad("name the person by exactly one of id, email or phone");
|
|
96
|
+
const key = named[0];
|
|
97
|
+
const out = { [key]: nonEmptyString(person[key], key) };
|
|
98
|
+
if (person.issuer !== undefined) {
|
|
99
|
+
if (key !== "id")
|
|
100
|
+
bad("issuer goes with id only");
|
|
101
|
+
out.issuer = nonEmptyString(person.issuer, "issuer");
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { CallOptions, Transport } from "./transport.js";
|
|
2
|
+
export declare const enc: typeof encodeURIComponent;
|
|
3
|
+
export declare const BASE = "/integration/v1";
|
|
4
|
+
export declare const CALL_KEYS: readonly ["signal", "timeoutMs"];
|
|
5
|
+
export interface ListOptions extends CallOptions {
|
|
6
|
+
/** 1 to 200; default 50. */
|
|
7
|
+
limit?: number;
|
|
8
|
+
/** The `next_cursor` of the previous page, passed back untouched. */
|
|
9
|
+
cursor?: string;
|
|
10
|
+
}
|
|
11
|
+
export declare function callOf(o: object): CallOptions;
|
|
12
|
+
export declare function checkCursor(v: unknown): string | undefined;
|
|
13
|
+
export declare class Resource {
|
|
14
|
+
protected readonly t: Transport;
|
|
15
|
+
constructor(t: Transport);
|
|
16
|
+
protected getJson<T>(path: string, query: Record<string, string | number | undefined>, o: CallOptions): Promise<T>;
|
|
17
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { bad } from "./validate.js";
|
|
2
|
+
export const enc = encodeURIComponent;
|
|
3
|
+
export const BASE = "/integration/v1";
|
|
4
|
+
export const CALL_KEYS = ["signal", "timeoutMs"];
|
|
5
|
+
export function callOf(o) {
|
|
6
|
+
const r = o;
|
|
7
|
+
return { signal: r.signal, timeoutMs: r.timeoutMs };
|
|
8
|
+
}
|
|
9
|
+
export function checkCursor(v) {
|
|
10
|
+
if (v === undefined || v === "")
|
|
11
|
+
return undefined;
|
|
12
|
+
if (typeof v !== "string")
|
|
13
|
+
bad("cursor must be the string the cloud gave you");
|
|
14
|
+
return v;
|
|
15
|
+
}
|
|
16
|
+
export class Resource {
|
|
17
|
+
t;
|
|
18
|
+
constructor(t) {
|
|
19
|
+
this.t = t;
|
|
20
|
+
}
|
|
21
|
+
async getJson(path, query, o) {
|
|
22
|
+
return (await this.t.request({ method: "GET", path, query, ...o })).data;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -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
|
+
}
|