@smartcrab/management-client 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.ts ADDED
@@ -0,0 +1,934 @@
1
+ import * as cm from "@smartcrab/contracts-management";
2
+ import type { ManagementClientError } from "./errors.js";
3
+ import type { Result, ResultAsync } from "./result.js";
4
+ import { fail } from "./result.js";
5
+ import type { InputOf, ManagementResponse, RequestSpec, Schema } from "./transport.js";
6
+ import { formatIssues, invalidRequest, send } from "./transport.js";
7
+
8
+ /**
9
+ * Typed client for the Management API (design.md §26).
10
+ *
11
+ * - one method per design.md §26.2 route
12
+ * - `Authorization: Bearer <key>` on every request (the key is never logged)
13
+ * - `Idempotency-Key` generated per write, caller-overridable (§26.3)
14
+ * - `If-Match` honored on conditional updates/deletes (§26.3)
15
+ * - response bodies validated with the `@smartcrab/contracts-management`
16
+ * zod schemas (`safeParse` — never trust the wire)
17
+ * - `x-request-id` (and `etag`) surfaced on every result for support correlation
18
+ */
19
+
20
+ // ---------------------------------------------------------------------------
21
+ // Options & shared parameter types
22
+ // ---------------------------------------------------------------------------
23
+
24
+ export interface ManagementClientOptions {
25
+ /** API root, e.g. `https://api.example-auth.com/v1` (design.md §26). */
26
+ readonly baseUrl: string;
27
+ /** `sk_live_...` / `sk_test_...` Management API key (design.md §26.1). */
28
+ readonly apiKey: string;
29
+ /** Injectable fetch implementation (defaults to the global `fetch`). */
30
+ readonly fetch?: typeof fetch;
31
+ }
32
+
33
+ export interface PaginationParams {
34
+ readonly cursor?: string;
35
+ /** Max 100 (design.md §26.3); the server default applies when omitted. */
36
+ readonly limit?: number;
37
+ }
38
+
39
+ export interface WriteOptions {
40
+ /** Caller override for the `Idempotency-Key` header; a UUID is generated when omitted. */
41
+ readonly idempotencyKey?: string;
42
+ /** Entity tag from a prior response (`ManagementResponse.etag`) sent as `If-Match`. */
43
+ readonly ifMatch?: string;
44
+ }
45
+
46
+ export interface WorkspaceListParams extends PaginationParams {
47
+ readonly status?: cm.WorkspaceStatus;
48
+ }
49
+ export type WorkspaceMemberListParams = PaginationParams;
50
+ export interface ProjectListParams extends PaginationParams {
51
+ readonly workspace_id: string;
52
+ }
53
+ export interface EnvironmentListParams extends PaginationParams {
54
+ readonly project_id: string;
55
+ readonly type?: cm.EnvironmentType;
56
+ }
57
+ export interface ClientListParams extends PaginationParams {
58
+ readonly environment_id: string;
59
+ readonly client_type?: cm.ClientType;
60
+ }
61
+ export interface ConnectionListParams extends PaginationParams {
62
+ readonly environment_id: string;
63
+ readonly provider?: cm.Connection["provider"];
64
+ }
65
+ export interface DomainListParams extends PaginationParams {
66
+ readonly environment_id: string;
67
+ readonly status?: cm.CustomDomainStatus;
68
+ }
69
+ export interface UserListParams extends PaginationParams {
70
+ readonly environment_id: string;
71
+ readonly status?: cm.UserStatus;
72
+ readonly search?: string;
73
+ }
74
+ export interface WebhookListParams extends PaginationParams {
75
+ readonly environment_id: string;
76
+ }
77
+ export interface WebhookDeliveryListParams extends PaginationParams {
78
+ readonly status?: cm.WebhookDeliveryStatus;
79
+ readonly occurred_after?: string;
80
+ readonly occurred_before?: string;
81
+ }
82
+ export interface AuditEventListParams extends PaginationParams {
83
+ readonly environment_id: string;
84
+ readonly actor_type?: cm.AuditActorType;
85
+ readonly action?: string;
86
+ readonly subject_type?: string;
87
+ readonly subject_id?: string;
88
+ readonly result?: cm.AuditResult;
89
+ readonly created_after?: string;
90
+ readonly created_before?: string;
91
+ }
92
+ export interface MauUsageParams {
93
+ readonly billing_month?: string;
94
+ readonly environment_id?: string;
95
+ }
96
+
97
+ // ---------------------------------------------------------------------------
98
+ // Request body input types (zod input side: schema-defaulted fields optional)
99
+ // ---------------------------------------------------------------------------
100
+
101
+ export type WorkspaceCreateInput = InputOf<typeof cm.workspaceCreateRequestSchema>;
102
+ export type WorkspaceUpdateInput = InputOf<typeof cm.workspaceUpdateRequestSchema>;
103
+ export type ProjectCreateInput = InputOf<typeof cm.projectCreateRequestSchema>;
104
+ export type ProjectUpdateInput = InputOf<typeof cm.projectUpdateRequestSchema>;
105
+ export type EnvironmentCreateInput = InputOf<typeof cm.environmentCreateRequestSchema>;
106
+ export type EnvironmentUpdateInput = InputOf<typeof cm.environmentUpdateRequestSchema>;
107
+ export type RpMigrationDisableInput = InputOf<typeof cm.rpMigrationDisableLegacyRequestSchema>;
108
+ export type RpMigration = cm.RpMigrationResponse;
109
+ export type ClientCreateInput = InputOf<typeof cm.clientCreateRequestSchema>;
110
+ export type ClientUpdateInput = InputOf<typeof cm.clientUpdateRequestSchema>;
111
+ export type ConnectionCreateInput = InputOf<typeof cm.connectionCreateRequestSchema>;
112
+ export type ConnectionUpdateInput = InputOf<typeof cm.connectionUpdateRequestSchema>;
113
+ export type DomainCreateInput = InputOf<typeof cm.domainCreateRequestSchema>;
114
+ export type DomainUpdateInput = InputOf<typeof cm.domainUpdateRequestSchema>;
115
+ export type UserCreateInput = InputOf<typeof cm.userCreateRequestSchema>;
116
+ export type UserUpdateInput = InputOf<typeof cm.userUpdateRequestSchema>;
117
+ export type UserBlockInput = InputOf<typeof cm.userBlockRequestSchema>;
118
+ export type UserImportJobCreateInput = InputOf<typeof cm.userImportJobCreateRequestSchema>;
119
+ export type UserExportJobCreateInput = InputOf<typeof cm.userExportJobCreateRequestSchema>;
120
+ export type WebhookCreateInput = InputOf<typeof cm.webhookCreateRequestSchema>;
121
+ export type WebhookUpdateInput = InputOf<typeof cm.webhookUpdateRequestSchema>;
122
+ export type WebhookTestInput = InputOf<typeof cm.webhookTestRequestSchema>;
123
+ export type BillingCheckoutSessionCreateInput = InputOf<
124
+ typeof cm.billingCheckoutSessionCreateRequestSchema
125
+ >;
126
+ export type BillingPortalSessionCreateInput = InputOf<
127
+ typeof cm.billingPortalSessionCreateRequestSchema
128
+ >;
129
+
130
+ type Api<T> = ResultAsync<ManagementResponse<T>, ManagementClientError>;
131
+ export interface ManagementClient {
132
+ // Workspaces
133
+ listWorkspaces(params?: WorkspaceListParams): Api<cm.WorkspaceListResponse>;
134
+ listWorkspaceMembers(
135
+ workspaceId: string,
136
+ params?: WorkspaceMemberListParams,
137
+ ): Api<cm.WorkspaceMemberListResponse>;
138
+ createWorkspace(body: WorkspaceCreateInput, options?: WriteOptions): Api<cm.Workspace>;
139
+ getWorkspace(workspaceId: string): Api<cm.Workspace>;
140
+ updateWorkspace(
141
+ workspaceId: string,
142
+ body: WorkspaceUpdateInput,
143
+ options?: WriteOptions,
144
+ ): Api<cm.Workspace>;
145
+
146
+ // Projects
147
+ listProjects(params: ProjectListParams): Api<cm.ProjectListResponse>;
148
+ createProject(body: ProjectCreateInput, options?: WriteOptions): Api<cm.Project>;
149
+ getProject(projectId: string): Api<cm.Project>;
150
+ updateProject(
151
+ projectId: string,
152
+ body: ProjectUpdateInput,
153
+ options?: WriteOptions,
154
+ ): Api<cm.Project>;
155
+ deleteProject(projectId: string, options?: WriteOptions): Api<cm.ProjectDeleteResponse>;
156
+
157
+ // Environments
158
+ listEnvironments(params: EnvironmentListParams): Api<cm.EnvironmentListResponse>;
159
+ createEnvironment(body: EnvironmentCreateInput, options?: WriteOptions): Api<cm.Environment>;
160
+ getEnvironment(environmentId: string): Api<cm.Environment>;
161
+ updateEnvironment(
162
+ environmentId: string,
163
+ body: EnvironmentUpdateInput,
164
+ options?: WriteOptions,
165
+ ): Api<cm.Environment>;
166
+ deleteEnvironment(
167
+ environmentId: string,
168
+ options?: WriteOptions,
169
+ ): Api<cm.EnvironmentDeleteResponse>;
170
+ getRpMigration(environmentId: string): Api<RpMigration>;
171
+ disableLegacyRp(
172
+ environmentId: string,
173
+ body: RpMigrationDisableInput,
174
+ options?: WriteOptions,
175
+ ): Api<RpMigration>;
176
+
177
+ // Clients
178
+ listClients(params: ClientListParams): Api<cm.ClientListResponse>;
179
+ createClient(body: ClientCreateInput, options?: WriteOptions): Api<cm.ClientCreateResponse>;
180
+ getClient(clientId: string): Api<cm.Client>;
181
+ updateClient(clientId: string, body: ClientUpdateInput, options?: WriteOptions): Api<cm.Client>;
182
+ deleteClient(clientId: string, options?: WriteOptions): Api<cm.ClientDeleteResponse>;
183
+ rotateClientSecret(clientId: string, options?: WriteOptions): Api<cm.ClientRotateSecretResponse>;
184
+
185
+ // Connections (social/OAuth providers, design.md §20)
186
+ listConnections(params: ConnectionListParams): Api<cm.ConnectionListResponse>;
187
+ createConnection(body: ConnectionCreateInput, options?: WriteOptions): Api<cm.Connection>;
188
+ updateConnection(
189
+ connectionId: string,
190
+ body: ConnectionUpdateInput,
191
+ options?: WriteOptions,
192
+ ): Api<cm.Connection>;
193
+ deleteConnection(connectionId: string, options?: WriteOptions): Api<cm.ConnectionDeleteResponse>;
194
+
195
+ // Custom domains (design.md §8.2, §11.9)
196
+ listDomains(params: DomainListParams): Api<cm.DomainListResponse>;
197
+ createDomain(body: DomainCreateInput, options?: WriteOptions): Api<cm.Domain>;
198
+ getDomain(domainId: string): Api<cm.Domain>;
199
+ updateDomain(domainId: string, body: DomainUpdateInput, options?: WriteOptions): Api<cm.Domain>;
200
+ deleteDomain(domainId: string, options?: WriteOptions): Api<cm.DomainDeleteResponse>;
201
+ retryDomainValidation(domainId: string, options?: WriteOptions): Api<cm.Domain>;
202
+
203
+ // Users
204
+ listUsers(params: UserListParams): Api<cm.UserListResponse>;
205
+ createUser(body: UserCreateInput, options?: WriteOptions): Api<cm.User>;
206
+ getUser(environmentId: string, userId: string): Api<cm.User>;
207
+ updateUser(
208
+ environmentId: string,
209
+ userId: string,
210
+ body: UserUpdateInput,
211
+ options?: WriteOptions,
212
+ ): Api<cm.User>;
213
+ deleteUser(
214
+ environmentId: string,
215
+ userId: string,
216
+ options?: WriteOptions,
217
+ ): Api<cm.UserDeleteResponse>;
218
+ blockUser(
219
+ environmentId: string,
220
+ userId: string,
221
+ body?: UserBlockInput,
222
+ options?: WriteOptions,
223
+ ): Api<cm.UserBlockResponse>;
224
+ unblockUser(
225
+ environmentId: string,
226
+ userId: string,
227
+ options?: WriteOptions,
228
+ ): Api<cm.UserUnblockResponse>;
229
+
230
+ // User sub-resources (identities / passkeys / sessions)
231
+ listUserIdentities(
232
+ environmentId: string,
233
+ userId: string,
234
+ params?: PaginationParams,
235
+ ): Api<cm.UserIdentityListResponse>;
236
+ deleteUserIdentity(
237
+ environmentId: string,
238
+ userId: string,
239
+ identityId: string,
240
+ options?: WriteOptions,
241
+ ): Api<cm.UserIdentityDeleteResponse>;
242
+ listUserPasskeys(
243
+ environmentId: string,
244
+ userId: string,
245
+ params?: PaginationParams,
246
+ ): Api<cm.UserPasskeyListResponse>;
247
+ deleteUserPasskey(
248
+ environmentId: string,
249
+ userId: string,
250
+ passkeyId: string,
251
+ options?: WriteOptions,
252
+ ): Api<cm.UserPasskeyDeleteResponse>;
253
+ listUserSessions(
254
+ environmentId: string,
255
+ userId: string,
256
+ params?: PaginationParams,
257
+ ): Api<cm.UserSessionListResponse>;
258
+ revokeUserSession(
259
+ environmentId: string,
260
+ userId: string,
261
+ sessionId: string,
262
+ options?: WriteOptions,
263
+ ): Api<cm.UserSessionRevokeResponse>;
264
+ revokeAllUserSessions(
265
+ environmentId: string,
266
+ userId: string,
267
+ options?: WriteOptions,
268
+ ): Api<cm.UserSessionsRevokeAllResponse>;
269
+
270
+ // User import/export jobs
271
+ createUserImportJob(
272
+ body: UserImportJobCreateInput,
273
+ options?: WriteOptions,
274
+ ): Api<cm.UserImportJob>;
275
+ getUserImportJob(jobId: string): Api<cm.UserImportJob>;
276
+ createUserExportJob(
277
+ body: UserExportJobCreateInput,
278
+ options?: WriteOptions,
279
+ ): Api<cm.UserExportJob>;
280
+ getUserExportJob(jobId: string): Api<cm.UserExportJob>;
281
+
282
+ // Webhooks
283
+ listWebhooks(params: WebhookListParams): Api<cm.WebhookListResponse>;
284
+ listWebhookDeliveries(
285
+ webhookId: string,
286
+ params?: WebhookDeliveryListParams,
287
+ ): Api<cm.WebhookDeliveryListResponse>;
288
+ createWebhook(body: WebhookCreateInput, options?: WriteOptions): Api<cm.WebhookCreateResponse>;
289
+ updateWebhook(
290
+ webhookId: string,
291
+ body: WebhookUpdateInput,
292
+ options?: WriteOptions,
293
+ ): Api<cm.Webhook>;
294
+ deleteWebhook(webhookId: string, options?: WriteOptions): Api<cm.WebhookDeleteResponse>;
295
+ rotateWebhookSecret(
296
+ webhookId: string,
297
+ options?: WriteOptions,
298
+ ): Api<cm.WebhookRotateSecretResponse>;
299
+ testWebhook(
300
+ webhookId: string,
301
+ body?: WebhookTestInput,
302
+ options?: WriteOptions,
303
+ ): Api<cm.WebhookTestResponse>;
304
+
305
+ // Audit events / usage / billing
306
+ listAuditEvents(params: AuditEventListParams): Api<cm.AuditEventListResponse>;
307
+ getMauUsage(params?: MauUsageParams): Api<cm.MauUsageResponse>;
308
+ createBillingCheckoutSession(
309
+ body: BillingCheckoutSessionCreateInput,
310
+ options?: WriteOptions,
311
+ ): Api<cm.BillingCheckoutSessionCreateResponse>;
312
+ createBillingPortalSession(
313
+ body: BillingPortalSessionCreateInput,
314
+ options?: WriteOptions,
315
+ ): Api<cm.BillingPortalSessionCreateResponse>;
316
+ }
317
+
318
+ // ---------------------------------------------------------------------------
319
+ // Implementation
320
+ // ---------------------------------------------------------------------------
321
+
322
+ /** Normalizes and validates the API root. Throws `TypeError` on programmer misconfiguration. */
323
+ const normalizeBaseUrl = (raw: string): string => {
324
+ const trimmed = raw.trim().replace(/\/+$/, "");
325
+ if (!URL.canParse(trimmed)) {
326
+ throw new TypeError(`management-client: invalid baseUrl ${JSON.stringify(raw)}`);
327
+ }
328
+ const protocol = new URL(trimmed).protocol;
329
+ if (protocol !== "https:" && protocol !== "http:") {
330
+ throw new TypeError(`management-client: baseUrl must be http(s), got protocol ${protocol}`);
331
+ }
332
+ return trimmed;
333
+ };
334
+
335
+ const newIdempotencyKey = (): string => crypto.randomUUID();
336
+
337
+ const segment = (id: string): string => encodeURIComponent(id);
338
+ const getSpec = (
339
+ path: string,
340
+ query?: Readonly<Record<string, string | number | boolean | undefined>>,
341
+ ): RequestSpec => ({
342
+ method: "GET",
343
+ path,
344
+ ...(query !== undefined ? { query } : {}),
345
+ });
346
+
347
+ export const createManagementClient = (options: ManagementClientOptions): ManagementClient => {
348
+ const baseUrl = normalizeBaseUrl(options.baseUrl);
349
+ if (options.apiKey.length === 0) {
350
+ throw new TypeError("management-client: apiKey must not be empty");
351
+ }
352
+ const config = { baseUrl, apiKey: options.apiKey, fetchFn: options.fetch ?? fetch };
353
+
354
+ const writeSpec = (
355
+ method: "POST" | "PATCH" | "DELETE",
356
+ path: string,
357
+ body: unknown,
358
+ writeOptions: WriteOptions | undefined,
359
+ query?: Readonly<Record<string, string | number | boolean | undefined>>,
360
+ ): RequestSpec => ({
361
+ method,
362
+ path,
363
+ ...(query !== undefined ? { query } : {}),
364
+ ...(body !== undefined ? { body } : {}),
365
+ idempotencyKey: writeOptions?.idempotencyKey ?? newIdempotencyKey(),
366
+ ...(writeOptions?.ifMatch !== undefined ? { ifMatch: writeOptions.ifMatch } : {}),
367
+ });
368
+ /** Validates a request body against its contract schema before anything hits the wire. */
369
+ const withValidBody = <B, T>(
370
+ schema: Schema<B>,
371
+ body: unknown,
372
+ then: (validBody: B) => Api<T>,
373
+ ): Api<T> => {
374
+ const parsed = schema.safeParse(body);
375
+ if (!parsed.success) {
376
+ return Promise.resolve(fail(invalidRequest(formatIssues(parsed.error))));
377
+ }
378
+ return then(parsed.data);
379
+ };
380
+
381
+ return {
382
+ // --------------------------------------------------------------
383
+ // Workspaces
384
+ // --------------------------------------------------------------
385
+ listWorkspaces: (params) =>
386
+ send(
387
+ config,
388
+ getSpec("/workspaces", {
389
+ cursor: params?.cursor,
390
+ limit: params?.limit,
391
+ status: params?.status,
392
+ }),
393
+ cm.workspaceListResponseSchema,
394
+ ),
395
+ listWorkspaceMembers: (workspaceId, params) =>
396
+ send(
397
+ config,
398
+ getSpec(`/workspaces/${segment(workspaceId)}/members`, {
399
+ cursor: params?.cursor,
400
+ limit: params?.limit,
401
+ }),
402
+ cm.workspaceMemberListResponseSchema,
403
+ ),
404
+ createWorkspace: (body, writeOptions) =>
405
+ withValidBody(cm.workspaceCreateRequestSchema, body, (valid) =>
406
+ send(
407
+ config,
408
+ writeSpec("POST", "/workspaces", valid, writeOptions),
409
+ cm.workspaceCreateResponseSchema,
410
+ ),
411
+ ),
412
+ getWorkspace: (workspaceId) =>
413
+ send(config, getSpec(`/workspaces/${segment(workspaceId)}`), cm.workspaceGetResponseSchema),
414
+ updateWorkspace: (workspaceId, body, writeOptions) =>
415
+ withValidBody(cm.workspaceUpdateRequestSchema, body, (valid) =>
416
+ send(
417
+ config,
418
+ writeSpec("PATCH", `/workspaces/${segment(workspaceId)}`, valid, writeOptions),
419
+ cm.workspaceUpdateResponseSchema,
420
+ ),
421
+ ),
422
+
423
+ // --------------------------------------------------------------
424
+ // Projects
425
+ // --------------------------------------------------------------
426
+ listProjects: (params) =>
427
+ send(
428
+ config,
429
+ getSpec("/projects", {
430
+ cursor: params.cursor,
431
+ limit: params.limit,
432
+ workspace_id: params.workspace_id,
433
+ }),
434
+ cm.projectListResponseSchema,
435
+ ),
436
+ createProject: (body, writeOptions) =>
437
+ withValidBody(cm.projectCreateRequestSchema, body, (valid) =>
438
+ send(
439
+ config,
440
+ writeSpec("POST", "/projects", valid, writeOptions),
441
+ cm.projectCreateResponseSchema,
442
+ ),
443
+ ),
444
+ getProject: (projectId) =>
445
+ send(config, getSpec(`/projects/${segment(projectId)}`), cm.projectGetResponseSchema),
446
+ updateProject: (projectId, body, writeOptions) =>
447
+ withValidBody(cm.projectUpdateRequestSchema, body, (valid) =>
448
+ send(
449
+ config,
450
+ writeSpec("PATCH", `/projects/${segment(projectId)}`, valid, writeOptions),
451
+ cm.projectUpdateResponseSchema,
452
+ ),
453
+ ),
454
+ deleteProject: (projectId, writeOptions) =>
455
+ send(
456
+ config,
457
+ writeSpec("DELETE", `/projects/${segment(projectId)}`, undefined, writeOptions),
458
+ cm.projectDeleteResponseSchema,
459
+ ),
460
+
461
+ // --------------------------------------------------------------
462
+ // Environments
463
+ // --------------------------------------------------------------
464
+ listEnvironments: (params) =>
465
+ send(
466
+ config,
467
+ getSpec("/environments", {
468
+ cursor: params.cursor,
469
+ limit: params.limit,
470
+ project_id: params.project_id,
471
+ type: params.type,
472
+ }),
473
+ cm.environmentListResponseSchema,
474
+ ),
475
+ createEnvironment: (body, writeOptions) =>
476
+ withValidBody(cm.environmentCreateRequestSchema, body, (valid) =>
477
+ send(
478
+ config,
479
+ writeSpec("POST", "/environments", valid, writeOptions),
480
+ cm.environmentCreateResponseSchema,
481
+ ),
482
+ ),
483
+ getEnvironment: (environmentId) =>
484
+ send(
485
+ config,
486
+ getSpec(`/environments/${segment(environmentId)}`),
487
+ cm.environmentGetResponseSchema,
488
+ ),
489
+ updateEnvironment: (environmentId, body, writeOptions) =>
490
+ withValidBody(cm.environmentUpdateRequestSchema, body, (valid) =>
491
+ send(
492
+ config,
493
+ writeSpec("PATCH", `/environments/${segment(environmentId)}`, valid, writeOptions),
494
+ cm.environmentUpdateResponseSchema,
495
+ ),
496
+ ),
497
+ deleteEnvironment: (environmentId, writeOptions) =>
498
+ send(
499
+ config,
500
+ writeSpec("DELETE", `/environments/${segment(environmentId)}`, undefined, writeOptions),
501
+ cm.environmentDeleteResponseSchema,
502
+ ),
503
+ getRpMigration: (environmentId) =>
504
+ send(
505
+ config,
506
+ getSpec(`/environments/${segment(environmentId)}/rp-migration`),
507
+ cm.rpMigrationResponseSchema,
508
+ ),
509
+ disableLegacyRp: (environmentId, body, writeOptions) =>
510
+ withValidBody(cm.rpMigrationDisableLegacyRequestSchema, body, (valid) =>
511
+ send(
512
+ config,
513
+ writeSpec(
514
+ "POST",
515
+ `/environments/${segment(environmentId)}/rp-migration/disable-legacy`,
516
+ valid,
517
+ writeOptions,
518
+ ),
519
+ cm.rpMigrationResponseSchema,
520
+ ),
521
+ ),
522
+
523
+ // --------------------------------------------------------------
524
+ // Clients
525
+ // --------------------------------------------------------------
526
+ listClients: (params) =>
527
+ send(
528
+ config,
529
+ getSpec("/clients", {
530
+ cursor: params.cursor,
531
+ limit: params.limit,
532
+ environment_id: params.environment_id,
533
+ client_type: params.client_type,
534
+ }),
535
+ cm.clientListResponseSchema,
536
+ ),
537
+ createClient: (body, writeOptions) =>
538
+ withValidBody(cm.clientCreateRequestSchema, body, (valid) =>
539
+ send(
540
+ config,
541
+ writeSpec("POST", "/clients", valid, writeOptions),
542
+ cm.clientCreateResponseSchema,
543
+ ),
544
+ ),
545
+ getClient: (clientId) =>
546
+ send(config, getSpec(`/clients/${segment(clientId)}`), cm.clientGetResponseSchema),
547
+ updateClient: (clientId, body, writeOptions) =>
548
+ withValidBody(cm.clientUpdateRequestSchema, body, (valid) =>
549
+ send(
550
+ config,
551
+ writeSpec("PATCH", `/clients/${segment(clientId)}`, valid, writeOptions),
552
+ cm.clientUpdateResponseSchema,
553
+ ),
554
+ ),
555
+ deleteClient: (clientId, writeOptions) =>
556
+ send(
557
+ config,
558
+ writeSpec("DELETE", `/clients/${segment(clientId)}`, undefined, writeOptions),
559
+ cm.clientDeleteResponseSchema,
560
+ ),
561
+ rotateClientSecret: (clientId, writeOptions) =>
562
+ send(
563
+ config,
564
+ writeSpec("POST", `/clients/${segment(clientId)}/rotate-secret`, {}, writeOptions),
565
+ cm.clientRotateSecretResponseSchema,
566
+ ),
567
+
568
+ // --------------------------------------------------------------
569
+ // Connections
570
+ // --------------------------------------------------------------
571
+ listConnections: (params) =>
572
+ send(
573
+ config,
574
+ getSpec("/connections", {
575
+ cursor: params.cursor,
576
+ limit: params.limit,
577
+ environment_id: params.environment_id,
578
+ provider: params.provider,
579
+ }),
580
+ cm.connectionListResponseSchema,
581
+ ),
582
+ createConnection: (body, writeOptions) =>
583
+ withValidBody(cm.connectionCreateRequestSchema, body, (valid) =>
584
+ send(
585
+ config,
586
+ writeSpec("POST", "/connections", valid, writeOptions),
587
+ cm.connectionCreateResponseSchema,
588
+ ),
589
+ ),
590
+ updateConnection: (connectionId, body, writeOptions) =>
591
+ withValidBody(cm.connectionUpdateRequestSchema, body, (valid) =>
592
+ send(
593
+ config,
594
+ writeSpec("PATCH", `/connections/${segment(connectionId)}`, valid, writeOptions),
595
+ cm.connectionUpdateResponseSchema,
596
+ ),
597
+ ),
598
+ deleteConnection: (connectionId, writeOptions) =>
599
+ send(
600
+ config,
601
+ writeSpec("DELETE", `/connections/${segment(connectionId)}`, undefined, writeOptions),
602
+ cm.connectionDeleteResponseSchema,
603
+ ),
604
+
605
+ // --------------------------------------------------------------
606
+ // Domains
607
+ // --------------------------------------------------------------
608
+ listDomains: (params) =>
609
+ send(
610
+ config,
611
+ getSpec("/domains", {
612
+ cursor: params.cursor,
613
+ limit: params.limit,
614
+ environment_id: params.environment_id,
615
+ status: params.status,
616
+ }),
617
+ cm.domainListResponseSchema,
618
+ ),
619
+ createDomain: (body, writeOptions) =>
620
+ withValidBody(cm.domainCreateRequestSchema, body, (valid) =>
621
+ send(
622
+ config,
623
+ writeSpec("POST", "/domains", valid, writeOptions),
624
+ cm.domainCreateResponseSchema,
625
+ ),
626
+ ),
627
+ getDomain: (domainId) =>
628
+ send(config, getSpec(`/domains/${segment(domainId)}`), cm.domainGetResponseSchema),
629
+ updateDomain: (domainId, body, writeOptions) =>
630
+ withValidBody(cm.domainUpdateRequestSchema, body, (valid) =>
631
+ send(
632
+ config,
633
+ writeSpec("PATCH", `/domains/${segment(domainId)}`, valid, writeOptions),
634
+ cm.domainUpdateResponseSchema,
635
+ ),
636
+ ),
637
+ deleteDomain: (domainId, writeOptions) =>
638
+ send(
639
+ config,
640
+ writeSpec("DELETE", `/domains/${segment(domainId)}`, undefined, writeOptions),
641
+ cm.domainDeleteResponseSchema,
642
+ ),
643
+ retryDomainValidation: (domainId, writeOptions) =>
644
+ send(
645
+ config,
646
+ writeSpec("POST", `/domains/${segment(domainId)}/retry-validation`, {}, writeOptions),
647
+ cm.domainRetryValidationResponseSchema,
648
+ ),
649
+
650
+ // --------------------------------------------------------------
651
+ // Users
652
+ // --------------------------------------------------------------
653
+ listUsers: (params) =>
654
+ send(
655
+ config,
656
+ getSpec("/users", {
657
+ cursor: params.cursor,
658
+ limit: params.limit,
659
+ environment_id: params.environment_id,
660
+ status: params.status,
661
+ search: params.search,
662
+ }),
663
+ cm.userListResponseSchema,
664
+ ),
665
+ createUser: (body, writeOptions) =>
666
+ withValidBody(cm.userCreateRequestSchema, body, (valid) =>
667
+ send(config, writeSpec("POST", "/users", valid, writeOptions), cm.userCreateResponseSchema),
668
+ ),
669
+ getUser: (environmentId, userId) =>
670
+ send(
671
+ config,
672
+ getSpec(`/users/${segment(userId)}`, { environment_id: environmentId }),
673
+ cm.userGetResponseSchema,
674
+ ),
675
+ updateUser: (environmentId, userId, body, writeOptions) =>
676
+ withValidBody(cm.userUpdateRequestSchema, body, (valid) =>
677
+ send(
678
+ config,
679
+ writeSpec("PATCH", `/users/${segment(userId)}`, valid, writeOptions, {
680
+ environment_id: environmentId,
681
+ }),
682
+ cm.userUpdateResponseSchema,
683
+ ),
684
+ ),
685
+ deleteUser: (environmentId, userId, writeOptions) =>
686
+ send(
687
+ config,
688
+ writeSpec("DELETE", `/users/${segment(userId)}`, undefined, writeOptions, {
689
+ environment_id: environmentId,
690
+ }),
691
+ cm.userDeleteResponseSchema,
692
+ ),
693
+ blockUser: (environmentId, userId, body, writeOptions) =>
694
+ withValidBody(cm.userBlockRequestSchema, body ?? {}, (valid) =>
695
+ send(
696
+ config,
697
+ writeSpec("POST", `/users/${segment(userId)}/block`, valid, writeOptions, {
698
+ environment_id: environmentId,
699
+ }),
700
+ cm.userBlockResponseSchema,
701
+ ),
702
+ ),
703
+ unblockUser: (environmentId, userId, writeOptions) =>
704
+ send(
705
+ config,
706
+ writeSpec("POST", `/users/${segment(userId)}/unblock`, {}, writeOptions, {
707
+ environment_id: environmentId,
708
+ }),
709
+ cm.userUnblockResponseSchema,
710
+ ),
711
+
712
+ // --------------------------------------------------------------
713
+ // User sub-resources
714
+ // --------------------------------------------------------------
715
+ listUserIdentities: (environmentId, userId, params) =>
716
+ send(
717
+ config,
718
+ getSpec(`/users/${segment(userId)}/identities`, {
719
+ environment_id: environmentId,
720
+ cursor: params?.cursor,
721
+ limit: params?.limit,
722
+ }),
723
+ cm.userIdentityListResponseSchema,
724
+ ),
725
+ deleteUserIdentity: (environmentId, userId, identityId, writeOptions) =>
726
+ send(
727
+ config,
728
+ writeSpec(
729
+ "DELETE",
730
+ `/users/${segment(userId)}/identities/${segment(identityId)}`,
731
+ undefined,
732
+ writeOptions,
733
+ { environment_id: environmentId },
734
+ ),
735
+ cm.userIdentityDeleteResponseSchema,
736
+ ),
737
+ listUserPasskeys: (environmentId, userId, params) =>
738
+ send(
739
+ config,
740
+ getSpec(`/users/${segment(userId)}/passkeys`, {
741
+ environment_id: environmentId,
742
+ cursor: params?.cursor,
743
+ limit: params?.limit,
744
+ }),
745
+ cm.userPasskeyListResponseSchema,
746
+ ),
747
+ deleteUserPasskey: (environmentId, userId, passkeyId, writeOptions) =>
748
+ send(
749
+ config,
750
+ writeSpec(
751
+ "DELETE",
752
+ `/users/${segment(userId)}/passkeys/${segment(passkeyId)}`,
753
+ undefined,
754
+ writeOptions,
755
+ { environment_id: environmentId },
756
+ ),
757
+ cm.userPasskeyDeleteResponseSchema,
758
+ ),
759
+ listUserSessions: (environmentId, userId, params) =>
760
+ send(
761
+ config,
762
+ getSpec(`/users/${segment(userId)}/sessions`, {
763
+ environment_id: environmentId,
764
+ cursor: params?.cursor,
765
+ limit: params?.limit,
766
+ }),
767
+ cm.userSessionListResponseSchema,
768
+ ),
769
+ revokeUserSession: (environmentId, userId, sessionId, writeOptions) =>
770
+ send(
771
+ config,
772
+ writeSpec(
773
+ "DELETE",
774
+ `/users/${segment(userId)}/sessions/${segment(sessionId)}`,
775
+ undefined,
776
+ writeOptions,
777
+ { environment_id: environmentId },
778
+ ),
779
+ cm.userSessionRevokeResponseSchema,
780
+ ),
781
+ revokeAllUserSessions: (environmentId, userId, writeOptions) =>
782
+ send(
783
+ config,
784
+ writeSpec("DELETE", `/users/${segment(userId)}/sessions`, undefined, writeOptions, {
785
+ environment_id: environmentId,
786
+ }),
787
+ cm.userSessionsRevokeAllResponseSchema,
788
+ ),
789
+
790
+ // --------------------------------------------------------------
791
+ // User import/export jobs
792
+ // --------------------------------------------------------------
793
+ createUserImportJob: (body, writeOptions) =>
794
+ withValidBody(cm.userImportJobCreateRequestSchema, body, (valid) =>
795
+ send(
796
+ config,
797
+ writeSpec("POST", "/user-import-jobs", valid, writeOptions),
798
+ cm.userImportJobCreateResponseSchema,
799
+ ),
800
+ ),
801
+ getUserImportJob: (jobId) =>
802
+ send(
803
+ config,
804
+ getSpec(`/user-import-jobs/${segment(jobId)}`),
805
+ cm.userImportJobGetResponseSchema,
806
+ ),
807
+ createUserExportJob: (body, writeOptions) =>
808
+ withValidBody(cm.userExportJobCreateRequestSchema, body, (valid) =>
809
+ send(
810
+ config,
811
+ writeSpec("POST", "/user-export-jobs", valid, writeOptions),
812
+ cm.userExportJobCreateResponseSchema,
813
+ ),
814
+ ),
815
+ getUserExportJob: (jobId) =>
816
+ send(
817
+ config,
818
+ getSpec(`/user-export-jobs/${segment(jobId)}`),
819
+ cm.userExportJobGetResponseSchema,
820
+ ),
821
+
822
+ // --------------------------------------------------------------
823
+ // Webhooks
824
+ // --------------------------------------------------------------
825
+ listWebhooks: (params) =>
826
+ send(
827
+ config,
828
+ getSpec("/webhooks", {
829
+ cursor: params.cursor,
830
+ limit: params.limit,
831
+ environment_id: params.environment_id,
832
+ }),
833
+ cm.webhookListResponseSchema,
834
+ ),
835
+ listWebhookDeliveries: (webhookId, params) =>
836
+ send(
837
+ config,
838
+ getSpec(`/webhooks/${segment(webhookId)}/deliveries`, {
839
+ cursor: params?.cursor,
840
+ limit: params?.limit,
841
+ status: params?.status,
842
+ occurred_after: params?.occurred_after,
843
+ occurred_before: params?.occurred_before,
844
+ }),
845
+ cm.webhookDeliveryListResponseSchema,
846
+ ),
847
+ createWebhook: (body, writeOptions) =>
848
+ withValidBody(cm.webhookCreateRequestSchema, body, (valid) =>
849
+ send(
850
+ config,
851
+ writeSpec("POST", "/webhooks", valid, writeOptions),
852
+ cm.webhookCreateResponseSchema,
853
+ ),
854
+ ),
855
+ updateWebhook: (webhookId, body, writeOptions) =>
856
+ withValidBody(cm.webhookUpdateRequestSchema, body, (valid) =>
857
+ send(
858
+ config,
859
+ writeSpec("PATCH", `/webhooks/${segment(webhookId)}`, valid, writeOptions),
860
+ cm.webhookUpdateResponseSchema,
861
+ ),
862
+ ),
863
+ deleteWebhook: (webhookId, writeOptions) =>
864
+ send(
865
+ config,
866
+ writeSpec("DELETE", `/webhooks/${segment(webhookId)}`, undefined, writeOptions),
867
+ cm.webhookDeleteResponseSchema,
868
+ ),
869
+ rotateWebhookSecret: (webhookId, writeOptions) =>
870
+ send(
871
+ config,
872
+ writeSpec("POST", `/webhooks/${segment(webhookId)}/rotate-secret`, {}, writeOptions),
873
+ cm.webhookRotateSecretResponseSchema,
874
+ ),
875
+ testWebhook: (webhookId, body, writeOptions) =>
876
+ withValidBody(cm.webhookTestRequestSchema, body ?? {}, (valid) =>
877
+ send(
878
+ config,
879
+ writeSpec("POST", `/webhooks/${segment(webhookId)}/test`, valid, writeOptions),
880
+ cm.webhookTestResponseSchema,
881
+ ),
882
+ ),
883
+
884
+ // --------------------------------------------------------------
885
+ // Audit events / usage / billing
886
+ // --------------------------------------------------------------
887
+ listAuditEvents: (params) =>
888
+ send(
889
+ config,
890
+ getSpec("/audit-events", {
891
+ cursor: params.cursor,
892
+ limit: params.limit,
893
+ environment_id: params.environment_id,
894
+ actor_type: params.actor_type,
895
+ action: params.action,
896
+ subject_type: params.subject_type,
897
+ subject_id: params.subject_id,
898
+ result: params.result,
899
+ created_after: params.created_after,
900
+ created_before: params.created_before,
901
+ }),
902
+ cm.auditEventListResponseSchema,
903
+ ),
904
+ getMauUsage: (params) =>
905
+ send(
906
+ config,
907
+ getSpec("/usage/mau", {
908
+ billing_month: params?.billing_month,
909
+ environment_id: params?.environment_id,
910
+ }),
911
+ cm.mauUsageResponseSchema,
912
+ ),
913
+ createBillingCheckoutSession: (body, writeOptions) =>
914
+ withValidBody(cm.billingCheckoutSessionCreateRequestSchema, body, (valid) =>
915
+ send(
916
+ config,
917
+ writeSpec("POST", "/billing/checkout-session", valid, writeOptions),
918
+ cm.billingCheckoutSessionCreateResponseSchema,
919
+ ),
920
+ ),
921
+ createBillingPortalSession: (body, writeOptions) =>
922
+ withValidBody(cm.billingPortalSessionCreateRequestSchema, body, (valid) =>
923
+ send(
924
+ config,
925
+ writeSpec("POST", "/billing/portal-session", valid, writeOptions),
926
+ cm.billingPortalSessionCreateResponseSchema,
927
+ ),
928
+ ),
929
+ };
930
+ };
931
+
932
+ // Re-exported for consumers that narrow on failures (e.g. the CLI).
933
+ export { isFailure, isSuccess } from "./result.js";
934
+ export type { Result };