@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
package/CHANGELOG.md ADDED
@@ -0,0 +1,43 @@
1
+ # Changelog: @wiconnect/sdk
2
+
3
+ The server-side SDK for your backend (Node.js 22 or newer). It follows [Semantic Versioning](https://semver.org).
4
+ **Version 1.x serves the API under `/integration/v1`.** Inside one API version the cloud only adds: new fields, new
5
+ enum values, new operations. The SDK keeps unknown fields and tolerates unknown values, so a cloud release never
6
+ needs an SDK upgrade to keep working. A change that could break your code ships as 2.0.0 with a migration note below,
7
+ and is announced at least six months before the old behaviour is removed.
8
+
9
+ ## 1.0.0-rc.1 (not published yet)
10
+
11
+ First release candidate. It becomes 1.0.0 after a customer has run it in their own environment.
12
+
13
+ ### Added
14
+
15
+ - `WiConnect`: `credential()`, `sites`, `sessions` (`list`, `iterate`, `get`, `revoke`), `members` (`list`, `iterate`,
16
+ `get`, `find`, `create`, `update`, `disable`), `capabilities`, `diagnostics`.
17
+ - `PresenceClient`: read the roster and set a person's sharing and status, with the venue's presence token.
18
+ - Typed errors with `requestId`; `outcomeUnknown` on a write whose result could not be read; automatic retry only where
19
+ it is safe (reads, and writes with an idempotency key).
20
+ - ESM and CommonJS builds, TypeScript declarations, no runtime dependencies.
21
+
22
+ ### Fixed
23
+
24
+ - `outcomeUnknown` stays `true` for the whole call once any attempt of a write may have run. Before, a write that got
25
+ a 500 and then a 401 on the retry ended with `outcomeUnknown: false`, which invited a duplicate write.
26
+ - A `token` function that is still pending is now covered by the call: cancelling through `signal` raises
27
+ `AbortedError` and the total `timeoutMs` raises `TimeoutError`, both with `outcomeUnknown: false`. Before, the call
28
+ waited for the token and then sent the request anyway.
29
+
30
+ ### Compatibility
31
+
32
+ | This SDK | API | Node.js |
33
+ |---|---|---|
34
+ | 1.x | `/integration/v1` | 22 and 24 |
35
+
36
+ ### Upgrading
37
+
38
+ Within 1.x: raise the version and run your tests. There are no breaking changes to look for.
39
+
40
+ ### Migration
41
+
42
+ None: there is no 2.x yet. A 2.0.0 entry here will list every change that needs your attention, with before and after
43
+ code.
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # @wiconnect/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ WiConnect 的**服务端** TypeScript SDK:给你们自己的后端查在场、管本地会员资格、查询与撤销网络会话、读取执行能力与诊断。
4
+
5
+ > **版本 1.0.0-rc.1(发行候选)。** 云端已开放凭据自检、在场、会员资格、会话、能力与诊断、站点只读;本包已用打包后的版本对真实的 WiConnect 服务做过端到端测试,还没有在客户自己的环境里验证过,所以还不是 1.0.0。实时状态见[支持情况](../../docs/integrations/sdk/README.md#支持情况与限制)。已发布在 npm:`npm install @wiconnect/sdk@rc`,许可证 MIT。版本规则与怎么拿到:[版本与发行](../../docs/integrations/sdk/releases.md);变更记录:[CHANGELOG.md](CHANGELOG.md)。
6
+
7
+ ## 只能在服务端用
8
+
9
+ **Server-side only.** Never bundle this package into a browser page or a mini-program: the credential would be readable by everyone who opens it.
10
+
11
+ 接入凭据(`wci_…`)和场地在场令牌都是**服务端秘密**,不要放进页面、前端 bundle 或小程序代码;在浏览器里初始化会直接抛错。前端登录页用另一个包 [`@wiconnect/login`](../browser/README.md),页面调用你们自己的后端,由后端用本包。
12
+
13
+ Node.js ≥ 22;ESM 与 CJS;零运行时依赖,只用全局 `fetch`。
14
+
15
+ ## 快速开始
16
+
17
+ ```ts
18
+ import { WiConnect } from "@wiconnect/sdk";
19
+
20
+ const wc = new WiConnect({
21
+ baseUrl: "https://cloud.example.com",
22
+ credential: process.env.WICONNECT_CREDENTIAL!, // wci_…,来自环境变量,不要写进代码
23
+ });
24
+
25
+ const me = await wc.credential(); // 自检:绑定哪些场地、有哪些范围、何时到期
26
+ ```
27
+
28
+ 在场、会员资格、会话撤销的完整例子和预期输出:[快速开始:后端](../../docs/integrations/sdk/quickstart-backend.md);全部方法和错误:[服务端 SDK 参考](../../docs/integrations/sdk/reference/server-sdk.md)、[错误参考](../../docs/integrations/sdk/reference/errors.md)。
29
+
30
+ ## 开发
31
+
32
+ ```sh
33
+ npm install
34
+ npm test # 构建 + 全部测试(替身服务,不连真实云端)
35
+ npm run pack:check # npm pack,在干净临时工程里安装并运行 ESM/CJS 冒烟脚本和类型检查
36
+ ```
@@ -0,0 +1,79 @@
1
+ import { Members } from "./members.js";
2
+ import { type IterateOptions } from "./paging.js";
3
+ import { PresenceClient, type PresenceOptions } from "./presence.js";
4
+ import { Resource, type ListOptions } from "./resource.js";
5
+ import { type CallOptions, type ClientOptions } from "./transport.js";
6
+ import type { Capabilities, Credential, Diagnostics, GrantState, Page, Session, Site } from "./types.js";
7
+ export type { ListOptions } from "./resource.js";
8
+ export interface WiConnectOptions extends ClientOptions {
9
+ /** The integration credential (`wci_…`) issued by an owner or administrator. Keep it on your server. */
10
+ credential: string;
11
+ }
12
+ /**
13
+ * The client for your own backend. One instance per credential; it is safe to share between requests.
14
+ *
15
+ * ```ts
16
+ * const wc = new WiConnect({ baseUrl: "https://cloud.example.com", credential: process.env.WICONNECT_CREDENTIAL! });
17
+ * const { items } = await wc.sessions.list("my-site");
18
+ * ```
19
+ */
20
+ export declare class WiConnect {
21
+ readonly sites: Sites;
22
+ readonly sessions: Sessions;
23
+ readonly members: Members;
24
+ readonly capabilities: CapabilitiesApi;
25
+ readonly diagnostics: DiagnosticsApi;
26
+ private readonly t;
27
+ private readonly shared;
28
+ constructor(options: WiConnectOptions);
29
+ /** What this credential is and may do: organization, bound sites, scopes, expiry. Never returns the secret. */
30
+ credential(options?: CallOptions): Promise<Credential>;
31
+ /**
32
+ * A presence client that shares this client's base URL and transport settings. The presence token is a
33
+ * different secret (issued per site, `read` or `write`), so it is given separately.
34
+ */
35
+ presence(options: Pick<PresenceOptions, "siteId" | "token">): PresenceClient;
36
+ }
37
+ export declare class Sites extends Resource {
38
+ list(options?: ListOptions): Promise<Page<Site>>;
39
+ iterate(options?: ListOptions & IterateOptions): AsyncGenerator<Site, void, undefined>;
40
+ get(siteId: string, options?: CallOptions): Promise<Site>;
41
+ }
42
+ export interface ListSessionsOptions extends ListOptions {
43
+ /** The cloud's grant state. Unknown values are sent as given. */
44
+ grantState?: GrantState;
45
+ /** With `subject`: one identity. */
46
+ issuer?: string;
47
+ subject?: string;
48
+ }
49
+ export interface RevokeOptions extends CallOptions {
50
+ /** Refuse, and revoke nothing, when the executor cannot disconnect at once (409 capability_unsupported). */
51
+ requireImmediate?: boolean;
52
+ /** Kept in the audit record. No personal data. */
53
+ reason?: string;
54
+ /** Repeat the same key to repeat a request safely. Default: a fresh key per call, reused across its retries. */
55
+ idempotencyKey?: string;
56
+ }
57
+ export declare class Sessions extends Resource {
58
+ /** A page of the site's network sessions, newest first. */
59
+ list(siteId: string, options?: ListSessionsOptions): Promise<Page<Session>>;
60
+ /** Every session of the site, page by page. */
61
+ iterate(siteId: string, options?: ListSessionsOptions & IterateOptions): AsyncGenerator<Session, void, undefined>;
62
+ /** One session with its layered state. */
63
+ get(id: string, options?: CallOptions): Promise<Session>;
64
+ /**
65
+ * Ask for the end of a session. Device-wide, as the cloud does it. The answer is 202 and says what is KNOWN:
66
+ * `revocation.state` is `pending` until the executor confirms, and `pending` is not "disconnected". Poll
67
+ * `sessions.get` for `confirmed`. `unconfirmed_expired` is a timeout, not a confirmation.
68
+ * Safe to repeat: every automatic retry carries the same Idempotency-Key, so it is never carried out twice.
69
+ */
70
+ revoke(id: string, options?: RevokeOptions): Promise<Session>;
71
+ }
72
+ export declare class CapabilitiesApi extends Resource {
73
+ /** What the site's executor can and cannot do. Unreported or stale facts are `unknown`, never `supported`. */
74
+ get(siteId: string, options?: CallOptions): Promise<Capabilities>;
75
+ }
76
+ export declare class DiagnosticsApi extends Resource {
77
+ /** Where the chain from configuration to execution stands. `observed.wan` is `unknown` in the first release. */
78
+ get(siteId: string, options?: CallOptions): Promise<Diagnostics>;
79
+ }
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DiagnosticsApi = exports.CapabilitiesApi = exports.Sessions = exports.Sites = exports.WiConnect = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const environment_js_1 = require("./environment.js");
6
+ const errors_js_1 = require("./errors.js");
7
+ const members_js_1 = require("./members.js");
8
+ const paging_js_1 = require("./paging.js");
9
+ const presence_js_1 = require("./presence.js");
10
+ const resource_js_1 = require("./resource.js");
11
+ const transport_js_1 = require("./transport.js");
12
+ const validate_js_1 = require("./validate.js");
13
+ /**
14
+ * The client for your own backend. One instance per credential; it is safe to share between requests.
15
+ *
16
+ * ```ts
17
+ * const wc = new WiConnect({ baseUrl: "https://cloud.example.com", credential: process.env.WICONNECT_CREDENTIAL! });
18
+ * const { items } = await wc.sessions.list("my-site");
19
+ * ```
20
+ */
21
+ class WiConnect {
22
+ sites;
23
+ sessions;
24
+ members;
25
+ capabilities;
26
+ diagnostics;
27
+ t;
28
+ shared;
29
+ constructor(options) {
30
+ (0, environment_js_1.assertServerSide)();
31
+ const o = (0, validate_js_1.requireObject)(options, "options");
32
+ const credential = o.credential;
33
+ if (typeof credential !== "string" || !credential.startsWith("wci_") || credential.length < 8) {
34
+ throw new errors_js_1.InvalidArgumentError("credential must be an integration credential (it starts with wci_). A venue presence token is not one: pass it to PresenceClient.");
35
+ }
36
+ const { baseUrl, timeoutMs, retry, fetch, userAgentSuffix } = o;
37
+ this.shared = { baseUrl, timeoutMs, retry, fetch, userAgentSuffix };
38
+ this.t = new transport_js_1.Transport(this.shared, () => credential);
39
+ this.sites = new Sites(this.t);
40
+ this.sessions = new Sessions(this.t);
41
+ this.members = new members_js_1.Members(this.t);
42
+ this.capabilities = new CapabilitiesApi(this.t);
43
+ this.diagnostics = new DiagnosticsApi(this.t);
44
+ }
45
+ /** What this credential is and may do: organization, bound sites, scopes, expiry. Never returns the secret. */
46
+ async credential(options = {}) {
47
+ (0, validate_js_1.onlyKeys)(options, resource_js_1.CALL_KEYS, "credential()");
48
+ return (await this.t.request({ method: "GET", path: `${resource_js_1.BASE}/credential`, ...(0, resource_js_1.callOf)(options) })).data;
49
+ }
50
+ /**
51
+ * A presence client that shares this client's base URL and transport settings. The presence token is a
52
+ * different secret (issued per site, `read` or `write`), so it is given separately.
53
+ */
54
+ presence(options) {
55
+ return new presence_js_1.PresenceClient({ ...this.shared, ...options });
56
+ }
57
+ }
58
+ exports.WiConnect = WiConnect;
59
+ class Sites extends resource_js_1.Resource {
60
+ async list(options = {}) {
61
+ (0, validate_js_1.onlyKeys)(options, ["limit", "cursor", ...resource_js_1.CALL_KEYS], "sites.list()");
62
+ return (0, paging_js_1.asPage)(await this.getJson(`${resource_js_1.BASE}/sites`, { limit: (0, validate_js_1.limitOf)(options.limit), cursor: (0, resource_js_1.checkCursor)(options.cursor) }, (0, resource_js_1.callOf)(options)));
63
+ }
64
+ iterate(options = {}) {
65
+ const { maxPages, ...rest } = options;
66
+ return (0, paging_js_1.walk)((cursor) => this.list({ ...rest, cursor }), { maxPages });
67
+ }
68
+ async get(siteId, options = {}) {
69
+ (0, validate_js_1.onlyKeys)(options, resource_js_1.CALL_KEYS, "sites.get()");
70
+ return this.getJson(`${resource_js_1.BASE}/sites/${(0, resource_js_1.enc)((0, validate_js_1.nonEmptyString)(siteId, "siteId"))}`, {}, (0, resource_js_1.callOf)(options));
71
+ }
72
+ }
73
+ exports.Sites = Sites;
74
+ class Sessions extends resource_js_1.Resource {
75
+ /** A page of the site's network sessions, newest first. */
76
+ async list(siteId, options = {}) {
77
+ (0, validate_js_1.onlyKeys)(options, ["limit", "cursor", "grantState", "issuer", "subject", ...resource_js_1.CALL_KEYS], "sessions.list()");
78
+ return (0, paging_js_1.asPage)(await this.getJson(`${resource_js_1.BASE}/sites/${(0, resource_js_1.enc)((0, validate_js_1.nonEmptyString)(siteId, "siteId"))}/sessions`, { limit: (0, validate_js_1.limitOf)(options.limit), cursor: (0, resource_js_1.checkCursor)(options.cursor), grant_state: options.grantState, issuer: options.issuer, subject: options.subject }, (0, resource_js_1.callOf)(options)));
79
+ }
80
+ /** Every session of the site, page by page. */
81
+ iterate(siteId, options = {}) {
82
+ const { maxPages, ...rest } = options;
83
+ return (0, paging_js_1.walk)((cursor) => this.list(siteId, { ...rest, cursor }), { maxPages });
84
+ }
85
+ /** One session with its layered state. */
86
+ async get(id, options = {}) {
87
+ (0, validate_js_1.onlyKeys)(options, resource_js_1.CALL_KEYS, "sessions.get()");
88
+ return this.getJson(`${resource_js_1.BASE}/sessions/${(0, resource_js_1.enc)((0, validate_js_1.nonEmptyString)(id, "id"))}`, {}, (0, resource_js_1.callOf)(options));
89
+ }
90
+ /**
91
+ * Ask for the end of a session. Device-wide, as the cloud does it. The answer is 202 and says what is KNOWN:
92
+ * `revocation.state` is `pending` until the executor confirms, and `pending` is not "disconnected". Poll
93
+ * `sessions.get` for `confirmed`. `unconfirmed_expired` is a timeout, not a confirmation.
94
+ * Safe to repeat: every automatic retry carries the same Idempotency-Key, so it is never carried out twice.
95
+ */
96
+ async revoke(id, options = {}) {
97
+ (0, validate_js_1.requireObject)(options, "options");
98
+ (0, validate_js_1.onlyKeys)(options, ["requireImmediate", "reason", "idempotencyKey", ...resource_js_1.CALL_KEYS], "sessions.revoke()");
99
+ const key = (0, validate_js_1.idempotencyKeyOf)(options.idempotencyKey) ?? (0, node_crypto_1.randomUUID)();
100
+ let body;
101
+ if (options.requireImmediate !== undefined) {
102
+ if (typeof options.requireImmediate !== "boolean")
103
+ (0, validate_js_1.bad)("requireImmediate must be true or false");
104
+ body = { require_immediate: options.requireImmediate };
105
+ }
106
+ if (options.reason !== undefined)
107
+ body = { ...body, reason: (0, validate_js_1.nonEmptyString)(options.reason, "reason", 200) };
108
+ const path = `${resource_js_1.BASE}/sessions/${(0, resource_js_1.enc)((0, validate_js_1.nonEmptyString)(id, "id"))}/revoke`;
109
+ return (await this.t.request({ method: "POST", path, body, idempotencyKey: key, ...(0, resource_js_1.callOf)(options) })).data;
110
+ }
111
+ }
112
+ exports.Sessions = Sessions;
113
+ class CapabilitiesApi extends resource_js_1.Resource {
114
+ /** What the site's executor can and cannot do. Unreported or stale facts are `unknown`, never `supported`. */
115
+ async get(siteId, options = {}) {
116
+ (0, validate_js_1.onlyKeys)(options, resource_js_1.CALL_KEYS, "capabilities.get()");
117
+ return this.getJson(`${resource_js_1.BASE}/sites/${(0, resource_js_1.enc)((0, validate_js_1.nonEmptyString)(siteId, "siteId"))}/capabilities`, {}, (0, resource_js_1.callOf)(options));
118
+ }
119
+ }
120
+ exports.CapabilitiesApi = CapabilitiesApi;
121
+ class DiagnosticsApi extends resource_js_1.Resource {
122
+ /** Where the chain from configuration to execution stands. `observed.wan` is `unknown` in the first release. */
123
+ async get(siteId, options = {}) {
124
+ (0, validate_js_1.onlyKeys)(options, resource_js_1.CALL_KEYS, "diagnostics.get()");
125
+ return this.getJson(`${resource_js_1.BASE}/sites/${(0, resource_js_1.enc)((0, validate_js_1.nonEmptyString)(siteId, "siteId"))}/diagnostics`, {}, (0, resource_js_1.callOf)(options));
126
+ }
127
+ }
128
+ exports.DiagnosticsApi = DiagnosticsApi;
@@ -0,0 +1,53 @@
1
+ export declare const CONTRACT: {
2
+ readonly enums: {
3
+ readonly GrantState: string[];
4
+ readonly Scope: string[];
5
+ readonly MemberState: string[];
6
+ readonly MemberWritableState: string[];
7
+ readonly EnforcerKind: string[];
8
+ readonly AuthorizedState: string[];
9
+ readonly EndedReason: string[];
10
+ readonly AppliedState: string[];
11
+ readonly AppliedBy: string[];
12
+ readonly PresenceState: string[];
13
+ readonly PresenceSource: string[];
14
+ readonly WanState: string[];
15
+ readonly WanSource: string[];
16
+ readonly RevocationState: string[];
17
+ readonly RevocationConfirmedBy: string[];
18
+ readonly DisconnectOutcome: string[];
19
+ readonly CapabilityState: string[];
20
+ readonly CapabilitiesEnforcer: string[];
21
+ readonly DiagnosticsEnforcerState: string[];
22
+ readonly CredentialState: string[];
23
+ };
24
+ readonly properties: {
25
+ readonly Session: string[];
26
+ readonly SessionState: string[];
27
+ readonly Revocation: string[];
28
+ readonly Capability: string[];
29
+ readonly Capabilities: string[];
30
+ readonly Diagnostics: string[];
31
+ readonly Site: string[];
32
+ readonly Credential: string[];
33
+ readonly SessionPage: string[];
34
+ readonly Member: string[];
35
+ readonly MemberSaved: string[];
36
+ readonly MemberCreate: readonly ["issuer", "subject", "expires_at"];
37
+ readonly MemberUpdate: readonly ["version", "state", "expires_at"];
38
+ readonly RevokeRequest: readonly ["require_immediate", "reason"];
39
+ };
40
+ /** The operations this SDK calls: all first-release (`x-wc-release: first`) operations of the frozen draft. */
41
+ readonly operations: Record<string, {
42
+ method: string;
43
+ path: string;
44
+ scope: string;
45
+ }>;
46
+ readonly limits: {
47
+ readonly pageDefault: 50;
48
+ readonly pageMax: 200;
49
+ readonly idempotencyKeyMax: 64;
50
+ readonly defaultTimeoutMs: 15000;
51
+ readonly maxRetries: 3;
52
+ };
53
+ };
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CONTRACT = void 0;
4
+ // Tables that tie the hand-written types to the frozen draft. `satisfies Record<keyof T, 1>` makes the compiler
5
+ // check each key list against its interface; test/contract-drift.test.mjs checks it against the draft YAML.
6
+ const E = require("./enums.js");
7
+ const keys = (o) => Object.keys(o);
8
+ exports.CONTRACT = {
9
+ enums: {
10
+ GrantState: [...E.GRANT_STATES],
11
+ Scope: [...E.SCOPES],
12
+ MemberState: [...E.MEMBER_STATES],
13
+ MemberWritableState: [...E.MEMBER_WRITABLE_STATES],
14
+ EnforcerKind: [...E.ENFORCER_KINDS],
15
+ AuthorizedState: [...E.AUTHORIZED_STATES],
16
+ EndedReason: [...E.ENDED_REASONS],
17
+ AppliedState: [...E.APPLIED_STATES],
18
+ AppliedBy: [...E.APPLIED_BY],
19
+ PresenceState: [...E.PRESENCE_STATES],
20
+ PresenceSource: [...E.PRESENCE_SOURCES],
21
+ WanState: [...E.WAN_STATES],
22
+ WanSource: [...E.WAN_SOURCES],
23
+ RevocationState: [...E.REVOCATION_STATES],
24
+ RevocationConfirmedBy: [...E.REVOCATION_CONFIRMED_BY],
25
+ DisconnectOutcome: [...E.DISCONNECT_OUTCOMES],
26
+ CapabilityState: [...E.CAPABILITY_STATES],
27
+ CapabilitiesEnforcer: [...E.CAPABILITIES_ENFORCER_KINDS],
28
+ DiagnosticsEnforcerState: [...E.DIAGNOSTICS_ENFORCER_STATES],
29
+ CredentialState: [...E.CREDENTIAL_STATES],
30
+ },
31
+ properties: {
32
+ Session: keys({
33
+ id: 1, site_id: 1, subject: 1, device: 1, class: 1, synthetic: 1, issued_at: 1, expires_at: 1,
34
+ enforcer: 1, grant_state: 1, state: 1, revocation: 1,
35
+ }),
36
+ SessionState: keys({ saved: 1, authorized: 1, applied: 1, observed: 1 }),
37
+ Revocation: keys({
38
+ state: 1, requested_at: 1, confirmed_at: 1, confirmed_by: 1, latest_effect_at: 1, disconnect: 1, request_id: 1,
39
+ }),
40
+ Capability: keys({ key: 1, state: 1, value: 1, reason: 1, source: 1, reported_at: 1 }),
41
+ Capabilities: keys({ site_id: 1, enforcer: 1, items: 1 }),
42
+ Diagnostics: keys({
43
+ site_id: 1, generated_at: 1, enforcer: 1, config: 1, native_setup: 1, last_identity_test: 1, observed: 1,
44
+ }),
45
+ Site: keys({
46
+ id: 1, slug: 1, display_name: 1, network_name: 1, landing_url: 1, theme: 1, timezone: 1, contact: 1, consent: 1,
47
+ has_logo: 1, disabled: 1, grant_scope: 1, created: 1, version: 1,
48
+ }),
49
+ Credential: keys({
50
+ id: 1, name: 1, organization: 1, sites: 1, scopes: 1, org_wide: 1, state: 1, created_at: 1, expires_at: 1,
51
+ last_used_at: 1, issued_by: 1, previous_secret_ends_at: 1, version: 1,
52
+ }),
53
+ SessionPage: keys({ items: 1, limit: 1, next_cursor: 1 }),
54
+ Member: keys({ id: 1, issuer: 1, subject: 1, state: 1, expires_at: 1, created_at: 1, updated_at: 1, version: 1 }),
55
+ MemberSaved: keys({ member: 1, saved: 1, sessions: 1 }),
56
+ MemberCreate: ["issuer", "subject", "expires_at"],
57
+ MemberUpdate: ["version", "state", "expires_at"],
58
+ RevokeRequest: ["require_immediate", "reason"],
59
+ },
60
+ /** The operations this SDK calls: all first-release (`x-wc-release: first`) operations of the frozen draft. */
61
+ operations: {
62
+ getCredential: { method: "GET", path: "/integration/v1/credential", scope: "any valid credential" },
63
+ listSites: { method: "GET", path: "/integration/v1/sites", scope: "sites:read" },
64
+ getSite: { method: "GET", path: "/integration/v1/sites/{site}", scope: "sites:read" },
65
+ listSessions: { method: "GET", path: "/integration/v1/sites/{site}/sessions", scope: "sessions:read" },
66
+ getSession: { method: "GET", path: "/integration/v1/sessions/{id}", scope: "sessions:read" },
67
+ revokeSession: { method: "POST", path: "/integration/v1/sessions/{id}/revoke", scope: "sessions:revoke" },
68
+ getCapabilities: { method: "GET", path: "/integration/v1/sites/{site}/capabilities", scope: "diagnostics:read" },
69
+ getDiagnostics: { method: "GET", path: "/integration/v1/sites/{site}/diagnostics", scope: "diagnostics:read" },
70
+ listMembers: { method: "GET", path: "/integration/v1/members", scope: "members:read" },
71
+ createMember: { method: "POST", path: "/integration/v1/members", scope: "members:write" },
72
+ getMember: { method: "GET", path: "/integration/v1/members/{id}", scope: "members:read" },
73
+ updateMember: { method: "PATCH", path: "/integration/v1/members/{id}", scope: "members:write" },
74
+ },
75
+ limits: { pageDefault: 50, pageMax: 200, idempotencyKeyMax: 64, defaultTimeoutMs: 15_000, maxRetries: 3 },
76
+ };
@@ -0,0 +1,29 @@
1
+ /** A string union that still accepts values this SDK version has not heard of. */
2
+ export type Open<T extends string> = T | (string & {});
3
+ export declare const GRANT_STATES: readonly ["pending", "applied", "failed", "revoke_pending", "revoked", "expired"];
4
+ /**
5
+ * Scopes of the frozen contract (#1131). The first eight are site scopes; the next four and the two member scopes
6
+ * are organization scopes (issued by an owner only, `org_wide=true`). The first-release server SDK needs
7
+ * sites:read, sessions:read, sessions:revoke, diagnostics:read, members:read and members:write.
8
+ */
9
+ export declare const SCOPES: readonly ["sites:read", "sites:write", "access:read", "access:write", "sessions:read", "sessions:revoke", "diagnostics:read", "identity:test", "identity:read", "identity:write", "identity:activate", "policy:read", "members:read", "members:write"];
10
+ export declare const ENFORCER_KINDS: readonly ["gateway", "native"];
11
+ export declare const CAPABILITIES_ENFORCER_KINDS: readonly ["gateway", "native", "none"];
12
+ export declare const AUTHORIZED_STATES: readonly ["authorized", "ended"];
13
+ export declare const ENDED_REASONS: readonly ["expired", "revoked", "replaced", "failed"];
14
+ export declare const APPLIED_STATES: readonly ["pending", "confirmed", "failed", "unknown"];
15
+ export declare const APPLIED_BY: readonly ["gateway_ack", "native_accounting_start"];
16
+ export declare const PRESENCE_STATES: readonly ["seen", "not_seen", "unknown"];
17
+ export declare const PRESENCE_SOURCES: readonly ["gateway_observation", "native_accounting_interim"];
18
+ export declare const WAN_STATES: readonly ["observed", "not_observed", "unknown"];
19
+ export declare const WAN_SOURCES: readonly ["wan_proof_probe"];
20
+ export declare const REVOCATION_STATES: readonly ["pending", "confirmed", "unconfirmed_expired", "unknown"];
21
+ export declare const REVOCATION_CONFIRMED_BY: readonly ["gateway_ack", "acct_stop", "disconnect_ack"];
22
+ export declare const DISCONNECT_OUTCOMES: readonly ["ack", "nak", "timeout", "not_available"];
23
+ export declare const CAPABILITY_STATES: readonly ["supported", "unsupported", "unknown"];
24
+ export declare const DIAGNOSTICS_ENFORCER_STATES: readonly ["online", "offline", "unknown", "not_installed"];
25
+ export declare const CREDENTIAL_STATES: readonly ["active", "rotating", "revoked", "expired"];
26
+ /** Member states: `expired` is decided by time and never written. */
27
+ export declare const MEMBER_STATES: readonly ["active", "disabled", "expired"];
28
+ export declare const MEMBER_WRITABLE_STATES: readonly ["active", "disabled"];
29
+ export declare const PRESENCE_INTENTS: readonly ["chat", "focus", "private"];
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ // Enumerations from the frozen draft (docs/integrations/sdk/public-api-draft.yaml). Types are derived from
3
+ // these arrays; test/contract-drift.test.mjs compares them with the draft, so they cannot drift quietly.
4
+ // Every public union is open (`Open<…>`): contract 9.1 says clients must tolerate values added later.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.PRESENCE_INTENTS = exports.MEMBER_WRITABLE_STATES = exports.MEMBER_STATES = exports.CREDENTIAL_STATES = exports.DIAGNOSTICS_ENFORCER_STATES = exports.CAPABILITY_STATES = exports.DISCONNECT_OUTCOMES = exports.REVOCATION_CONFIRMED_BY = exports.REVOCATION_STATES = exports.WAN_SOURCES = exports.WAN_STATES = exports.PRESENCE_SOURCES = exports.PRESENCE_STATES = exports.APPLIED_BY = exports.APPLIED_STATES = exports.ENDED_REASONS = exports.AUTHORIZED_STATES = exports.CAPABILITIES_ENFORCER_KINDS = exports.ENFORCER_KINDS = exports.SCOPES = exports.GRANT_STATES = void 0;
7
+ exports.GRANT_STATES = ["pending", "applied", "failed", "revoke_pending", "revoked", "expired"];
8
+ /**
9
+ * Scopes of the frozen contract (#1131). The first eight are site scopes; the next four and the two member scopes
10
+ * are organization scopes (issued by an owner only, `org_wide=true`). The first-release server SDK needs
11
+ * sites:read, sessions:read, sessions:revoke, diagnostics:read, members:read and members:write.
12
+ */
13
+ exports.SCOPES = [
14
+ "sites:read",
15
+ "sites:write",
16
+ "access:read",
17
+ "access:write",
18
+ "sessions:read",
19
+ "sessions:revoke",
20
+ "diagnostics:read",
21
+ "identity:test",
22
+ "identity:read",
23
+ "identity:write",
24
+ "identity:activate",
25
+ "policy:read",
26
+ "members:read",
27
+ "members:write",
28
+ ];
29
+ exports.ENFORCER_KINDS = ["gateway", "native"];
30
+ exports.CAPABILITIES_ENFORCER_KINDS = ["gateway", "native", "none"];
31
+ exports.AUTHORIZED_STATES = ["authorized", "ended"];
32
+ exports.ENDED_REASONS = ["expired", "revoked", "replaced", "failed"];
33
+ exports.APPLIED_STATES = ["pending", "confirmed", "failed", "unknown"];
34
+ exports.APPLIED_BY = ["gateway_ack", "native_accounting_start"];
35
+ exports.PRESENCE_STATES = ["seen", "not_seen", "unknown"];
36
+ exports.PRESENCE_SOURCES = ["gateway_observation", "native_accounting_interim"];
37
+ exports.WAN_STATES = ["observed", "not_observed", "unknown"];
38
+ exports.WAN_SOURCES = ["wan_proof_probe"];
39
+ exports.REVOCATION_STATES = ["pending", "confirmed", "unconfirmed_expired", "unknown"];
40
+ exports.REVOCATION_CONFIRMED_BY = ["gateway_ack", "acct_stop", "disconnect_ack"];
41
+ exports.DISCONNECT_OUTCOMES = ["ack", "nak", "timeout", "not_available"];
42
+ exports.CAPABILITY_STATES = ["supported", "unsupported", "unknown"];
43
+ exports.DIAGNOSTICS_ENFORCER_STATES = ["online", "offline", "unknown", "not_installed"];
44
+ exports.CREDENTIAL_STATES = ["active", "rotating", "revoked", "expired"];
45
+ /** Member states: `expired` is decided by time and never written. */
46
+ exports.MEMBER_STATES = ["active", "disabled", "expired"];
47
+ exports.MEMBER_WRITABLE_STATES = ["active", "disabled"];
48
+ exports.PRESENCE_INTENTS = ["chat", "focus", "private"];
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The integration credential and the venue presence token are server secrets. A browser or a mini-program bundle
3
+ * is readable by everyone who opens the page, so the SDK refuses to start there (contract 9.2).
4
+ * Put your server in between and call it from the page.
5
+ */
6
+ export declare function assertServerSide(): void;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assertServerSide = assertServerSide;
4
+ const errors_js_1 = require("./errors.js");
5
+ /**
6
+ * The integration credential and the venue presence token are server secrets. A browser or a mini-program bundle
7
+ * is readable by everyone who opens the page, so the SDK refuses to start there (contract 9.2).
8
+ * Put your server in between and call it from the page.
9
+ */
10
+ function assertServerSide() {
11
+ const g = globalThis;
12
+ if (typeof g.window !== "undefined" && typeof g.window?.document !== "undefined") {
13
+ throw new errors_js_1.InvalidArgumentError("@wiconnect/sdk holds server-side secrets and must not run in a browser or a mini-program. Call your own backend from the page instead; the browser/mini-program login SDK is a separate package.");
14
+ }
15
+ }
@@ -0,0 +1,99 @@
1
+ import type { AmbiguousCandidate } from "./types.js";
2
+ export interface ErrorFields {
3
+ status?: number;
4
+ code?: string;
5
+ requestId?: string;
6
+ outcomeUnknown?: boolean;
7
+ retryAfterSeconds?: number;
8
+ idempotencyKey?: string;
9
+ attempts?: number;
10
+ }
11
+ /** Base class of every error thrown by this SDK. */
12
+ export declare class WiConnectError extends Error {
13
+ /** HTTP status; undefined when no response was received. */
14
+ status?: number;
15
+ /** Stable machine code from the cloud (`version_conflict`, `rate_limited`, …). Do not parse `message`. */
16
+ code?: string;
17
+ /** The cloud's X-Request-ID: quote it when asking for support. */
18
+ requestId?: string;
19
+ /**
20
+ * True when a WRITE may or may not have happened (timeout, cancel, network loss, 5xx). It is not "failed":
21
+ * re-read before deciding, or repeat a POST with the same `idempotencyKey`. A 429 means it did not run.
22
+ */
23
+ outcomeUnknown: boolean;
24
+ retryAfterSeconds?: number;
25
+ /** The Idempotency-Key of a POST, so the same request can be repeated safely. */
26
+ idempotencyKey?: string;
27
+ /** How many HTTP attempts were made. */
28
+ attempts?: number;
29
+ constructor(message: string, fields?: ErrorFields);
30
+ /** Only plain fields: no cause, no headers. */
31
+ toJSON(): Record<string, unknown>;
32
+ }
33
+ /** The call was refused locally, before anything was sent. */
34
+ export declare class InvalidArgumentError extends WiConnectError {
35
+ }
36
+ /** The cloud answered with an error status. */
37
+ export declare class ApiError extends WiConnectError {
38
+ }
39
+ export declare class BadRequestError extends ApiError {
40
+ }
41
+ /** 400 member_identity_invalid: the issuer/subject cannot form a member identity (empty, over length, not canonical). */
42
+ export declare class MemberIdentityInvalidError extends BadRequestError {
43
+ }
44
+ /** 401 credential_invalid: absent, unknown, expired or revoked (deliberately not told apart). Do not retry. */
45
+ export declare class CredentialInvalidError extends ApiError {
46
+ }
47
+ /** 403: `scope_forbidden`, `site_forbidden` (this API) or `site_required` / `write_scope_required` (presence). */
48
+ export declare class ForbiddenError extends ApiError {
49
+ }
50
+ /** 404 with an API error body: it does not exist, or belongs to another organization (not told apart). */
51
+ export declare class NotFoundError extends ApiError {
52
+ }
53
+ /** 404 without an API error body: this cloud does not have the endpoint at all (an older cloud than this SDK). */
54
+ export declare class EndpointNotAvailableError extends ApiError {
55
+ }
56
+ export declare class ConflictError extends ApiError {
57
+ }
58
+ /** 409 local_membership_disabled: the site has no enabled local-membership rule, so a member entry would do
59
+ * nothing. Nothing was changed. Enable the rule in the console (an administrator's step), then repeat. */
60
+ export declare class LocalMembershipDisabledError extends ConflictError {
61
+ }
62
+ /** 409 member_exists: that issuer+subject already has an entry. Read it and update it instead. */
63
+ export declare class MemberExistsError extends ConflictError {
64
+ }
65
+ /** 409 version_conflict: someone changed it first. Re-read, then decide; do not overwrite blindly. */
66
+ export declare class VersionConflictError extends ConflictError {
67
+ }
68
+ /** 409 ambiguous_person: one e-mail/phone matches two identities. Nobody was changed. Name one candidate. */
69
+ export declare class AmbiguousPersonError extends ConflictError {
70
+ candidates: AmbiguousCandidate[];
71
+ toJSON(): Record<string, unknown>;
72
+ }
73
+ export declare class IdempotencyKeyReuseError extends ApiError {
74
+ }
75
+ export declare class VersionRequiredError extends ApiError {
76
+ }
77
+ /** 429: it did NOT run. `retryAfterSeconds` says when to try again. */
78
+ export declare class RateLimitedError extends ApiError {
79
+ }
80
+ export declare class ServerError extends ApiError {
81
+ }
82
+ /** No usable response arrived. */
83
+ export declare class TransportError extends WiConnectError {
84
+ }
85
+ export declare class NetworkError extends TransportError {
86
+ /** A short, redacted reason such as ECONNRESET. */
87
+ reason?: string;
88
+ toJSON(): Record<string, unknown>;
89
+ }
90
+ export declare class TimeoutError extends TransportError {
91
+ }
92
+ export declare class AbortedError extends TransportError {
93
+ }
94
+ /** The cloud answered 2xx with something that is not the documented shape. */
95
+ export declare class ProtocolError extends WiConnectError {
96
+ }
97
+ export declare function isWiConnectError(e: unknown): e is WiConnectError;
98
+ /** Removes known secrets and anything shaped like an integration credential from text that may be shown. */
99
+ export declare function redact(text: string, secrets: Iterable<string>): string;