@planescrm/sdk 0.4.0 → 0.72.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.
@@ -0,0 +1,3232 @@
1
+ // src/config.ts
2
+ var MemoryTokenStorage = class {
3
+ constructor(seed) {
4
+ this.tokens = seed ?? null;
5
+ }
6
+ async getTokens() {
7
+ return this.tokens;
8
+ }
9
+ async setTokens(tokens) {
10
+ this.tokens = tokens;
11
+ }
12
+ };
13
+ var DEFAULT_BASE_URL = "https://api.planescrm.com/api/v1";
14
+ var DEFAULT_TIMEOUT = 3e4;
15
+ var DEFAULT_MAX_RETRIES = 3;
16
+ var DEFAULT_TOKEN_REFRESH_SKEW_MS = 6e4;
17
+
18
+ // src/errors.ts
19
+ var PlanesError = class extends Error {
20
+ constructor(message, status, code) {
21
+ super(message);
22
+ this.name = "PlanesError";
23
+ this.status = status;
24
+ this.code = code;
25
+ }
26
+ };
27
+ var AuthenticationError = class extends PlanesError {
28
+ constructor(message = "Authentication failed") {
29
+ super(message, 401, "authentication_error");
30
+ this.name = "AuthenticationError";
31
+ }
32
+ };
33
+ var AuthorizationError = class extends PlanesError {
34
+ constructor(message = "Insufficient permissions") {
35
+ super(message, 403, "authorization_error");
36
+ this.name = "AuthorizationError";
37
+ }
38
+ };
39
+ var NotFoundError = class extends PlanesError {
40
+ constructor(message = "Resource not found") {
41
+ super(message, 404, "not_found");
42
+ this.name = "NotFoundError";
43
+ }
44
+ };
45
+ var ValidationError = class extends PlanesError {
46
+ constructor(message = "Validation failed", fieldErrors = []) {
47
+ super(message, 400, "validation_error");
48
+ this.name = "ValidationError";
49
+ this.fieldErrors = fieldErrors;
50
+ }
51
+ };
52
+ var RateLimitError = class extends PlanesError {
53
+ constructor(retryAfter = 1, message = "Rate limit exceeded") {
54
+ super(message, 429, "rate_limit_error");
55
+ this.name = "RateLimitError";
56
+ this.retryAfter = retryAfter;
57
+ }
58
+ };
59
+ var ServerError = class extends PlanesError {
60
+ constructor(message = "Internal server error") {
61
+ super(message, 500, "server_error");
62
+ this.name = "ServerError";
63
+ }
64
+ };
65
+ var WebhookVerificationError = class extends PlanesError {
66
+ constructor(message = "Webhook signature verification failed") {
67
+ super(message, 400, "webhook_verification_error");
68
+ this.name = "WebhookVerificationError";
69
+ }
70
+ };
71
+ var OAuthError = class extends PlanesError {
72
+ constructor(errorCode, message = "OAuth error") {
73
+ super(message, 400, "oauth_error");
74
+ this.name = "OAuthError";
75
+ this.errorCode = errorCode;
76
+ }
77
+ };
78
+
79
+ // src/client-shims/node-crypto.ts
80
+ function unavailable(name) {
81
+ throw new Error(
82
+ `${name} is not available in @planescrm/sdk/client. Use the main @planescrm/sdk entry on a server.`
83
+ );
84
+ }
85
+ function createHmac(_algorithm, _key) {
86
+ return unavailable("createHmac (webhook verification)");
87
+ }
88
+ function timingSafeEqual(_a, _b) {
89
+ return unavailable("timingSafeEqual (webhook verification)");
90
+ }
91
+
92
+ // src/oauth.ts
93
+ async function refreshAccessToken(options) {
94
+ const baseUrl = options.baseUrl.replace(/\/+$/, "");
95
+ const url = `${baseUrl}/oauth/token`;
96
+ const body = new URLSearchParams({
97
+ grant_type: "refresh_token",
98
+ client_id: options.clientId,
99
+ client_secret: options.clientSecret,
100
+ refresh_token: options.refreshToken
101
+ });
102
+ const response = await fetch(url, {
103
+ method: "POST",
104
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
105
+ body: body.toString()
106
+ });
107
+ if (!response.ok) {
108
+ const errorBody = await response.json().catch(() => ({}));
109
+ const errorCode = errorBody["error"] ?? "unknown_error";
110
+ const errorDescription = errorBody["error_description"] ?? "Token refresh failed";
111
+ throw new OAuthError(errorCode, errorDescription);
112
+ }
113
+ return await response.json();
114
+ }
115
+ async function clientCredentialsGrant(options) {
116
+ const baseUrl = options.baseUrl.replace(/\/+$/, "");
117
+ const url = `${baseUrl}/oauth/token`;
118
+ const body = new URLSearchParams({
119
+ grant_type: "client_credentials",
120
+ client_id: options.clientId,
121
+ client_secret: options.clientSecret,
122
+ scope: options.scopes.join(" ")
123
+ });
124
+ const response = await fetch(url, {
125
+ method: "POST",
126
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
127
+ body: body.toString()
128
+ });
129
+ if (!response.ok) {
130
+ const errorBody = await response.json().catch(() => ({}));
131
+ const errorCode = errorBody["error"] ?? "unknown_error";
132
+ const errorDescription = errorBody["error_description"] ?? "Client credentials grant failed";
133
+ throw new OAuthError(errorCode, errorDescription);
134
+ }
135
+ return await response.json();
136
+ }
137
+
138
+ // src/http.ts
139
+ var HttpClient = class {
140
+ constructor(config) {
141
+ this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
142
+ this.accessToken = config.accessToken;
143
+ this.apiKey = config.apiKey;
144
+ this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
145
+ this.retryOnRateLimit = config.retryOnRateLimit !== false;
146
+ this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
147
+ this.getAccessToken = config.getAccessToken;
148
+ this.onUnauthorized = config.onUnauthorized;
149
+ this.fetchImpl = config.fetch;
150
+ if (config.clientId && config.clientSecret) {
151
+ this.oauth = {
152
+ clientId: config.clientId,
153
+ clientSecret: config.clientSecret,
154
+ tokenStorage: config.tokenStorage ?? new MemoryTokenStorage(),
155
+ skewMs: config.tokenRefreshSkewMs ?? DEFAULT_TOKEN_REFRESH_SKEW_MS,
156
+ scopes: config.scopes
157
+ };
158
+ }
159
+ }
160
+ async request(options) {
161
+ const url = this.buildUrl(options.path, options.params);
162
+ const bodyStr = options.body !== void 0 ? JSON.stringify(options.body) : void 0;
163
+ let lastError;
164
+ let didRefreshOn401 = false;
165
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
166
+ const authHeaders = await this.resolveAuthHeaders();
167
+ const headers = {
168
+ "Content-Type": "application/json",
169
+ ...authHeaders,
170
+ ...options.headers
171
+ };
172
+ if (options.idempotencyKey) headers["Idempotency-Key"] = options.idempotencyKey;
173
+ const timer = timeoutSignal(this.timeout);
174
+ const fetchOptions = {
175
+ method: options.method,
176
+ headers,
177
+ signal: timer.signal
178
+ };
179
+ if (bodyStr !== void 0) {
180
+ fetchOptions.body = bodyStr;
181
+ }
182
+ try {
183
+ const response = await (this.fetchImpl ?? fetch)(url, fetchOptions);
184
+ if (response.ok) {
185
+ if (response.status === 204) {
186
+ return void 0;
187
+ }
188
+ if (options.responseType === "arrayBuffer") {
189
+ return await response.arrayBuffer();
190
+ }
191
+ return await response.json();
192
+ }
193
+ if (response.status === 429 && this.retryOnRateLimit && attempt < this.maxRetries) {
194
+ const retryAfter = this.parseRetryAfter(response);
195
+ await this.sleep(retryAfter * 1e3);
196
+ continue;
197
+ }
198
+ if (response.status === 401 && this.oauth && !didRefreshOn401) {
199
+ didRefreshOn401 = true;
200
+ await this.refreshTokens();
201
+ attempt--;
202
+ continue;
203
+ }
204
+ if (response.status === 401 && this.onUnauthorized && !didRefreshOn401) {
205
+ didRefreshOn401 = true;
206
+ if (await this.recoverSession(authHeaders["Authorization"])) {
207
+ attempt--;
208
+ continue;
209
+ }
210
+ }
211
+ lastError = await this.mapError(response);
212
+ if (response.status !== 429 || !this.retryOnRateLimit) {
213
+ throw lastError;
214
+ }
215
+ } finally {
216
+ timer.clear();
217
+ }
218
+ }
219
+ throw lastError ?? new RateLimitError();
220
+ }
221
+ getAuthHeaders() {
222
+ if (this.getAccessToken) return {};
223
+ if (this.accessToken) {
224
+ return { Authorization: `Bearer ${this.accessToken}` };
225
+ }
226
+ if (this.apiKey) {
227
+ return { Authorization: `Bearer ${this.apiKey}` };
228
+ }
229
+ return {};
230
+ }
231
+ /**
232
+ * Resolve the Authorization header for the current request. For the static
233
+ * accessToken/apiKey modes this is {@link getAuthHeaders}. For the
234
+ * OAuth-managed path it reads the stored token, proactively refreshing when
235
+ * the token is within the skew window of expiry.
236
+ */
237
+ async resolveAuthHeaders() {
238
+ if (this.getAccessToken) {
239
+ const token = await withTimeout(this.getAccessToken(), this.timeout, "getAccessToken");
240
+ return token ? { Authorization: `Bearer ${token}` } : {};
241
+ }
242
+ if (!this.oauth) {
243
+ return this.getAuthHeaders();
244
+ }
245
+ const tokens = await this.oauth.tokenStorage.getTokens();
246
+ if (!tokens) {
247
+ return {};
248
+ }
249
+ if (tokens.expiresAt - Date.now() <= this.oauth.skewMs) {
250
+ const refreshed = await this.refreshTokens();
251
+ return { Authorization: `Bearer ${refreshed.accessToken}` };
252
+ }
253
+ return { Authorization: `Bearer ${tokens.accessToken}` };
254
+ }
255
+ /**
256
+ * Refresh the OAuth access token via `refreshAccessToken` and persist the new
257
+ * tokens through the configured {@link TokenStorage}. Concurrent callers share
258
+ * a single in-flight refresh.
259
+ */
260
+ async refreshTokens() {
261
+ if (!this.oauth) {
262
+ throw new AuthenticationError("Token refresh requires the OAuth clientId/clientSecret path");
263
+ }
264
+ if (this.refreshInFlight) {
265
+ return this.refreshInFlight;
266
+ }
267
+ const oauth = this.oauth;
268
+ this.refreshInFlight = (async () => {
269
+ const current = await oauth.tokenStorage.getTokens();
270
+ if (!current?.refreshToken) {
271
+ const response2 = await clientCredentialsGrant({
272
+ baseUrl: this.baseUrl,
273
+ clientId: oauth.clientId,
274
+ clientSecret: oauth.clientSecret,
275
+ scopes: oauth.scopes ?? []
276
+ });
277
+ const next2 = {
278
+ accessToken: response2.access_token,
279
+ refreshToken: response2.refresh_token ?? null,
280
+ expiresAt: Date.now() + response2.expires_in * 1e3
281
+ };
282
+ await oauth.tokenStorage.setTokens(next2);
283
+ return next2;
284
+ }
285
+ const response = await refreshAccessToken({
286
+ baseUrl: this.baseUrl,
287
+ clientId: oauth.clientId,
288
+ clientSecret: oauth.clientSecret,
289
+ refreshToken: current.refreshToken
290
+ });
291
+ const next = {
292
+ accessToken: response.access_token,
293
+ refreshToken: response.refresh_token || current.refreshToken,
294
+ expiresAt: Date.now() + response.expires_in * 1e3
295
+ };
296
+ await oauth.tokenStorage.setTokens(next);
297
+ return next;
298
+ })();
299
+ try {
300
+ return await this.refreshInFlight;
301
+ } finally {
302
+ this.refreshInFlight = void 0;
303
+ }
304
+ }
305
+ /**
306
+ * Ask the app to refresh its session after a 401. Resolves `true` when the
307
+ * request should be retried.
308
+ * - Requests that got a 401 while a refresh is running share that one call.
309
+ * - A request whose 401 arrives after a refresh already finished (it was
310
+ * sent with the old token) doesn't start a second refresh: if the current
311
+ * token differs from the one it sent, it just retries with the new one.
312
+ * - A refresh that throws, or doesn't settle within the request timeout,
313
+ * counts as "still signed out": the original 401 surfaces.
314
+ */
315
+ async recoverSession(sentAuthorization) {
316
+ if (!this.onUnauthorized || !this.getAccessToken) return false;
317
+ if (!this.unauthorizedInFlight) {
318
+ try {
319
+ const current = await withTimeout(this.getAccessToken(), this.timeout, "getAccessToken");
320
+ if (current && `Bearer ${current}` !== sentAuthorization) return true;
321
+ } catch {
322
+ return false;
323
+ }
324
+ }
325
+ if (!this.unauthorizedInFlight) {
326
+ const call = this.onUnauthorized;
327
+ const inFlight = (async () => {
328
+ try {
329
+ return await withTimeout(call(), this.timeout, "onUnauthorized");
330
+ } catch {
331
+ return false;
332
+ }
333
+ })().finally(() => {
334
+ if (this.unauthorizedInFlight === inFlight) this.unauthorizedInFlight = void 0;
335
+ });
336
+ this.unauthorizedInFlight = inFlight;
337
+ }
338
+ return this.unauthorizedInFlight;
339
+ }
340
+ buildUrl(path, params) {
341
+ const url = new URL(`${this.baseUrl}${path}`);
342
+ if (params) {
343
+ for (const [key, value] of Object.entries(params)) {
344
+ if (value !== void 0 && value !== null) {
345
+ url.searchParams.set(key, String(value));
346
+ }
347
+ }
348
+ }
349
+ return url.toString();
350
+ }
351
+ parseRetryAfter(response) {
352
+ const header = response.headers.get("Retry-After");
353
+ if (header) {
354
+ const seconds = Number(header);
355
+ if (!Number.isNaN(seconds) && seconds > 0) {
356
+ return seconds;
357
+ }
358
+ }
359
+ return 1;
360
+ }
361
+ async mapError(response) {
362
+ let body = {};
363
+ try {
364
+ body = await response.json();
365
+ } catch {
366
+ }
367
+ const envelope = body["error"];
368
+ const message = (typeof body["message"] === "string" ? body["message"] : void 0) ?? (typeof envelope?.message === "string" ? envelope.message : void 0) ?? response.statusText ?? "Request failed";
369
+ switch (response.status) {
370
+ case 400: {
371
+ const fieldErrors = body["errors"] ?? [];
372
+ return new ValidationError(message, fieldErrors);
373
+ }
374
+ case 401:
375
+ return new AuthenticationError(message);
376
+ case 403:
377
+ return new AuthorizationError(message);
378
+ case 404:
379
+ return new NotFoundError(message);
380
+ case 429: {
381
+ const retryAfter = this.parseRetryAfter(response);
382
+ return new RateLimitError(retryAfter, message);
383
+ }
384
+ default:
385
+ if (response.status >= 500) {
386
+ return new ServerError(message);
387
+ }
388
+ return new PlanesError(message, response.status, "unknown_error");
389
+ }
390
+ }
391
+ sleep(ms) {
392
+ return new Promise((resolve) => setTimeout(resolve, ms));
393
+ }
394
+ };
395
+ function timeoutSignal(ms) {
396
+ if (typeof AbortSignal.timeout === "function") {
397
+ return { signal: AbortSignal.timeout(ms), clear: () => void 0 };
398
+ }
399
+ const controller = new AbortController();
400
+ const timer = setTimeout(() => controller.abort(), ms);
401
+ return { signal: controller.signal, clear: () => clearTimeout(timer) };
402
+ }
403
+ function withTimeout(promise, ms, what) {
404
+ return new Promise((resolve, reject) => {
405
+ const timer = setTimeout(() => reject(new Error(`${what} did not settle within ${ms}ms`)), ms);
406
+ Promise.resolve(promise).then(
407
+ (value) => {
408
+ clearTimeout(timer);
409
+ resolve(value);
410
+ },
411
+ (err) => {
412
+ clearTimeout(timer);
413
+ reject(err);
414
+ }
415
+ );
416
+ });
417
+ }
418
+
419
+ // src/resources/base-resource.ts
420
+ var ApiResource = class {
421
+ constructor(http, basePath) {
422
+ this.http = http;
423
+ this.basePath = basePath;
424
+ }
425
+ };
426
+ var BaseResource = class extends ApiResource {
427
+ /**
428
+ * List entities with optional filters and pagination.
429
+ */
430
+ async list(params) {
431
+ return this.http.request({
432
+ method: "GET",
433
+ path: this.basePath,
434
+ params
435
+ });
436
+ }
437
+ /**
438
+ * Get a single entity by ID.
439
+ */
440
+ async get(id) {
441
+ return this.http.request({
442
+ method: "GET",
443
+ path: `${this.basePath}/${id}`
444
+ });
445
+ }
446
+ /**
447
+ * Create a new entity. Pass `idempotencyKey` (a UUID you keep for retries) to
448
+ * make a retry safe on routes that honor it (customers, opportunities, contacts,
449
+ * tasks): a repeat returns the first response and creates nothing.
450
+ */
451
+ async create(data, options) {
452
+ return this.http.request({
453
+ method: "POST",
454
+ path: this.basePath,
455
+ body: data,
456
+ ...options?.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}
457
+ });
458
+ }
459
+ /**
460
+ * Update an existing entity.
461
+ */
462
+ async update(id, data) {
463
+ return this.http.request({
464
+ method: "PATCH",
465
+ path: `${this.basePath}/${id}`,
466
+ body: data
467
+ });
468
+ }
469
+ /**
470
+ * Delete an entity by ID.
471
+ */
472
+ async delete(id) {
473
+ await this.http.request({
474
+ method: "DELETE",
475
+ path: `${this.basePath}/${id}`
476
+ });
477
+ }
478
+ };
479
+
480
+ // src/resources/query-params.ts
481
+ function toQueryParams(params) {
482
+ const out = {};
483
+ if (!params) return out;
484
+ for (const [key, value] of Object.entries(params)) {
485
+ if (value === void 0 || value === null) continue;
486
+ if (key === "customFields" && typeof value === "object" && !Array.isArray(value)) {
487
+ for (const [field, v] of Object.entries(value)) {
488
+ if (v !== void 0 && v !== null) out[`cf.${field}`] = String(v);
489
+ }
490
+ continue;
491
+ }
492
+ if (Array.isArray(value)) {
493
+ if (value.length === 0) continue;
494
+ out[key] = value.map(String).join(",");
495
+ } else {
496
+ out[key] = value;
497
+ }
498
+ }
499
+ return out;
500
+ }
501
+
502
+ // src/resources/opportunities.ts
503
+ var OpportunityResource = class extends BaseResource {
504
+ constructor(http) {
505
+ super(http, "/opportunities");
506
+ }
507
+ /**
508
+ * List opportunities. `tag_ids` is ANY-of and travels as one comma-separated
509
+ * query value (`?tag_ids=a,b`), which is what the API's filter schema parses.
510
+ */
511
+ async list(params) {
512
+ return this.http.request({
513
+ method: "GET",
514
+ path: this.basePath,
515
+ params: toQueryParams(params)
516
+ });
517
+ }
518
+ /**
519
+ * GET /opportunities/trade-options — the active trades a client can request
520
+ * (`requestedTradeIds` on create/update), sorted by name.
521
+ */
522
+ async tradeOptions() {
523
+ return this.http.request({
524
+ method: "GET",
525
+ path: `${this.basePath}/trade-options`
526
+ });
527
+ }
528
+ /** PUT /opportunities/{id} — partial update; stage moves go through workflow transitions. */
529
+ async update(id, data) {
530
+ return this.http.request({
531
+ method: "PUT",
532
+ path: `${this.basePath}/${id}`,
533
+ body: data
534
+ });
535
+ }
536
+ /** GET /opportunities/:id/transitions — the pipeline moves available from the current stage, for the caller's role. */
537
+ async listTransitions(id) {
538
+ return this.http.request({ method: "GET", path: `${this.basePath}/${id}/transitions` });
539
+ }
540
+ /**
541
+ * POST /opportunities/:id/transition — take one pipeline move, as the stage button does: required
542
+ * fields are checked, the move is logged, and the stage's automations run (they can send email).
543
+ */
544
+ async transition(id, data) {
545
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/transition`, body: data });
546
+ }
547
+ /** GET /opportunities/:id/workflow — the pipeline instance with its transition history (404 if none). */
548
+ async getWorkflow(id) {
549
+ return this.http.request({ method: "GET", path: `${this.basePath}/${id}/workflow` });
550
+ }
551
+ };
552
+
553
+ // src/resources/customers.ts
554
+ var CustomerResource = class extends BaseResource {
555
+ constructor(http) {
556
+ super(http, "/customers");
557
+ }
558
+ /**
559
+ * Update a customer. The API route is `PUT /customers/{id}` (not PATCH like
560
+ * the other resources), so this overrides the base verb; the body is still a
561
+ * partial — send only the fields to change. See `UpdateCustomerDto.address`
562
+ * for how a service address resolves to a property.
563
+ */
564
+ async update(id, data) {
565
+ return this.http.request({
566
+ method: "PUT",
567
+ path: `/customers/${id}`,
568
+ body: data
569
+ });
570
+ }
571
+ /**
572
+ * List customers. `tag_ids` is ANY-of and travels as one comma-separated
573
+ * query value (`?tag_ids=a,b`), which is what the API's filter schema parses.
574
+ */
575
+ async list(params) {
576
+ return this.http.request({
577
+ method: "GET",
578
+ path: this.basePath,
579
+ params: toQueryParams(params)
580
+ });
581
+ }
582
+ /**
583
+ * Fold a duplicate company (`loserId`) into a survivor (`winnerId`).
584
+ *
585
+ * Everything hanging off the loser moves to the winner, the winner's empty
586
+ * fields are filled from the loser, and the loser is soft-deleted with a
587
+ * resolvable pointer — `GET /customers/{loserId}` afterwards returns the
588
+ * winner's detail with a `mergedFrom` pointer, so a stored loser id keeps
589
+ * working. Irreversible; requires admin scope.
590
+ */
591
+ async merge(winnerId, loserId) {
592
+ return this.http.request({
593
+ method: "POST",
594
+ path: `/customers/${winnerId}/merge/${loserId}`
595
+ });
596
+ }
597
+ /**
598
+ * POST /customers/{id}/convert-to-company — turn a person customer into a
599
+ * company. The person becomes the company's primary contact (their email and
600
+ * phone, with do-not-contact and marketing opt-outs carried over). A customer
601
+ * that's already a company is a 409 `ALREADY_COMPANY`.
602
+ */
603
+ async convertToCompany(id, data = {}) {
604
+ return this.http.request({
605
+ method: "POST",
606
+ path: `${this.basePath}/${id}/convert-to-company`,
607
+ body: data
608
+ });
609
+ }
610
+ };
611
+
612
+ // src/resources/properties.ts
613
+ var PropertyResource = class extends ApiResource {
614
+ constructor(http) {
615
+ super(http, "/properties");
616
+ }
617
+ /** GET /customers/{customerId}/properties — paginated (`page`, `limit` ≤ 100). */
618
+ async list(customerId, params) {
619
+ return this.http.request({
620
+ method: "GET",
621
+ path: `/customers/${customerId}/properties`,
622
+ params: toQueryParams(params)
623
+ });
624
+ }
625
+ /** GET /properties/{id} — one property, without naming its customer. */
626
+ async get(id) {
627
+ return this.http.request({
628
+ method: "GET",
629
+ path: `${this.basePath}/${id}`
630
+ });
631
+ }
632
+ /** POST /customers/{customerId}/properties — the property inherits the customer's org path. */
633
+ async create(customerId, data) {
634
+ return this.http.request({
635
+ method: "POST",
636
+ path: `/customers/${customerId}/properties`,
637
+ body: data
638
+ });
639
+ }
640
+ /** PUT /customers/{customerId}/properties/{id} — partial update. */
641
+ async update(customerId, id, data) {
642
+ return this.http.request({
643
+ method: "PUT",
644
+ path: `/customers/${customerId}/properties/${id}`,
645
+ body: data
646
+ });
647
+ }
648
+ /** GET /customers/:customerId/properties/:id — one property, checked against its customer (404 if it isn't theirs). */
649
+ async getForCustomer(customerId, id) {
650
+ return this.http.request({
651
+ method: "GET",
652
+ path: `/customers/${customerId}/properties/${id}`
653
+ });
654
+ }
655
+ /** POST /properties/:id/geocode — queue a fresh geocode of the property's address. */
656
+ async geocode(id) {
657
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/geocode` });
658
+ }
659
+ /** DELETE /customers/{customerId}/properties/{id} — soft delete (204). */
660
+ async delete(customerId, id) {
661
+ await this.http.request({
662
+ method: "DELETE",
663
+ path: `/customers/${customerId}/properties/${id}`
664
+ });
665
+ }
666
+ };
667
+
668
+ // src/resources/calendar-events.ts
669
+ var CalendarEventResource = class extends BaseResource {
670
+ constructor(http) {
671
+ super(http, "/events");
672
+ }
673
+ async list(params) {
674
+ return this.http.request({
675
+ method: "GET",
676
+ path: this.basePath,
677
+ params: params ?? {}
678
+ });
679
+ }
680
+ /**
681
+ * PATCH /events/:id. For an occurrence of a recurring event, `editMode`
682
+ * picks which occurrences change (`this` when omitted — the server's
683
+ * default); it is ignored for one-time events.
684
+ */
685
+ async update(id, data, options = {}) {
686
+ return this.http.request({
687
+ method: "PATCH",
688
+ path: `${this.basePath}/${id}`,
689
+ params: { recurrence_edit_mode: options.editMode },
690
+ body: data
691
+ });
692
+ }
693
+ /**
694
+ * POST /events/:id/complete — marks the event completed and runs its "on
695
+ * complete" transition, best-effort. The event is completed even when the
696
+ * transition can't run; `workflow_trigger` says whether it fired, was
697
+ * skipped (none set, or `handled_by_pipeline_rule`: the pipeline's rule
698
+ * moves the record instead) or failed (with a reason).
699
+ */
700
+ async complete(id, body = {}) {
701
+ return this.http.request({
702
+ method: "POST",
703
+ path: `${this.basePath}/${id}/complete`,
704
+ body
705
+ });
706
+ }
707
+ /**
708
+ * POST /events/:id/cancel. For an occurrence of a recurring event, `editMode`
709
+ * picks which occurrences are cancelled (`this` when omitted). 409 if already
710
+ * cancelled; 422 for a completed event.
711
+ */
712
+ async cancel(id, options = {}) {
713
+ return this.http.request({
714
+ method: "POST",
715
+ path: `${this.basePath}/${id}/cancel`,
716
+ params: { recurrence_edit_mode: options.editMode }
717
+ });
718
+ }
719
+ /** POST /events/:id/participants — add a user, contact, crew or agent to the event. No invite is sent. */
720
+ async addParticipant(id, data) {
721
+ return this.http.request({
722
+ method: "POST",
723
+ path: `${this.basePath}/${id}/participants`,
724
+ body: data
725
+ });
726
+ }
727
+ /** PATCH /events/:id/participants/:participantId — set a participant's response. */
728
+ async updateParticipantStatus(id, participantId, status) {
729
+ return this.http.request({
730
+ method: "PATCH",
731
+ path: `${this.basePath}/${id}/participants/${participantId}`,
732
+ body: { status }
733
+ });
734
+ }
735
+ };
736
+
737
+ // src/resources/contracts.ts
738
+ var ContractResource = class extends BaseResource {
739
+ constructor(http) {
740
+ super(http, "/contracts");
741
+ }
742
+ /** POST /contracts/for-subject — a bare agreement for a customer or a service schedule (no opportunity, no line groups). */
743
+ async createForSubject(data) {
744
+ return this.http.request({ method: "POST", path: `${this.basePath}/for-subject`, body: data });
745
+ }
746
+ /** POST /contracts/flat — a contract on an opportunity with a manually entered total and a contract template, no estimates. */
747
+ async createFlat(data) {
748
+ return this.http.request({ method: "POST", path: `${this.basePath}/flat`, body: data });
749
+ }
750
+ /** POST /contracts/{id}/change-orders — a change order on a signed or fulfilled contract (409 otherwise). */
751
+ async createChangeOrder(id, data) {
752
+ return this.http.request({
753
+ method: "POST",
754
+ path: `${this.basePath}/${id}/change-orders`,
755
+ body: data
756
+ });
757
+ }
758
+ /**
759
+ * GET /contracts/{id}/change-orders — the change orders written against a
760
+ * contract, oldest first, each with its line groups. A change order has none
761
+ * of its own, so asking for one returns an empty list.
762
+ */
763
+ async listChangeOrders(id) {
764
+ return this.http.request({
765
+ method: "GET",
766
+ path: `${this.basePath}/${id}/change-orders`
767
+ });
768
+ }
769
+ /** POST /contracts/{id}/submit — submit for approval; auto-approved when under the tenant's threshold. */
770
+ async submit(id) {
771
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/submit` });
772
+ }
773
+ /** POST /contracts/{id}/approve — approve a contract pending approval (needs the approve grant). */
774
+ async approve(id) {
775
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/approve` });
776
+ }
777
+ /** POST /contracts/{id}/cancel — cancel a contract in any state before it's signed. */
778
+ async cancel(id) {
779
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/cancel` });
780
+ }
781
+ /** POST /contracts/{id}/reopen — return a kicked-back contract to draft for review and re-send. */
782
+ async reopen(id) {
783
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/reopen` });
784
+ }
785
+ /**
786
+ * POST /contracts/{id}/send — **emails the signer a "Review & Sign" link.**
787
+ * Snapshots the clauses and creates the signing token. An empty body
788
+ * addresses the customer; `signerContactId` sends it to that contact instead.
789
+ * The first send of a contract uses one unit of the tenant's e-signature
790
+ * allowance; a re-send doesn't. Not safe to retry blindly after a timeout: a
791
+ * repeat emails again.
792
+ */
793
+ async send(id, data = {}) {
794
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/send`, body: data });
795
+ }
796
+ /**
797
+ * GET /contracts/{id}/pdf — the contract PDF bytes. `type: 'signed'` returns
798
+ * the stored signed copy (404 until it's signed); otherwise a preview renders.
799
+ */
800
+ async downloadPdf(id, options = {}) {
801
+ return this.http.request({
802
+ method: "GET",
803
+ path: `${this.basePath}/${id}/pdf`,
804
+ params: options.type ? { type: options.type } : {},
805
+ headers: { Accept: "application/pdf" },
806
+ responseType: "arrayBuffer"
807
+ });
808
+ }
809
+ };
810
+
811
+ // src/resources/jobs.ts
812
+ var JobResource = class extends ApiResource {
813
+ constructor(http) {
814
+ super(http, "/jobs");
815
+ }
816
+ /** The jobs under one opportunity — the same route as `listForOpportunity()`. */
817
+ async list(opportunityId, params) {
818
+ return this.listForOpportunity(opportunityId, params);
819
+ }
820
+ /**
821
+ * List the jobs under one opportunity — `GET /opportunities/{opportunityId}/jobs`,
822
+ * the API's job list route. Default order is `created_at` desc;
823
+ * `sort_by: 'recent'` puts the calling user's most recently opened jobs first.
824
+ */
825
+ async listForOpportunity(opportunityId, params) {
826
+ return this.http.request({
827
+ method: "GET",
828
+ path: `/opportunities/${opportunityId}/jobs`,
829
+ params: toQueryParams(params)
830
+ });
831
+ }
832
+ /** GET /opportunities/{opportunityId}/jobs/{id} */
833
+ async get(opportunityId, id) {
834
+ return this.http.request({
835
+ method: "GET",
836
+ path: `/opportunities/${opportunityId}/jobs/${id}`
837
+ });
838
+ }
839
+ /**
840
+ * POST /opportunities/{opportunityId}/jobs — 422 WORKFLOW_NOT_CONFIGURED when
841
+ * the trade has no published job workflow (check `getTradeCoverage()` first).
842
+ */
843
+ async create(opportunityId, data) {
844
+ return this.http.request({
845
+ method: "POST",
846
+ path: `/opportunities/${opportunityId}/jobs`,
847
+ body: data
848
+ });
849
+ }
850
+ /** PUT /opportunities/{opportunityId}/jobs/{id} — partial update (status, notes). */
851
+ async update(opportunityId, id, data) {
852
+ return this.http.request({
853
+ method: "PUT",
854
+ path: `/opportunities/${opportunityId}/jobs/${id}`,
855
+ body: data
856
+ });
857
+ }
858
+ /** DELETE /opportunities/{opportunityId}/jobs/{id} — soft delete (204). */
859
+ async delete(opportunityId, id) {
860
+ await this.http.request({
861
+ method: "DELETE",
862
+ path: `/opportunities/${opportunityId}/jobs/${id}`
863
+ });
864
+ }
865
+ /**
866
+ * GET /jobs/trade-coverage — every active trade with whether a job can be
867
+ * created under it (a published job workflow resolves: the trade's own or the
868
+ * generic one). Check before creating a job to avoid a 422
869
+ * WORKFLOW_NOT_CONFIGURED. Readable by any role that can create jobs (403
870
+ * otherwise); carries no workflow details.
871
+ */
872
+ async getTradeCoverage() {
873
+ return this.http.request({
874
+ method: "GET",
875
+ path: "/jobs/trade-coverage"
876
+ });
877
+ }
878
+ /** GET /jobs/{id}/workflow — the job's pipeline instance with its transition history (404 if none). */
879
+ async getWorkflow(id) {
880
+ return this.http.request({ method: "GET", path: `${this.basePath}/${id}/workflow` });
881
+ }
882
+ /**
883
+ * POST /jobs/{id}/transition — take one pipeline move, as the stage button
884
+ * does: required fields are checked, the move is logged, and **the
885
+ * transition's actions run**. A tenant can attach actions that create or send
886
+ * an invoice, charge a saved card, send a contract, or send email, SMS or a
887
+ * webhook. Not safe to retry blindly after a timeout: check `getWorkflow()`
888
+ * first, because a repeat runs the actions again.
889
+ */
890
+ async transition(id, data) {
891
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/transition`, body: data });
892
+ }
893
+ /** GET /jobs/{id}/transitions — the pipeline moves available from the job's current stage, for the caller's role. */
894
+ async listTransitions(id) {
895
+ return this.http.request({
896
+ method: "GET",
897
+ path: `${this.basePath}/${id}/transitions`
898
+ });
899
+ }
900
+ };
901
+
902
+ // src/resources/estimates.ts
903
+ var EstimateResource = class extends ApiResource {
904
+ constructor(http) {
905
+ super(http, "/estimates");
906
+ }
907
+ /** GET /jobs/{jobId}/estimates — newest first, paginated (`page`, `limit` ≤ 100). */
908
+ async list(jobId, params) {
909
+ return this.http.request({
910
+ method: "GET",
911
+ path: `/jobs/${jobId}/estimates`,
912
+ params: toQueryParams(params)
913
+ });
914
+ }
915
+ /**
916
+ * Every estimate across all of one opportunity's jobs, in one request —
917
+ * `GET /opportunities/{opportunityId}/estimates`. Newest first; each row
918
+ * carries its `jobId`. Paginated with `page` / `limit` (max 100).
919
+ */
920
+ async listForOpportunity(opportunityId, params) {
921
+ return this.http.request({
922
+ method: "GET",
923
+ path: `/opportunities/${opportunityId}/estimates`,
924
+ params: toQueryParams(params)
925
+ });
926
+ }
927
+ /** GET /jobs/{jobId}/estimates/{id} — the estimate with its line items. */
928
+ async get(jobId, id) {
929
+ return this.http.request({
930
+ method: "GET",
931
+ path: `/jobs/${jobId}/estimates/${id}`
932
+ });
933
+ }
934
+ /** POST /jobs/{jobId}/estimates — optionally cloned from an estimate template. */
935
+ async create(jobId, data) {
936
+ return this.http.request({
937
+ method: "POST",
938
+ path: `/jobs/${jobId}/estimates`,
939
+ body: data
940
+ });
941
+ }
942
+ /** PUT /jobs/{jobId}/estimates/{id} — partial update (measurements, notes, discount, tax). */
943
+ async update(jobId, id, data) {
944
+ return this.http.request({
945
+ method: "PUT",
946
+ path: `/jobs/${jobId}/estimates/${id}`,
947
+ body: data
948
+ });
949
+ }
950
+ /** DELETE /jobs/{jobId}/estimates/{id} — soft delete (204). */
951
+ async delete(jobId, id) {
952
+ await this.http.request({
953
+ method: "DELETE",
954
+ path: `/jobs/${jobId}/estimates/${id}`
955
+ });
956
+ }
957
+ /** GET /estimates/{id}/workflow — the estimate's pipeline instance with its transition history (404 if none). */
958
+ async getWorkflow(id) {
959
+ return this.http.request({ method: "GET", path: `${this.basePath}/${id}/workflow` });
960
+ }
961
+ /**
962
+ * POST /estimates/{id}/transition — take one pipeline move. **The
963
+ * transition's actions run**, as for `jobs.transition()`: a tenant can attach
964
+ * actions that bill, charge, send a contract, or send email, SMS or a webhook.
965
+ * Not safe to retry blindly after a timeout: check `getWorkflow()` first.
966
+ */
967
+ async transition(id, data) {
968
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/transition`, body: data });
969
+ }
970
+ /**
971
+ * PUT /jobs/{jobId}/estimates/{id}/status — move the estimate's status (see
972
+ * `UpdateEstimateStatusDto` for the allowed moves). The route itself sends
973
+ * nothing and creates no contract or invoice; a tenant's webhooks or
974
+ * automations on the status change can.
975
+ */
976
+ async updateStatus(jobId, id, data) {
977
+ return this.http.request({
978
+ method: "PUT",
979
+ path: `/jobs/${jobId}/estimates/${id}/status`,
980
+ body: data
981
+ });
982
+ }
983
+ /** GET /estimates/{id}/transitions — the pipeline moves available from the estimate's current stage, for the caller's role. */
984
+ async listTransitions(id) {
985
+ return this.http.request({
986
+ method: "GET",
987
+ path: `${this.basePath}/${id}/transitions`
988
+ });
989
+ }
990
+ /**
991
+ * POST /jobs/{jobId}/estimates/{estimateId}/line-items — add a line item. With
992
+ * `materialCatalogId` or `tradeLaborItemId`, the catalog fills in description,
993
+ * unit and price. The estimate's subtotal and total are recalculated.
994
+ */
995
+ async createLineItem(jobId, estimateId, data) {
996
+ return this.http.request({
997
+ method: "POST",
998
+ path: `/jobs/${jobId}/estimates/${estimateId}/line-items`,
999
+ body: data
1000
+ });
1001
+ }
1002
+ /** PUT /jobs/{jobId}/estimates/{estimateId}/line-items/{id} — partial update; totals are recalculated. */
1003
+ async updateLineItem(jobId, estimateId, id, data) {
1004
+ return this.http.request({
1005
+ method: "PUT",
1006
+ path: `/jobs/${jobId}/estimates/${estimateId}/line-items/${id}`,
1007
+ body: data
1008
+ });
1009
+ }
1010
+ /** DELETE /jobs/{jobId}/estimates/{estimateId}/line-items/{id} — totals are recalculated. */
1011
+ async deleteLineItem(jobId, estimateId, id) {
1012
+ await this.http.request({
1013
+ method: "DELETE",
1014
+ path: `/jobs/${jobId}/estimates/${estimateId}/line-items/${id}`
1015
+ });
1016
+ }
1017
+ /** PUT /jobs/{jobId}/estimates/{estimateId}/line-items/reorder — set each item's `sortOrder` (and optionally `section`) in one call. */
1018
+ async reorderLineItems(jobId, estimateId, data) {
1019
+ return this.http.request({
1020
+ method: "PUT",
1021
+ path: `/jobs/${jobId}/estimates/${estimateId}/line-items/reorder`,
1022
+ body: data
1023
+ });
1024
+ }
1025
+ };
1026
+
1027
+ // src/resources/invoices.ts
1028
+ var InvoiceResource = class extends BaseResource {
1029
+ constructor(http) {
1030
+ super(http, "/admin/invoices");
1031
+ }
1032
+ /** List invoices, newest first. Each row carries the customer's `customerName`. */
1033
+ async list(params) {
1034
+ return this.http.request({
1035
+ method: "GET",
1036
+ path: this.basePath,
1037
+ params
1038
+ });
1039
+ }
1040
+ /**
1041
+ * GET /admin/invoices/:id — the invoice with its line items, payments
1042
+ * (including any `needs_review` payment) and `payLink` state.
1043
+ */
1044
+ async get(id) {
1045
+ return this.http.request({
1046
+ method: "GET",
1047
+ path: `${this.basePath}/${id}`
1048
+ });
1049
+ }
1050
+ /**
1051
+ * POST /admin/invoices/:id/pay-link — issue a fresh durable pay link for a
1052
+ * `sent` or `partially_paid` invoice (Send Invoice grant) and return its URL,
1053
+ * e.g. to share by text. Rotates: the previously emailed link stops working.
1054
+ * Any other status → 409 `INVOICE_NOT_PAYABLE`.
1055
+ */
1056
+ async createPayLink(id) {
1057
+ return this.http.request({
1058
+ method: "POST",
1059
+ path: `${this.basePath}/${id}/pay-link`
1060
+ });
1061
+ }
1062
+ /**
1063
+ * GET /admin/invoices/:id/pdf — the invoice PDF bytes (Read Invoice grant).
1064
+ * A sent invoice returns the copy stored when it was sent; a draft renders on
1065
+ * demand with a DRAFT watermark.
1066
+ */
1067
+ async downloadPdf(id) {
1068
+ return this.http.request({
1069
+ method: "GET",
1070
+ path: `${this.basePath}/${id}/pdf`,
1071
+ headers: { Accept: "application/pdf" },
1072
+ responseType: "arrayBuffer"
1073
+ });
1074
+ }
1075
+ /**
1076
+ * GET /admin/invoices/overdue — sent / partially paid invoices with a balance
1077
+ * past their due date, most overdue first, each with `daysOverdue` and the
1078
+ * last overdue offset reached (E56-F8-S2). Read Invoice.
1079
+ */
1080
+ async listOverdue(params) {
1081
+ return this.http.request({
1082
+ method: "GET",
1083
+ path: `${this.basePath}/overdue`,
1084
+ params
1085
+ });
1086
+ }
1087
+ /** GET /admin/invoices/{invoiceId}/payments — every payment recorded against the invoice (Read Payment). */
1088
+ async listPayments(invoiceId) {
1089
+ return this.http.request({
1090
+ method: "GET",
1091
+ path: `${this.basePath}/${invoiceId}/payments`
1092
+ });
1093
+ }
1094
+ /**
1095
+ * GET /admin/payments/recording-settings — the tenant's resolved
1096
+ * payment-recording settings (whether manual recording is on, and which
1097
+ * methods). Read Invoice.
1098
+ */
1099
+ async getPaymentRecordingSettings() {
1100
+ return this.http.request({
1101
+ method: "GET",
1102
+ path: "/admin/payments/recording-settings"
1103
+ });
1104
+ }
1105
+ /** GET /admin/invoices/overdue/summary — `{ count, total }` of every overdue invoice. Read Invoice. */
1106
+ async overdueSummary() {
1107
+ return this.http.request({
1108
+ method: "GET",
1109
+ path: `${this.basePath}/overdue/summary`
1110
+ });
1111
+ }
1112
+ };
1113
+
1114
+ // src/resources/inventory.ts
1115
+ var InventoryResource = class extends BaseResource {
1116
+ constructor(http) {
1117
+ super(http, "/admin/inventory/items");
1118
+ }
1119
+ async list(params) {
1120
+ return this.http.request({
1121
+ method: "GET",
1122
+ path: this.basePath,
1123
+ params: toQueryParams(params)
1124
+ });
1125
+ }
1126
+ /** PUT /admin/inventory/items/{id} — partial update. */
1127
+ async update(id, data) {
1128
+ return this.http.request({
1129
+ method: "PUT",
1130
+ path: `${this.basePath}/${id}`,
1131
+ body: data
1132
+ });
1133
+ }
1134
+ // ---- Material used on a job (E64-S9). The routes live under /jobs/{jobId}. ----
1135
+ /**
1136
+ * POST /jobs/{jobId}/consumption — record stock drawn from a location for a
1137
+ * job. Each line lowers that location's on-hand quantity.
1138
+ */
1139
+ async recordJobConsumption(jobId, data) {
1140
+ return this.http.request({
1141
+ method: "POST",
1142
+ path: `/jobs/${jobId}/consumption`,
1143
+ body: data
1144
+ });
1145
+ }
1146
+ /**
1147
+ * GET /jobs/{jobId}/consumption — one page of the job's consume and return
1148
+ * movements (newest first by default), the job's totals across every page,
1149
+ * and page metadata. The rows are under `items`, not `data`.
1150
+ */
1151
+ async listJobConsumption(jobId, params) {
1152
+ return this.http.request({
1153
+ method: "GET",
1154
+ path: `/jobs/${jobId}/consumption`,
1155
+ params: toQueryParams(params)
1156
+ });
1157
+ }
1158
+ /** POST /jobs/{jobId}/return — put unused stock from a job back into a location. */
1159
+ async returnFromJob(jobId, data) {
1160
+ return this.http.request({
1161
+ method: "POST",
1162
+ path: `/jobs/${jobId}/return`,
1163
+ body: data
1164
+ });
1165
+ }
1166
+ /** GET /jobs/{jobId}/material-variance — estimated vs actual material for the job. */
1167
+ async getJobMaterialVariance(jobId) {
1168
+ return this.http.request({
1169
+ method: "GET",
1170
+ path: `/jobs/${jobId}/material-variance`
1171
+ });
1172
+ }
1173
+ };
1174
+
1175
+ // src/resources/contacts.ts
1176
+ var ContactChannelResource = class {
1177
+ constructor(http, contactId) {
1178
+ this.http = http;
1179
+ this.contactId = contactId;
1180
+ }
1181
+ /** Returns `{ channel, duplicateOf }` — `duplicateOf` is the dedup signal. */
1182
+ async create(data) {
1183
+ return this.http.request({
1184
+ method: "POST",
1185
+ path: `/contacts/${this.contactId}/channels`,
1186
+ body: data
1187
+ });
1188
+ }
1189
+ async update(channelId, data) {
1190
+ return this.http.request({
1191
+ method: "PATCH",
1192
+ path: `/contacts/${this.contactId}/channels/${channelId}`,
1193
+ body: data
1194
+ });
1195
+ }
1196
+ async delete(channelId) {
1197
+ await this.http.request({
1198
+ method: "DELETE",
1199
+ path: `/contacts/${this.contactId}/channels/${channelId}`
1200
+ });
1201
+ }
1202
+ };
1203
+ var ContactResource = class extends BaseResource {
1204
+ constructor(http) {
1205
+ super(http, "/contacts");
1206
+ }
1207
+ /**
1208
+ * List contacts. Typed against the real filter schema (customer_id /
1209
+ * property_id / q / sort_by / sort_order / page / limit / include) — the base
1210
+ * `list` would accept any key and let a typo reach the server as a 400.
1211
+ * `include: ['channels', 'links']` attaches each row's channels and active
1212
+ * links in the same response.
1213
+ */
1214
+ async list(params) {
1215
+ return this.http.request({
1216
+ method: "GET",
1217
+ path: this.basePath,
1218
+ params: toQueryParams(params)
1219
+ });
1220
+ }
1221
+ async merge(winnerId, loserId) {
1222
+ return this.http.request({
1223
+ method: "POST",
1224
+ path: `/contacts/${winnerId}/merge/${loserId}`
1225
+ });
1226
+ }
1227
+ /** GET /contacts/roles — the distinct roles in use on active links, for a role picker. */
1228
+ async listRoles() {
1229
+ return this.http.request({ method: "GET", path: "/contacts/roles" });
1230
+ }
1231
+ /** GET /contacts/:id/links — every link, active and ended (history). `get()` returns active links only. */
1232
+ async listLinks(contactId) {
1233
+ return this.http.request({ method: "GET", path: `/contacts/${contactId}/links` });
1234
+ }
1235
+ /** POST /contacts/:id/links — link the contact to a customer or property. */
1236
+ async addLink(contactId, data) {
1237
+ return this.http.request({ method: "POST", path: `/contacts/${contactId}/links`, body: data });
1238
+ }
1239
+ /** PATCH /contacts/:id/links/:linkId — change role/primary, or end the link (`endedAt`). */
1240
+ async updateLink(contactId, linkId, data) {
1241
+ return this.http.request({
1242
+ method: "PATCH",
1243
+ path: `/contacts/${contactId}/links/${linkId}`,
1244
+ body: data
1245
+ });
1246
+ }
1247
+ /** POST /contacts/:id/workflow/start — opt the contact into the relationship pipeline (409 if started). */
1248
+ async startWorkflow(contactId) {
1249
+ return this.http.request({ method: "POST", path: `/contacts/${contactId}/workflow/start` });
1250
+ }
1251
+ /** GET /contacts/:id/workflow — current stage and the transitions available from it. */
1252
+ async getWorkflow(contactId) {
1253
+ return this.http.request({ method: "GET", path: `/contacts/${contactId}/workflow` });
1254
+ }
1255
+ /** POST /contacts/:id/workflow/transitions/:transitionId — 422 for an invalid move or unmet required fields. */
1256
+ async transition(contactId, transitionId) {
1257
+ return this.http.request({
1258
+ method: "POST",
1259
+ path: `/contacts/${contactId}/workflow/transitions/${transitionId}`,
1260
+ body: {}
1261
+ });
1262
+ }
1263
+ /** GET /contacts/:id/workflow/history */
1264
+ async getWorkflowHistory(contactId) {
1265
+ return this.http.request({ method: "GET", path: `/contacts/${contactId}/workflow/history` });
1266
+ }
1267
+ channels(contactId) {
1268
+ return new ContactChannelResource(this.http, contactId);
1269
+ }
1270
+ };
1271
+
1272
+ // src/resources/activities.ts
1273
+ var ActivityResource = class {
1274
+ constructor(http) {
1275
+ this.http = http;
1276
+ }
1277
+ async create(data) {
1278
+ return this.http.request({
1279
+ method: "POST",
1280
+ path: "/activities",
1281
+ body: data
1282
+ });
1283
+ }
1284
+ async list(params) {
1285
+ return this.http.request({
1286
+ method: "GET",
1287
+ path: "/activities",
1288
+ params
1289
+ });
1290
+ }
1291
+ async listForEntity(entityType, entityId, params) {
1292
+ return this.http.request({
1293
+ method: "GET",
1294
+ path: `/${entityType}/${entityId}/activities`,
1295
+ params
1296
+ });
1297
+ }
1298
+ };
1299
+
1300
+ // src/resources/communications.ts
1301
+ var CommunicationsResource = class {
1302
+ constructor(http) {
1303
+ this.http = http;
1304
+ }
1305
+ async log(data) {
1306
+ return this.http.request({
1307
+ method: "POST",
1308
+ path: "/communications",
1309
+ body: data
1310
+ });
1311
+ }
1312
+ async list(params) {
1313
+ return this.http.request({
1314
+ method: "GET",
1315
+ path: "/communications",
1316
+ params
1317
+ });
1318
+ }
1319
+ async get(id) {
1320
+ return this.http.request({
1321
+ method: "GET",
1322
+ path: `/communications/${id}`
1323
+ });
1324
+ }
1325
+ async link(id, data) {
1326
+ return this.http.request({
1327
+ method: "POST",
1328
+ path: `/communications/${id}/link`,
1329
+ body: data
1330
+ });
1331
+ }
1332
+ };
1333
+
1334
+ // src/resources/conversations.ts
1335
+ var ConversationsResource = class {
1336
+ constructor(http) {
1337
+ this.http = http;
1338
+ }
1339
+ async log(data) {
1340
+ return this.http.request({ method: "POST", path: "/conversations", body: data });
1341
+ }
1342
+ async list(params) {
1343
+ return this.http.request({ method: "GET", path: "/conversations", params });
1344
+ }
1345
+ /** The review queue: `list()` pinned to `match_status: 'needs_review'`. */
1346
+ async reviewQueue(params) {
1347
+ return this.list({ ...params, match_status: "needs_review" });
1348
+ }
1349
+ async get(id) {
1350
+ return this.http.request({ method: "GET", path: `/conversations/${encodeURIComponent(id)}` });
1351
+ }
1352
+ async update(id, data) {
1353
+ return this.http.request({ method: "PATCH", path: `/conversations/${encodeURIComponent(id)}`, body: data });
1354
+ }
1355
+ async delete(id) {
1356
+ await this.http.request({ method: "DELETE", path: `/conversations/${encodeURIComponent(id)}` });
1357
+ }
1358
+ async link(id, data) {
1359
+ return this.http.request({ method: "POST", path: `/conversations/${encodeURIComponent(id)}/links`, body: data });
1360
+ }
1361
+ async unlink(id, linkId) {
1362
+ return this.http.request({
1363
+ method: "DELETE",
1364
+ path: `/conversations/${encodeURIComponent(id)}/links/${encodeURIComponent(linkId)}`
1365
+ });
1366
+ }
1367
+ async resolve(id, data) {
1368
+ return this.http.request({ method: "POST", path: `/conversations/${encodeURIComponent(id)}/resolve`, body: data });
1369
+ }
1370
+ async getInternalDomains() {
1371
+ return this.http.request({ method: "GET", path: "/conversations/settings/internal-domains" });
1372
+ }
1373
+ /** Requires an admin: the server checks `Update` on `Subject.Tenant` (tenant-wide matching config), not `Subject.Conversation`. */
1374
+ async setInternalDomains(data) {
1375
+ return this.http.request({ method: "PUT", path: "/conversations/settings/internal-domains", body: data });
1376
+ }
1377
+ /**
1378
+ * E57-F2-S4 — disconnect the CALLER's own Circleback connection (Update
1379
+ * Conversation). Another user's connection id is a 404. Connecting is the
1380
+ * interactive browser OAuth flow (Settings → Conversations), not an SDK call.
1381
+ */
1382
+ async disconnectCircleback(data) {
1383
+ return this.http.request({
1384
+ method: "POST",
1385
+ path: "/conversations/sources/circleback/disconnect",
1386
+ body: data
1387
+ });
1388
+ }
1389
+ /**
1390
+ * E57-F2-S8 — pull one company's meetings from every active teammate's
1391
+ * connected source (Update Conversation). 202, runs in the background.
1392
+ * 404 for a company you can't see; 409 `NO_SOURCES` when nobody has one.
1393
+ */
1394
+ async pull(data) {
1395
+ return this.http.request({ method: "POST", path: "/conversations/pull", body: data });
1396
+ }
1397
+ /**
1398
+ * E57-F2-S9 — whether a Pull has finished: pass the `job_ids` `pull()`
1399
+ * returned (1–50). Update Conversation, like `pull()`. 404
1400
+ * `PULL_NOT_FOUND` when none of them is readable (expired after ~2h,
1401
+ * unknown) — treat that as settled.
1402
+ */
1403
+ async getPullStatus(jobIds) {
1404
+ return this.http.request({
1405
+ method: "GET",
1406
+ path: "/conversations/pull/status",
1407
+ params: { job_ids: jobIds.join(",") }
1408
+ });
1409
+ }
1410
+ /** E57-F2-S8 — sync the caller's OWN Circleback connection now (deduplicated). 409 `NO_CONNECTION` when they have none. */
1411
+ async syncNow() {
1412
+ return this.http.request({ method: "POST", path: "/conversations/sources/circleback/sync-now" });
1413
+ }
1414
+ /** E57-F2-S8 — the caller's own connection, `has_sources`, and (admins only) the roster. */
1415
+ async syncStatus() {
1416
+ return this.http.request({ method: "GET", path: "/conversations/sync-status" });
1417
+ }
1418
+ /**
1419
+ * E57-F4-S1 — a synced meeting's transcript, fetched live from the meeting
1420
+ * recorder (never stored by Planes; the response is `Cache-Control:
1421
+ * no-store`). Read Conversation, plus the tenant's transcript-access rule:
1422
+ * 403 `TRANSCRIPT_OWNER_ONLY` under `owner` for a non-owner; 409
1423
+ * `TRANSCRIPT_SOURCE_UNAVAILABLE` (`owner_name` says who must reconnect) or
1424
+ * `TRANSCRIPT_NOT_AVAILABLE` (not a synced meeting); 404 when you can't see
1425
+ * the conversation. `segments: []` = no transcript yet.
1426
+ */
1427
+ async getTranscript(id) {
1428
+ return this.http.request({
1429
+ method: "GET",
1430
+ path: `/conversations/${encodeURIComponent(id)}/transcript`
1431
+ });
1432
+ }
1433
+ /** E57-F4-S1 — who can view transcripts: `owner` (default) or `viewers`. Read Conversation. */
1434
+ async getTranscriptAccess() {
1435
+ return this.http.request({ method: "GET", path: "/conversations/settings/transcript-access" });
1436
+ }
1437
+ /** E57-F4-S1 — requires an admin: the server checks `Update` on `Subject.Tenant`. */
1438
+ async setTranscriptAccess(value) {
1439
+ return this.http.request({
1440
+ method: "PUT",
1441
+ path: "/conversations/settings/transcript-access",
1442
+ body: { transcript_access: value }
1443
+ });
1444
+ }
1445
+ };
1446
+
1447
+ // src/resources/gmail.ts
1448
+ var GmailResource = class {
1449
+ constructor(http) {
1450
+ this.http = http;
1451
+ }
1452
+ /**
1453
+ * Send an email RIGHT NOW from the connected user's real Gmail address.
1454
+ * Hits `POST /admin/integrations/google/gmail/send` — final per Task 4
1455
+ * (`apps/api/src/modules/integrations/google/google-connection.controller.ts`).
1456
+ */
1457
+ async send(data) {
1458
+ return this.http.request({
1459
+ method: "POST",
1460
+ path: "/admin/integrations/google/gmail/send",
1461
+ body: data
1462
+ });
1463
+ }
1464
+ };
1465
+
1466
+ // src/resources/documents.ts
1467
+ var DocumentsResource = class {
1468
+ constructor(http) {
1469
+ this.http = http;
1470
+ }
1471
+ /** Attach an external (link-only) document — e.g. a Google Drive link — to a record. */
1472
+ async attachExternal(data) {
1473
+ return this.http.request({
1474
+ method: "POST",
1475
+ path: "/documents/external",
1476
+ body: data
1477
+ });
1478
+ }
1479
+ /** Documents filed directly on one record (uploaded + external), newest first. */
1480
+ async listForEntity(entityType, entityId) {
1481
+ return this.http.request({
1482
+ method: "GET",
1483
+ path: `/${entityType}/${entityId}/documents`
1484
+ });
1485
+ }
1486
+ };
1487
+
1488
+ // src/resources/tags.ts
1489
+ var TagResource = class extends ApiResource {
1490
+ constructor(http) {
1491
+ super(http, "/tags");
1492
+ }
1493
+ /** GET /tags */
1494
+ async list(params) {
1495
+ return this.http.request({
1496
+ method: "GET",
1497
+ path: this.basePath,
1498
+ params
1499
+ });
1500
+ }
1501
+ /** POST /tags — 409 on a case-insensitive duplicate name. */
1502
+ async create(data) {
1503
+ return this.http.request({ method: "POST", path: this.basePath, body: data });
1504
+ }
1505
+ /** PATCH /tags/:id — rename / recolor; 409 on a case-insensitive duplicate name. */
1506
+ async update(id, data) {
1507
+ return this.http.request({ method: "PATCH", path: `${this.basePath}/${id}`, body: data });
1508
+ }
1509
+ /** DELETE /tags/:id — cascades the tag off every record. */
1510
+ async delete(id) {
1511
+ await this.http.request({ method: "DELETE", path: `${this.basePath}/${id}` });
1512
+ }
1513
+ /**
1514
+ * POST /tags/:winnerId/merge/:loserId — fold a duplicate tag into another: records
1515
+ * move to the winner (`retagged`), duplicates are dropped (`dropped`), and the
1516
+ * loser is deleted. Irreversible.
1517
+ */
1518
+ async merge(winnerId, loserId) {
1519
+ return this.http.request({ method: "POST", path: `${this.basePath}/${winnerId}/merge/${loserId}` });
1520
+ }
1521
+ /** `TagsService.setEntityTags()` returns the final tag set wrapped in `{ tags }`. */
1522
+ async setEntityTags(entityType, entityId, data) {
1523
+ return this.http.request({
1524
+ method: "PUT",
1525
+ path: `/entities/${entityType}/${entityId}/tags`,
1526
+ body: data
1527
+ });
1528
+ }
1529
+ /**
1530
+ * POST /entities/:type/:id/tags — add ONE tag, keeping the record's other tags.
1531
+ * Safe to call concurrently with other tag changes on the same record (unlike
1532
+ * read-modify-write through `setEntityTags()`). Adding a tag the record already
1533
+ * carries is a no-op. Returns the record's full tag set.
1534
+ */
1535
+ async addEntityTag(entityType, entityId, ref) {
1536
+ const body = ref.tagId !== void 0 ? { tag_id: ref.tagId } : { tag_name: ref.tagName };
1537
+ return this.http.request({
1538
+ method: "POST",
1539
+ path: `/entities/${entityType}/${entityId}/tags`,
1540
+ body
1541
+ });
1542
+ }
1543
+ /**
1544
+ * DELETE /entities/:type/:id/tags/:tagId — remove ONE tag, keeping the rest.
1545
+ * Removing a tag the record doesn't carry is a no-op. Returns the record's
1546
+ * full tag set.
1547
+ */
1548
+ async removeEntityTag(entityType, entityId, tagId) {
1549
+ return this.http.request({
1550
+ method: "DELETE",
1551
+ path: `/entities/${entityType}/${entityId}/tags/${tagId}`
1552
+ });
1553
+ }
1554
+ async getEntityTags(entityType, entityId) {
1555
+ return this.http.request({
1556
+ method: "GET",
1557
+ path: `/entities/${entityType}/${entityId}/tags`
1558
+ });
1559
+ }
1560
+ async getEntities(tagId, params) {
1561
+ return this.http.request({
1562
+ method: "GET",
1563
+ path: `/tags/${tagId}/entities`,
1564
+ params
1565
+ });
1566
+ }
1567
+ };
1568
+
1569
+ // src/resources/lists.ts
1570
+ var ListsResource = class extends ApiResource {
1571
+ constructor(http) {
1572
+ super(http, "/lists");
1573
+ }
1574
+ /** GET /lists — every list, newest first, each with `member_count`. A bare array. */
1575
+ async list() {
1576
+ return this.http.request({ method: "GET", path: this.basePath });
1577
+ }
1578
+ /**
1579
+ * GET /lists/filter-fields — the standard fields, their types and the operators
1580
+ * each accepts for a smart list of this entity type, and whether custom fields
1581
+ * are accepted (E66-S3). A save that breaks these rules is a 400.
1582
+ */
1583
+ async filterFields(entityType) {
1584
+ return this.http.request({
1585
+ method: "GET",
1586
+ path: `${this.basePath}/filter-fields`,
1587
+ params: { entity_type: entityType }
1588
+ });
1589
+ }
1590
+ /** GET /lists/:id — one list with an on-demand `member_count`. */
1591
+ async get(id) {
1592
+ return this.http.request({ method: "GET", path: `${this.basePath}/${id}` });
1593
+ }
1594
+ /** POST /lists */
1595
+ async create(data) {
1596
+ return this.http.request({ method: "POST", path: this.basePath, body: data });
1597
+ }
1598
+ /** PATCH /lists/:id — rename, or replace a smart list's definition. */
1599
+ async update(id, data) {
1600
+ return this.http.request({ method: "PATCH", path: `${this.basePath}/${id}`, body: data });
1601
+ }
1602
+ /** DELETE /lists/:id — soft delete; the records on the list are untouched. */
1603
+ async delete(id) {
1604
+ await this.http.request({ method: "DELETE", path: `${this.basePath}/${id}` });
1605
+ }
1606
+ /** POST /lists/:id/members — static lists only; idempotent on duplicates. */
1607
+ async addMembers(id, members) {
1608
+ return this.http.request({
1609
+ method: "POST",
1610
+ path: `${this.basePath}/${id}/members`,
1611
+ body: { members }
1612
+ });
1613
+ }
1614
+ /** DELETE /lists/:id/members — static lists only. */
1615
+ async removeMembers(id, members) {
1616
+ return this.http.request({
1617
+ method: "DELETE",
1618
+ path: `${this.basePath}/${id}/members`,
1619
+ body: { members }
1620
+ });
1621
+ }
1622
+ /** GET /lists/:id/recipients — people (audience, contact and customer lists), with consent. */
1623
+ async getRecipients(id, params) {
1624
+ return this.http.request({
1625
+ method: "GET",
1626
+ path: `${this.basePath}/${id}/recipients`,
1627
+ params
1628
+ });
1629
+ }
1630
+ /** POST /lists/:id/export — queues a CSV export; a notification links the file when it's ready. */
1631
+ async export(id, options) {
1632
+ return this.http.request({
1633
+ method: "POST",
1634
+ path: `${this.basePath}/${id}/export`,
1635
+ body: options ?? {}
1636
+ });
1637
+ }
1638
+ };
1639
+
1640
+ // src/resources/lead-sources.ts
1641
+ var LeadSourcesResource = class extends ApiResource {
1642
+ constructor(http) {
1643
+ super(http, "/lead-sources");
1644
+ }
1645
+ /** GET /lead-sources — active ones by default, in display order. */
1646
+ async list(options) {
1647
+ const res = await this.http.request({
1648
+ method: "GET",
1649
+ path: this.basePath,
1650
+ ...options?.includeInactive ? { params: { includeInactive: "true" } } : {}
1651
+ });
1652
+ return res.data;
1653
+ }
1654
+ /** POST /lead-sources — 409 on a duplicate key. */
1655
+ async create(data) {
1656
+ const res = await this.http.request({ method: "POST", path: this.basePath, body: data });
1657
+ return res.data;
1658
+ }
1659
+ /** PATCH /lead-sources/:id — label, active flag or order; the key can't change. */
1660
+ async update(id, data) {
1661
+ const res = await this.http.request({
1662
+ method: "PATCH",
1663
+ path: `${this.basePath}/${id}`,
1664
+ body: data
1665
+ });
1666
+ return res.data;
1667
+ }
1668
+ /** DELETE /lead-sources/:id — soft delete. */
1669
+ async delete(id) {
1670
+ await this.http.request({ method: "DELETE", path: `${this.basePath}/${id}` });
1671
+ }
1672
+ };
1673
+
1674
+ // src/resources/tasks.ts
1675
+ var TaskResource = class extends ApiResource {
1676
+ constructor(http) {
1677
+ super(http, "/tasks");
1678
+ }
1679
+ async list(params) {
1680
+ return this.http.request({
1681
+ method: "GET",
1682
+ path: this.basePath,
1683
+ params
1684
+ });
1685
+ }
1686
+ /** GET /tasks/:id */
1687
+ async get(id) {
1688
+ return this.http.request({ method: "GET", path: `${this.basePath}/${id}` });
1689
+ }
1690
+ /** POST /tasks. Pass `idempotencyKey` to make a retry safe (E64-S6). */
1691
+ async create(data, options) {
1692
+ return this.http.request({
1693
+ method: "POST",
1694
+ path: this.basePath,
1695
+ body: data,
1696
+ ...options?.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}
1697
+ });
1698
+ }
1699
+ /** PATCH /tasks/:id — non-terminal fields only; terminal status changes use the action methods. */
1700
+ async update(id, data) {
1701
+ return this.http.request({ method: "PATCH", path: `${this.basePath}/${id}`, body: data });
1702
+ }
1703
+ /**
1704
+ * POST /tasks/:id/complete — fires the linked workflow transition (best-effort).
1705
+ * The task always completes; `workflow_trigger` says whether the next step ran.
1706
+ */
1707
+ async complete(id) {
1708
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/complete` });
1709
+ }
1710
+ /** POST /tasks/:id/cancel */
1711
+ async cancel(id) {
1712
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/cancel` });
1713
+ }
1714
+ /** POST /tasks/:id/reopen — the sanctioned resurrect of a completed/cancelled task. */
1715
+ async reopen(id) {
1716
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/reopen` });
1717
+ }
1718
+ };
1719
+
1720
+ // src/resources/record-views.ts
1721
+ var RecordViewsResource = class {
1722
+ constructor(http) {
1723
+ this.http = http;
1724
+ this.basePath = "/record-views";
1725
+ }
1726
+ /** POST /record-views — record that the calling user opened this record. Resolves on 204. */
1727
+ async touch(input) {
1728
+ await this.http.request({ method: "POST", path: this.basePath, body: input });
1729
+ }
1730
+ /** GET /record-views/recent — the calling user's most recently viewed records, newest first. */
1731
+ async recent(params) {
1732
+ return this.http.request({
1733
+ method: "GET",
1734
+ path: `${this.basePath}/recent`,
1735
+ params: toQueryParams(params)
1736
+ });
1737
+ }
1738
+ };
1739
+
1740
+ // src/resources/modules.ts
1741
+ var ModulesResource = class {
1742
+ constructor(http) {
1743
+ this.http = http;
1744
+ this.basePath = "/modules";
1745
+ }
1746
+ /** GET /modules — one entry per registered module key, in canonical order. */
1747
+ async list() {
1748
+ const res = await this.http.request({
1749
+ method: "GET",
1750
+ path: this.basePath
1751
+ });
1752
+ return res.data;
1753
+ }
1754
+ };
1755
+
1756
+ // src/resources/plan.ts
1757
+ var PlanResource = class {
1758
+ constructor(http) {
1759
+ this.http = http;
1760
+ this.basePath = "/plan";
1761
+ }
1762
+ /** GET /plan — plan, billing status and the plan's ceiling. */
1763
+ async get() {
1764
+ const res = await this.http.request({
1765
+ method: "GET",
1766
+ path: this.basePath
1767
+ });
1768
+ return res.data;
1769
+ }
1770
+ };
1771
+
1772
+ // src/resources/me.ts
1773
+ var MeResource = class {
1774
+ constructor(http) {
1775
+ this.http = http;
1776
+ this.basePath = "/me";
1777
+ }
1778
+ /**
1779
+ * GET /me/abilities — the caller's effective ability: for an API key, the key
1780
+ * role intersected with its acting agent's live role (`actingRole`).
1781
+ */
1782
+ async abilities() {
1783
+ return this.http.request({
1784
+ method: "GET",
1785
+ path: `${this.basePath}/abilities`
1786
+ });
1787
+ }
1788
+ };
1789
+
1790
+ // src/resources/roles.ts
1791
+ var RolesResource = class {
1792
+ constructor(http) {
1793
+ this.http = http;
1794
+ this.basePath = "/roles";
1795
+ }
1796
+ /** GET /roles — every role (not `system_agent`) with user and change counts. */
1797
+ async list() {
1798
+ return this.http.request({ method: "GET", path: this.basePath });
1799
+ }
1800
+ /** GET /roles/:key — one role's permission matrix, summary and grant version. */
1801
+ async get(key) {
1802
+ return this.http.request({
1803
+ method: "GET",
1804
+ path: `${this.basePath}/${encodeURIComponent(key)}`
1805
+ });
1806
+ }
1807
+ /**
1808
+ * PUT /roles/:key/grants — sparse per-cell changes, all validated before any
1809
+ * is written. 422 `GRANT_REQUIRED` / `GRANT_NOT_DELEGABLE` for locked cells,
1810
+ * `CONFIRMATION_REQUIRED` when a money action is granted without
1811
+ * `confirm: true` + `reason`, `ROLE_NOT_TUNABLE` for admin; 409
1812
+ * `ROLE_VERSION_CONFLICT` on a stale `baseVersion`. Returns the updated role.
1813
+ */
1814
+ async updateGrants(key, body) {
1815
+ return this.http.request({
1816
+ method: "PUT",
1817
+ path: `${this.basePath}/${encodeURIComponent(key)}/grants`,
1818
+ body
1819
+ });
1820
+ }
1821
+ /** DELETE /roles/:key/grants — back to the Planes defaults. Returns the reset role. */
1822
+ async reset(key) {
1823
+ return this.http.request({
1824
+ method: "DELETE",
1825
+ path: `${this.basePath}/${encodeURIComponent(key)}/grants`
1826
+ });
1827
+ }
1828
+ /** GET /roles/history — the change log, newest first; page with `cursor`. */
1829
+ async history(params) {
1830
+ return this.http.request({
1831
+ method: "GET",
1832
+ path: `${this.basePath}/history`,
1833
+ ...params ? { params } : {}
1834
+ });
1835
+ }
1836
+ };
1837
+
1838
+ // src/resources/invoice-settings.ts
1839
+ var InvoiceSettingsResource = class {
1840
+ constructor(http) {
1841
+ this.http = http;
1842
+ this.basePath = "/admin/invoice-settings";
1843
+ }
1844
+ /**
1845
+ * GET /admin/invoice-settings/offline-instructions — the plain-text
1846
+ * instructions shown on the pay page when online payment is unavailable,
1847
+ * or null when none are set.
1848
+ */
1849
+ async getOfflineInstructions() {
1850
+ const res = await this.http.request({
1851
+ method: "GET",
1852
+ path: `${this.basePath}/offline-instructions`
1853
+ });
1854
+ return res.instructions;
1855
+ }
1856
+ /**
1857
+ * PUT /admin/invoice-settings/offline-instructions — store plain text
1858
+ * (trimmed, at most 2,000 characters); null or blank clears it. Returns the
1859
+ * stored value.
1860
+ */
1861
+ async setOfflineInstructions(text) {
1862
+ const body = { instructions: text };
1863
+ const res = await this.http.request({
1864
+ method: "PUT",
1865
+ path: `${this.basePath}/offline-instructions`,
1866
+ body
1867
+ });
1868
+ return res.instructions;
1869
+ }
1870
+ /**
1871
+ * GET /admin/invoice-settings/overdue-offsets — the days after the due date
1872
+ * at which `invoice.overdue` fires, ascending (default `[3, 7, 14]`).
1873
+ */
1874
+ async getOverdueOffsets() {
1875
+ const res = await this.http.request({
1876
+ method: "GET",
1877
+ path: `${this.basePath}/overdue-offsets`
1878
+ });
1879
+ return res.offsets;
1880
+ }
1881
+ /**
1882
+ * PUT /admin/invoice-settings/overdue-offsets — replace the offsets: 1 to 5
1883
+ * unique whole days, each 1–90. Returns them sorted ascending. Admin only.
1884
+ */
1885
+ async setOverdueOffsets(offsets) {
1886
+ const body = { offsets };
1887
+ const res = await this.http.request({
1888
+ method: "PUT",
1889
+ path: `${this.basePath}/overdue-offsets`,
1890
+ body
1891
+ });
1892
+ return res.offsets;
1893
+ }
1894
+ /**
1895
+ * GET /admin/invoice-settings/attach-pdf — whether invoice emails carry the
1896
+ * invoice PDF (on unless an admin turned it off).
1897
+ */
1898
+ async getAttachPdf() {
1899
+ const res = await this.http.request({
1900
+ method: "GET",
1901
+ path: `${this.basePath}/attach-pdf`
1902
+ });
1903
+ return res.enabled;
1904
+ }
1905
+ /**
1906
+ * PUT /admin/invoice-settings/attach-pdf — turn the PDF attachment on
1907
+ * invoice emails on or off. Returns the stored value.
1908
+ */
1909
+ async setAttachPdf(enabled) {
1910
+ const body = { enabled };
1911
+ const res = await this.http.request({
1912
+ method: "PUT",
1913
+ path: `${this.basePath}/attach-pdf`,
1914
+ body
1915
+ });
1916
+ return res.enabled;
1917
+ }
1918
+ };
1919
+
1920
+ // src/resources/invoice-reminders.ts
1921
+ var InvoiceRemindersResource = class {
1922
+ constructor(http) {
1923
+ this.http = http;
1924
+ this.basePath = "/admin/invoice-reminders";
1925
+ }
1926
+ /** GET /admin/invoice-reminders — the rules, ascending by offset, and the overdue offsets. */
1927
+ async list() {
1928
+ return this.http.request({
1929
+ method: "GET",
1930
+ path: this.basePath
1931
+ });
1932
+ }
1933
+ /**
1934
+ * PUT /admin/invoice-reminders — replace the WHOLE rule set (a rule left out
1935
+ * is deleted): up to 5 rules at unique offsets. Templates may use only
1936
+ * `{{customerName}}`, `{{invoiceNumber}}`, `{{amountDue}}`, `{{total}}`,
1937
+ * `{{dueDate}}`, `{{daysOverdue}}` and `{{companyName}}`; any other is a 422
1938
+ * `REMINDER_TEMPLATE_INVALID` listing each one. Returns the stored set.
1939
+ */
1940
+ async update(rules) {
1941
+ return this.http.request({
1942
+ method: "PUT",
1943
+ path: this.basePath,
1944
+ body: { rules }
1945
+ });
1946
+ }
1947
+ /**
1948
+ * POST /admin/invoice-reminders/preview — render a subject and body exactly
1949
+ * as the reminder email would, against an invoice or a sample. Sends nothing.
1950
+ */
1951
+ async preview(params) {
1952
+ return this.http.request({
1953
+ method: "POST",
1954
+ path: `${this.basePath}/preview`,
1955
+ body: params
1956
+ });
1957
+ }
1958
+ };
1959
+
1960
+ // src/resources/event-automations.ts
1961
+ var EventAutomationsResource = class {
1962
+ constructor(http) {
1963
+ this.http = http;
1964
+ }
1965
+ // Each request spells its path out in full (no computed base path) so the
1966
+ // API's SDK route-parity audit (sdk-route-parity-audit.spec.ts) can read it.
1967
+ /** GET — enabled and disabled automations, oldest first, optionally by event type or owner. */
1968
+ async list(params = {}) {
1969
+ const query = {};
1970
+ if (params.owner_tag) query["owner_tag"] = params.owner_tag;
1971
+ if (params.event_type) query["event_type"] = params.event_type;
1972
+ const res = await this.http.request({
1973
+ method: "GET",
1974
+ path: "/admin/event-automations",
1975
+ params: query
1976
+ });
1977
+ return res.data;
1978
+ }
1979
+ /** GET /:id — 404 when it doesn't exist or was deleted. */
1980
+ async get(id) {
1981
+ return this.http.request({
1982
+ method: "GET",
1983
+ path: `/admin/event-automations/${encodeURIComponent(id)}`
1984
+ });
1985
+ }
1986
+ /**
1987
+ * POST — create (201). 400 `VALIDATION_FAILED` for a bad body, or a 400
1988
+ * naming the step whose `action_type` isn't allowed in automations.
1989
+ */
1990
+ async create(input) {
1991
+ return this.http.request({
1992
+ method: "POST",
1993
+ path: "/admin/event-automations",
1994
+ body: input
1995
+ });
1996
+ }
1997
+ /**
1998
+ * PATCH /:id — only the fields sent change. Sending `actions` replaces the
1999
+ * list: keep each existing step's `id` so a step that already ran isn't run
2000
+ * again. `{ enabled: false }` switches it off.
2001
+ */
2002
+ async update(id, input) {
2003
+ return this.http.request({
2004
+ method: "PATCH",
2005
+ path: `/admin/event-automations/${encodeURIComponent(id)}`,
2006
+ body: input
2007
+ });
2008
+ }
2009
+ /** DELETE /:id — soft delete; returns `{ id }` (200). */
2010
+ async delete(id) {
2011
+ return this.http.request({
2012
+ method: "DELETE",
2013
+ path: `/admin/event-automations/${encodeURIComponent(id)}`
2014
+ });
2015
+ }
2016
+ };
2017
+
2018
+ // src/resources/web-forms.ts
2019
+ var WebFormsResource = class {
2020
+ constructor(http) {
2021
+ this.http = http;
2022
+ this.submissions = new WebFormSubmissionsResource(http);
2023
+ }
2024
+ // Each request spells its path out in full so the API's SDK route-parity
2025
+ // audit (sdk-route-parity-audit.spec.ts) can read it.
2026
+ /** GET — every form not archived, newest first. */
2027
+ async list() {
2028
+ const res = await this.http.request({ method: "GET", path: "/admin/web-forms" });
2029
+ return res.data;
2030
+ }
2031
+ /** GET /trade-options — the active trades a `trade` question offers, by current name. */
2032
+ async tradeOptions() {
2033
+ const res = await this.http.request({ method: "GET", path: "/admin/web-forms/trade-options" });
2034
+ return res.data;
2035
+ }
2036
+ /** GET /:id */
2037
+ async get(id) {
2038
+ return this.http.request({ method: "GET", path: `/admin/web-forms/${encodeURIComponent(id)}` });
2039
+ }
2040
+ /** POST — create (201) with its default routing. Pass `recipient_agent_ids`. */
2041
+ async create(input) {
2042
+ return this.http.request({ method: "POST", path: "/admin/web-forms", body: input });
2043
+ }
2044
+ /** PATCH /:id — only the fields sent change. `active: false` switches the form off. */
2045
+ async update(id, input) {
2046
+ return this.http.request({
2047
+ method: "PATCH",
2048
+ path: `/admin/web-forms/${encodeURIComponent(id)}`,
2049
+ body: input
2050
+ });
2051
+ }
2052
+ /** DELETE /:id — archive: the public URL stops working and routing stops. Returns `{ id }`. */
2053
+ async archive(id) {
2054
+ return this.http.request({ method: "DELETE", path: `/admin/web-forms/${encodeURIComponent(id)}` });
2055
+ }
2056
+ /** POST /:id/rotate-key — a new public key; the old embed stops working at once. */
2057
+ async rotateKey(id) {
2058
+ return this.http.request({
2059
+ method: "POST",
2060
+ path: `/admin/web-forms/${encodeURIComponent(id)}/rotate-key`
2061
+ });
2062
+ }
2063
+ };
2064
+ var WebFormSubmissionsResource = class {
2065
+ constructor(http) {
2066
+ this.http = http;
2067
+ }
2068
+ /** GET /submissions — the first page, newest first, with routing state. Use `listPage` to read on. */
2069
+ async list(params = {}) {
2070
+ return (await this.listPage(params)).data;
2071
+ }
2072
+ /**
2073
+ * GET /submissions — one page plus `next`, which is null on the last page.
2074
+ * Pass `next`'s `before` and `before_id` back in to read the following page.
2075
+ */
2076
+ async listPage(params = {}) {
2077
+ const query = {};
2078
+ for (const [k, v] of Object.entries(params)) if (v !== void 0) query[k] = v;
2079
+ const res = await this.http.request({
2080
+ method: "GET",
2081
+ path: "/admin/web-forms/submissions",
2082
+ params: query
2083
+ });
2084
+ return { data: res.data, next: res.next ?? null };
2085
+ }
2086
+ /** GET /submissions/:id — answers as seen, plus each routing step. */
2087
+ async get(id) {
2088
+ return this.http.request({
2089
+ method: "GET",
2090
+ path: `/admin/web-forms/submissions/${encodeURIComponent(id)}`
2091
+ });
2092
+ }
2093
+ /** PATCH /submissions/:id — set triage status. */
2094
+ async update(id, input) {
2095
+ return this.http.request({
2096
+ method: "PATCH",
2097
+ path: `/admin/web-forms/submissions/${encodeURIComponent(id)}`,
2098
+ body: input
2099
+ });
2100
+ }
2101
+ /** POST /submissions/:id/route — retry failed steps, run never-run ones (not email, text or webhook: `skipped`); safe to repeat. */
2102
+ async route(id) {
2103
+ return this.http.request({
2104
+ method: "POST",
2105
+ path: `/admin/web-forms/submissions/${encodeURIComponent(id)}/route`
2106
+ });
2107
+ }
2108
+ };
2109
+
2110
+ // src/resources/contact-sequences.ts
2111
+ var ContactSequencesResource = class {
2112
+ constructor(http) {
2113
+ this.http = http;
2114
+ this.basePath = "/contact-sequences";
2115
+ }
2116
+ /** GET /contact-sequences — `{ data, meta: { total } }`, name-sorted, max 100. */
2117
+ async list() {
2118
+ return this.http.request({
2119
+ method: "GET",
2120
+ path: this.basePath
2121
+ });
2122
+ }
2123
+ };
2124
+
2125
+ // src/resources/enrollments.ts
2126
+ var EnrollmentsResource = class {
2127
+ constructor(http) {
2128
+ this.http = http;
2129
+ }
2130
+ /**
2131
+ * POST /contacts/:id/enrollments — `{ workflow_id }`. 409 if the contact is
2132
+ * already active in the sequence; 422 if the sequence has no published version.
2133
+ */
2134
+ async enroll(contactId, workflowId) {
2135
+ return this.http.request({
2136
+ method: "POST",
2137
+ path: `/contacts/${contactId}/enrollments`,
2138
+ body: { workflow_id: workflowId }
2139
+ });
2140
+ }
2141
+ /** GET /contacts/:id/enrollments — a bare array, newest first; optional `status` filter. */
2142
+ async list(contactId, params) {
2143
+ return this.http.request({
2144
+ method: "GET",
2145
+ path: `/contacts/${contactId}/enrollments`,
2146
+ ...params ? { params } : {}
2147
+ });
2148
+ }
2149
+ /**
2150
+ * POST /enrollments/:id/exit — no body; the exit reason is recorded as
2151
+ * `'manual'`. Idempotent: an already-ended enrollment is returned unchanged.
2152
+ */
2153
+ async exit(enrollmentId) {
2154
+ return this.http.request({
2155
+ method: "POST",
2156
+ path: `/enrollments/${enrollmentId}/exit`
2157
+ });
2158
+ }
2159
+ };
2160
+
2161
+ // src/resources/workflow-event-rules.ts
2162
+ var WorkflowEventRulesResource = class {
2163
+ constructor(http, workflowId) {
2164
+ this.http = http;
2165
+ this.workflowId = workflowId;
2166
+ }
2167
+ // Each request spells its path out in full (no computed base path) so the
2168
+ // API's SDK route-parity audit (sdk-route-parity-audit.spec.ts) can read it.
2169
+ /** GET — a bare array of the workflow's live rules, newest first. 404 `WORKFLOW_NOT_FOUND`. */
2170
+ async list() {
2171
+ return this.http.request({
2172
+ method: "GET",
2173
+ path: `/admin/workflows/${encodeURIComponent(this.workflowId)}/event-rules`
2174
+ });
2175
+ }
2176
+ /**
2177
+ * POST — add a rule (201). `when` defaults to `{}` and `enabled` to true; use
2178
+ * `when: {}` for the creation types in `WORKFLOW_EVENT_RULE_MATCH_ALL_EVENT_TYPES`.
2179
+ * 400 `VALIDATION_FAILED` for a bad body; 404 `WORKFLOW_NOT_FOUND`.
2180
+ */
2181
+ async create(input) {
2182
+ return this.http.request({
2183
+ method: "POST",
2184
+ path: `/admin/workflows/${encodeURIComponent(this.workflowId)}/event-rules`,
2185
+ body: input
2186
+ });
2187
+ }
2188
+ /** PATCH /:id — only the fields sent change (at least one). 404 `EVENT_RULE_NOT_FOUND`. */
2189
+ async update(ruleId, input) {
2190
+ return this.http.request({
2191
+ method: "PATCH",
2192
+ path: `/admin/workflows/${encodeURIComponent(this.workflowId)}/event-rules/${encodeURIComponent(ruleId)}`,
2193
+ body: input
2194
+ });
2195
+ }
2196
+ /** DELETE /:id — soft delete; returns `{ id }` (200). 404 `EVENT_RULE_NOT_FOUND`. */
2197
+ async delete(ruleId) {
2198
+ return this.http.request({
2199
+ method: "DELETE",
2200
+ path: `/admin/workflows/${encodeURIComponent(this.workflowId)}/event-rules/${encodeURIComponent(ruleId)}`
2201
+ });
2202
+ }
2203
+ };
2204
+
2205
+ // src/resources/workflows.ts
2206
+ var WorkflowsResource = class {
2207
+ constructor(http) {
2208
+ this.http = http;
2209
+ this.basePath = "/workflows";
2210
+ this.adminPath = "/admin/workflows";
2211
+ }
2212
+ /**
2213
+ * GET /workflows/:id/stages — the ordered stages of one workflow version. Pass
2214
+ * a record's instance `workflowId` (e.g. from `GET /opportunities/:id/workflow`)
2215
+ * to get the stages of the version that record is pinned to, even an archived
2216
+ * one. 404 for an unknown or draft id; 403 if the caller cannot read the
2217
+ * workflow's record type.
2218
+ */
2219
+ async getStages(workflowId) {
2220
+ return this.http.request({
2221
+ method: "GET",
2222
+ path: `${this.basePath}/${encodeURIComponent(workflowId)}/stages`
2223
+ });
2224
+ }
2225
+ /**
2226
+ * GET /workflows/transitions — transition summaries of every published
2227
+ * workflow, or with `workflowId` of that one version (published or archived;
2228
+ * an unknown, draft or other-tenant id returns an empty list). Each summary
2229
+ * carries `workflow_id`, `workflow_version`, `lineage_workflow_id` and
2230
+ * `automatic_only`. Only pipelines whose record type the caller can read
2231
+ * are listed; an unreadable `workflowId` returns an empty list, not 403.
2232
+ */
2233
+ async listTransitions(params = {}) {
2234
+ const query = {};
2235
+ if (params.entityTypes && params.entityTypes.length > 0) query["entity_types"] = params.entityTypes.join(",");
2236
+ if (params.workflowId) query["workflow_id"] = params.workflowId;
2237
+ return this.http.request({
2238
+ method: "GET",
2239
+ path: `${this.basePath}/transitions`,
2240
+ params: query
2241
+ });
2242
+ }
2243
+ /**
2244
+ * POST /admin/workflows/:wid/transitions — add a transition to a draft
2245
+ * workflow. Pass `automaticOnly: true` for an edge only automation should
2246
+ * fire (e.g. an event rule advancing on "contract sent").
2247
+ */
2248
+ async createTransition(workflowId, input) {
2249
+ return this.http.request({
2250
+ method: "POST",
2251
+ path: `${this.adminPath}/${encodeURIComponent(workflowId)}/transitions`,
2252
+ body: input
2253
+ });
2254
+ }
2255
+ /**
2256
+ * The event rules of one workflow (`/admin/workflows/:wid/event-rules`) —
2257
+ * "advance automatically when…". Any version's id works; rules are keyed by
2258
+ * the lineage root.
2259
+ */
2260
+ eventRules(workflowId) {
2261
+ return new WorkflowEventRulesResource(this.http, workflowId);
2262
+ }
2263
+ /** PUT /admin/workflows/:wid/transitions/:tid — update a draft workflow's transition. */
2264
+ async updateTransition(workflowId, transitionId, input) {
2265
+ return this.http.request({
2266
+ method: "PUT",
2267
+ path: `${this.adminPath}/${encodeURIComponent(workflowId)}/transitions/${encodeURIComponent(transitionId)}`,
2268
+ body: input
2269
+ });
2270
+ }
2271
+ };
2272
+
2273
+ // src/resources/service-schedules.ts
2274
+ var ServiceSchedulesResource = class {
2275
+ constructor(http) {
2276
+ this.http = http;
2277
+ }
2278
+ // Each request spells its path out in full (no computed base path) so the
2279
+ // API's SDK route-parity audit (sdk-route-parity-audit.spec.ts) can read it.
2280
+ /** GET — the schedules of one customer or opportunity. */
2281
+ async list(subject_type, subject_id) {
2282
+ return this.http.request({
2283
+ method: "GET",
2284
+ path: "/service-schedules",
2285
+ params: { subject_type, subject_id }
2286
+ });
2287
+ }
2288
+ /** GET /:id — 404 when it doesn't exist or was deleted. */
2289
+ async get(id) {
2290
+ return this.http.request({
2291
+ method: "GET",
2292
+ path: `/service-schedules/${encodeURIComponent(id)}`
2293
+ });
2294
+ }
2295
+ /**
2296
+ * POST — create (201). The horizon's visits are generated straight away.
2297
+ * 400 `INVALID_RECURRENCE_RULE`, `SERVICE_TRADE_REQUIRED` or a validation error.
2298
+ */
2299
+ async create(input) {
2300
+ return this.http.request({
2301
+ method: "POST",
2302
+ path: "/service-schedules",
2303
+ body: input
2304
+ });
2305
+ }
2306
+ /**
2307
+ * PATCH /:id — only the fields sent change. A cadence, time, crew, duration
2308
+ * or horizon change regenerates future visits from today (`effective_from`,
2309
+ * which must be today) and reports it in `regeneration`; a visit someone changed is never
2310
+ * touched and is listed under `regeneration.protected`. The edit and its
2311
+ * regeneration succeed or fail together. 400 `INVALID_EFFECTIVE_FROM` for any
2312
+ * date but today.
2313
+ */
2314
+ async update(id, input) {
2315
+ return this.http.request({
2316
+ method: "PATCH",
2317
+ path: `/service-schedules/${encodeURIComponent(id)}`,
2318
+ body: input
2319
+ });
2320
+ }
2321
+ /** POST /:id/preview-update — what `update` with the same input would do. Writes nothing. */
2322
+ async previewUpdate(id, input) {
2323
+ return this.http.request({
2324
+ method: "POST",
2325
+ path: `/service-schedules/${encodeURIComponent(id)}/preview-update`,
2326
+ body: input
2327
+ });
2328
+ }
2329
+ /** PATCH /:id/status — pause, resume (`active`) or end. Resume generates the horizon at once. */
2330
+ async setStatus(id, status) {
2331
+ return this.http.request({
2332
+ method: "PATCH",
2333
+ path: `/service-schedules/${encodeURIComponent(id)}/status`,
2334
+ body: { status }
2335
+ });
2336
+ }
2337
+ /** DELETE /:id — soft-delete (204). */
2338
+ async delete(id) {
2339
+ await this.http.request({
2340
+ method: "DELETE",
2341
+ path: `/service-schedules/${encodeURIComponent(id)}`
2342
+ });
2343
+ }
2344
+ /**
2345
+ * POST /conflicts/preview — before booking people, see who is already on
2346
+ * another event (`conflicts`) and who would be outside their working hours
2347
+ * (`working_hours`). Read-only and warn-only: nothing is ever blocked. Give
2348
+ * exactly one of `windows` (single booking) or `schedule` (a cadence). 400 on
2349
+ * invalid input, INVALID_RECURRENCE_RULE, INVALID_TIMEZONE or
2350
+ * TOO_MANY_WINDOWS (> 400).
2351
+ */
2352
+ async previewConflicts(request) {
2353
+ return this.http.request({
2354
+ method: "POST",
2355
+ path: "/service-schedules/conflicts/preview",
2356
+ body: request
2357
+ });
2358
+ }
2359
+ /** GET /settings/crew-roles — which agent roles count as assignable crew. */
2360
+ async getCrewRoles() {
2361
+ return this.http.request({
2362
+ method: "GET",
2363
+ path: "/service-schedules/settings/crew-roles"
2364
+ });
2365
+ }
2366
+ /** PUT /settings/crew-roles — set the assignable roles (an override of the default). */
2367
+ async setCrewRoles(roles) {
2368
+ return this.http.request({
2369
+ method: "PUT",
2370
+ path: "/service-schedules/settings/crew-roles",
2371
+ body: { roles }
2372
+ });
2373
+ }
2374
+ /** GET /settings/crew — assignable crew with their home-base status. */
2375
+ async listCrew() {
2376
+ const res = await this.http.request({
2377
+ method: "GET",
2378
+ path: "/service-schedules/settings/crew"
2379
+ });
2380
+ return res.crew;
2381
+ }
2382
+ /** PUT /settings/crew/:agentId/home-address — set and geocode a crew member's home base. */
2383
+ async setCrewHomeAddress(agentId, address) {
2384
+ return this.http.request({
2385
+ method: "PUT",
2386
+ path: `/service-schedules/settings/crew/${encodeURIComponent(agentId)}/home-address`,
2387
+ body: { address }
2388
+ });
2389
+ }
2390
+ };
2391
+
2392
+ // src/resources/billing-schedules.ts
2393
+ var BillingScheduleResource = class extends BaseResource {
2394
+ constructor(http) {
2395
+ super(http, "/admin/billing-schedules");
2396
+ }
2397
+ /** GET /admin/billing-schedules — list rows (no lines; `line_count` and `next_amount` instead). */
2398
+ async list(params) {
2399
+ return this.http.request({
2400
+ method: "GET",
2401
+ path: this.basePath,
2402
+ params: toQueryParams(params)
2403
+ });
2404
+ }
2405
+ /** GET /admin/billing-schedules/:id — the schedule with its lines and next 3 periods. */
2406
+ async get(id) {
2407
+ return this.http.request({
2408
+ method: "GET",
2409
+ path: `${this.basePath}/${encodeURIComponent(id)}`
2410
+ });
2411
+ }
2412
+ /**
2413
+ * POST /admin/billing-schedules. `timezone` defaults to the tenant's. A
2414
+ * backdated `start_date` needs `backfill` ('skip' | 'draft'), else 400
2415
+ * `BACKFILL_REQUIRED`; `collection: 'autopay'` without a platform-managed
2416
+ * Stripe connection and a saved default card is 422 `AUTOPAY_UNAVAILABLE`
2417
+ * (`reason` `no_connect` | `no_saved_method`).
2418
+ */
2419
+ async create(data) {
2420
+ return this.http.request({
2421
+ method: "POST",
2422
+ path: this.basePath,
2423
+ body: data
2424
+ });
2425
+ }
2426
+ /**
2427
+ * PATCH /admin/billing-schedules/:id — partial. `lines` replaces every line
2428
+ * from `effective_from` (default: the next period not yet invoiced) as a new
2429
+ * line version. 409 `CADENCE_LOCKED`; 422 `EFFECTIVE_DATE_IN_GENERATED_PERIOD`
2430
+ * for a date inside an invoiced period.
2431
+ */
2432
+ async update(id, data) {
2433
+ return this.http.request({
2434
+ method: "PATCH",
2435
+ path: `${this.basePath}/${encodeURIComponent(id)}`,
2436
+ body: data
2437
+ });
2438
+ }
2439
+ /** DELETE /admin/billing-schedules/:id — only a schedule that never invoiced (else 409 `SCHEDULE_HAS_INVOICES`). */
2440
+ async delete(id) {
2441
+ await this.http.request({
2442
+ method: "DELETE",
2443
+ path: `${this.basePath}/${encodeURIComponent(id)}`
2444
+ });
2445
+ }
2446
+ /** GET /admin/billing-schedules/:id/versions — line version history, newest effective date first. */
2447
+ async listVersions(id) {
2448
+ return this.http.request({
2449
+ method: "GET",
2450
+ path: `${this.basePath}/${encodeURIComponent(id)}/versions`
2451
+ });
2452
+ }
2453
+ /**
2454
+ * POST /admin/billing-schedules/:id/adjustments — add a one-off amount
2455
+ * (signed; negative is a credit) to the schedule's next generated invoice.
2456
+ * Billed exactly once; no automatic proration. 422 `ADJUSTMENT_INVALID`
2457
+ * (zero, or the next invoice would go below zero) or `SCHEDULE_NOT_ACTIVE`.
2458
+ */
2459
+ async addAdjustment(id, data) {
2460
+ return this.http.request({
2461
+ method: "POST",
2462
+ path: `${this.basePath}/${encodeURIComponent(id)}/adjustments`,
2463
+ body: data
2464
+ });
2465
+ }
2466
+ /** GET /admin/billing-schedules/:id/adjustments — oldest first; default pending and consumed. */
2467
+ async listAdjustments(id, params) {
2468
+ return this.http.request({
2469
+ method: "GET",
2470
+ path: `${this.basePath}/${encodeURIComponent(id)}/adjustments`,
2471
+ params: toQueryParams(params)
2472
+ });
2473
+ }
2474
+ /**
2475
+ * DELETE /admin/billing-schedules/:id/adjustments/:adjustmentId — cancel a
2476
+ * pending adjustment (it never bills). Returns it; 409
2477
+ * `ADJUSTMENT_ALREADY_CONSUMED` once an invoice carries it.
2478
+ */
2479
+ async cancelAdjustment(id, adjustmentId) {
2480
+ return this.http.request({
2481
+ method: "DELETE",
2482
+ path: `${this.basePath}/${encodeURIComponent(id)}/adjustments/${encodeURIComponent(adjustmentId)}`
2483
+ });
2484
+ }
2485
+ /** POST /admin/billing-schedules/:id/pause — 409 `INVALID_STATUS_TRANSITION` unless active. */
2486
+ async pause(id) {
2487
+ return this.http.request({
2488
+ method: "POST",
2489
+ path: `${this.basePath}/${encodeURIComponent(id)}/pause`
2490
+ });
2491
+ }
2492
+ /** POST /admin/billing-schedules/:id/resume — periods that fell due while paused are skipped. */
2493
+ async resume(id) {
2494
+ return this.http.request({
2495
+ method: "POST",
2496
+ path: `${this.basePath}/${encodeURIComponent(id)}/resume`
2497
+ });
2498
+ }
2499
+ /** POST /admin/billing-schedules/:id/end — no further periods generate. */
2500
+ async end(id) {
2501
+ return this.http.request({
2502
+ method: "POST",
2503
+ path: `${this.basePath}/${encodeURIComponent(id)}/end`
2504
+ });
2505
+ }
2506
+ /** GET /admin/billing-schedules/:id/preview — the next `count` (1–24, default 6) periods from the first unbilled one. */
2507
+ async preview(id, params) {
2508
+ return this.http.request({
2509
+ method: "GET",
2510
+ path: `${this.basePath}/${encodeURIComponent(id)}/preview`,
2511
+ params: toQueryParams(params)
2512
+ });
2513
+ }
2514
+ /** GET /admin/billing-schedules/:id/periods — the period ledger, newest first. */
2515
+ async periods(id, params) {
2516
+ return this.http.request({
2517
+ method: "GET",
2518
+ path: `${this.basePath}/${encodeURIComponent(id)}/periods`,
2519
+ params: toQueryParams(params)
2520
+ });
2521
+ }
2522
+ /**
2523
+ * GET /admin/billing-schedules/periods/needs-review — tenant-wide: needs_review
2524
+ * rows plus failed and stuck (pending over 2h) deliveries.
2525
+ */
2526
+ async needsReview(params) {
2527
+ return this.http.request({
2528
+ method: "GET",
2529
+ path: `${this.basePath}/periods/needs-review`,
2530
+ params: toQueryParams(params)
2531
+ });
2532
+ }
2533
+ /**
2534
+ * GET /admin/billing-schedules/autopay-summary — what disconnecting Stripe
2535
+ * would touch: live autopay schedules, the distinct customers on them, and
2536
+ * active saved cards on the current Stripe connection. On disconnect, autopay
2537
+ * schedules that can no longer charge switch to emailed pay links.
2538
+ */
2539
+ async autopaySummary() {
2540
+ return this.http.request({
2541
+ method: "GET",
2542
+ path: `${this.basePath}/autopay-summary`
2543
+ });
2544
+ }
2545
+ /**
2546
+ * POST /admin/billing-schedules/:id/generate-now — bill the current due
2547
+ * period now. Idempotent (`already_generated`); 409 `NOTHING_DUE` or
2548
+ * `SCHEDULE_NOT_ACTIVE`.
2549
+ */
2550
+ async generateNow(id) {
2551
+ return this.http.request({
2552
+ method: "POST",
2553
+ path: `${this.basePath}/${encodeURIComponent(id)}/generate-now`
2554
+ });
2555
+ }
2556
+ /**
2557
+ * POST /admin/billing-schedules/:id/periods/:periodStart/skip — skip one
2558
+ * period (`periodStart` is `YYYY-MM-DD`). Returns the skipped ledger row;
2559
+ * 400 `NOT_A_PERIOD`, 409 `PERIOD_ALREADY_INVOICED`.
2560
+ */
2561
+ async skipPeriod(id, periodStart, data = {}) {
2562
+ return this.http.request({
2563
+ method: "POST",
2564
+ path: `${this.basePath}/${encodeURIComponent(id)}/periods/${encodeURIComponent(periodStart)}/skip`,
2565
+ body: data
2566
+ });
2567
+ }
2568
+ /**
2569
+ * POST /admin/billing-schedules/:id/periods/:periodStart/regenerate — re-bill
2570
+ * a period whose invoice was voided (new draft on the same ledger row).
2571
+ * 409 `INVOICE_NOT_VOID` or `CHECKOUT_IN_FLIGHT`.
2572
+ */
2573
+ async regeneratePeriod(id, periodStart) {
2574
+ return this.http.request({
2575
+ method: "POST",
2576
+ path: `${this.basePath}/${encodeURIComponent(id)}/periods/${encodeURIComponent(periodStart)}/regenerate`
2577
+ });
2578
+ }
2579
+ };
2580
+
2581
+ // src/resources/custom-fields.ts
2582
+ var CustomFieldsResource = class {
2583
+ constructor(http) {
2584
+ this.http = http;
2585
+ }
2586
+ /** List definitions, optionally narrowed to one entity type. */
2587
+ async list(params) {
2588
+ return this.http.request({
2589
+ method: "GET",
2590
+ path: "/custom-fields",
2591
+ params
2592
+ });
2593
+ }
2594
+ /** GET /admin/custom-fields — the same list through the admin route (Manage grant). */
2595
+ async listAll(params) {
2596
+ return this.http.request({
2597
+ method: "GET",
2598
+ path: "/admin/custom-fields",
2599
+ params
2600
+ });
2601
+ }
2602
+ /** GET /admin/custom-fields/:id */
2603
+ async get(id) {
2604
+ return this.http.request({
2605
+ method: "GET",
2606
+ path: `/admin/custom-fields/${id}`
2607
+ });
2608
+ }
2609
+ /**
2610
+ * POST /admin/custom-fields — define a new field. 400 for `job`, `vendor` or
2611
+ * `agent` (those records can't hold values yet, PRD D6). A `fieldKey` must be
2612
+ * unique per entity type: check `listAll({ entity_type, include_inactive: true })` first.
2613
+ */
2614
+ async create(data) {
2615
+ return this.http.request({
2616
+ method: "POST",
2617
+ path: "/admin/custom-fields",
2618
+ body: data
2619
+ });
2620
+ }
2621
+ /** PATCH /admin/custom-fields/:id — `fieldKey` and `entityType` can't change. */
2622
+ async update(id, data) {
2623
+ return this.http.request({
2624
+ method: "PATCH",
2625
+ path: `/admin/custom-fields/${id}`,
2626
+ body: data
2627
+ });
2628
+ }
2629
+ /**
2630
+ * DELETE /admin/custom-fields/:id — deactivates the definition (204). Records
2631
+ * keep their stored values; `list({ include_inactive: true })` still shows it,
2632
+ * and `update(id, { active: true })` brings it back.
2633
+ */
2634
+ async deactivate(id) {
2635
+ await this.http.request({
2636
+ method: "DELETE",
2637
+ path: `/admin/custom-fields/${id}`
2638
+ });
2639
+ }
2640
+ };
2641
+
2642
+ // src/resources/ortto.ts
2643
+ var OrttoResource = class {
2644
+ constructor(http) {
2645
+ this.http = http;
2646
+ this.basePath = "/admin/integrations/ortto";
2647
+ }
2648
+ /** GET /admin/integrations/ortto/mappings — live mappings with their list names. */
2649
+ async listMappings() {
2650
+ const res = await this.http.request({
2651
+ method: "GET",
2652
+ path: `${this.basePath}/mappings`
2653
+ });
2654
+ return res.data;
2655
+ }
2656
+ /** GET /admin/integrations/ortto/audiences — the connected account's audiences (cached 60 s). */
2657
+ async listAudiences(params) {
2658
+ const res = await this.http.request({
2659
+ method: "GET",
2660
+ path: `${this.basePath}/audiences`,
2661
+ params
2662
+ });
2663
+ return res.data;
2664
+ }
2665
+ /** POST /admin/integrations/ortto/mappings — 409 when the list already has a mapping. */
2666
+ async createMapping(data) {
2667
+ const res = await this.http.request({
2668
+ method: "POST",
2669
+ path: `${this.basePath}/mappings`,
2670
+ body: data
2671
+ });
2672
+ return res.data;
2673
+ }
2674
+ /** PATCH /admin/integrations/ortto/mappings/:id — `ortto_tag` and/or `create_unmatched`. */
2675
+ async updateMapping(id, data) {
2676
+ const res = await this.http.request({
2677
+ method: "PATCH",
2678
+ path: `${this.basePath}/mappings/${id}`,
2679
+ body: data
2680
+ });
2681
+ return res.data;
2682
+ }
2683
+ /**
2684
+ * DELETE /admin/integrations/ortto/mappings/:id (204). A pull list becomes
2685
+ * editable again and keeps its members; a push tag is NOT removed from Ortto.
2686
+ */
2687
+ async deleteMapping(id) {
2688
+ await this.http.request({
2689
+ method: "DELETE",
2690
+ path: `${this.basePath}/mappings/${id}`
2691
+ });
2692
+ }
2693
+ /**
2694
+ * POST /admin/integrations/ortto/sync (202) — queue a sync for one mapping or
2695
+ * the whole connection. Never calls Ortto in-request.
2696
+ */
2697
+ async sync(data = {}) {
2698
+ const res = await this.http.request({
2699
+ method: "POST",
2700
+ path: `${this.basePath}/sync`,
2701
+ body: data
2702
+ });
2703
+ return res.data;
2704
+ }
2705
+ /** GET /admin/integrations/ortto/sync-status — 404 when Ortto is not connected. */
2706
+ async syncStatus() {
2707
+ const res = await this.http.request({
2708
+ method: "GET",
2709
+ path: `${this.basePath}/sync-status`
2710
+ });
2711
+ return res.data;
2712
+ }
2713
+ };
2714
+
2715
+ // src/resources/webhook-subscriptions.ts
2716
+ var WebhookSubscriptionsResource = class extends ApiResource {
2717
+ constructor(http) {
2718
+ super(http, "/admin/webhooks");
2719
+ }
2720
+ /** POST /admin/webhooks — the returned `secret` is shown only this once. */
2721
+ async create(data) {
2722
+ return this.http.request({ method: "POST", path: this.basePath, body: data });
2723
+ }
2724
+ /** GET /admin/webhooks */
2725
+ async list(params) {
2726
+ return this.http.request({
2727
+ method: "GET",
2728
+ path: this.basePath,
2729
+ params
2730
+ });
2731
+ }
2732
+ /** GET /admin/webhooks/:id */
2733
+ async get(id) {
2734
+ return this.http.request({ method: "GET", path: `${this.basePath}/${id}` });
2735
+ }
2736
+ /** PATCH /admin/webhooks/:id */
2737
+ async update(id, data) {
2738
+ return this.http.request({ method: "PATCH", path: `${this.basePath}/${id}`, body: data });
2739
+ }
2740
+ /** DELETE /admin/webhooks/:id */
2741
+ async delete(id) {
2742
+ return this.http.request({ method: "DELETE", path: `${this.basePath}/${id}` });
2743
+ }
2744
+ /** POST /admin/webhooks/:id/test — sends one signed test event to the URL now. */
2745
+ async test(id) {
2746
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/test` });
2747
+ }
2748
+ /**
2749
+ * POST /admin/webhooks/:id/rotate-secret — replaces the signing secret and
2750
+ * returns the new one, shown only this once. New deliveries are signed with
2751
+ * it, but deliveries already queued (and their retries, for several minutes)
2752
+ * keep the old one. `verifyWebhookSignature` checks one secret, so for a few
2753
+ * minutes have your receiver try the new secret and fall back to the old one.
2754
+ */
2755
+ async rotateSecret(id) {
2756
+ return this.http.request({
2757
+ method: "POST",
2758
+ path: `${this.basePath}/${id}/rotate-secret`
2759
+ });
2760
+ }
2761
+ /** GET /admin/webhooks/:id/deliveries — newest first. */
2762
+ async listDeliveries(id, params) {
2763
+ return this.http.request({
2764
+ method: "GET",
2765
+ path: `${this.basePath}/${id}/deliveries`,
2766
+ params
2767
+ });
2768
+ }
2769
+ /**
2770
+ * POST /admin/webhooks/:id/deliveries/:deliveryId/retry — queues a new
2771
+ * delivery of that event (202). The receiver sees the event again, so make
2772
+ * it idempotent on the event id.
2773
+ */
2774
+ async retryDelivery(id, deliveryId) {
2775
+ return this.http.request({
2776
+ method: "POST",
2777
+ path: `${this.basePath}/${id}/deliveries/${deliveryId}/retry`
2778
+ });
2779
+ }
2780
+ };
2781
+
2782
+ // src/resources/users.ts
2783
+ var UsersResource = class extends ApiResource {
2784
+ constructor(http) {
2785
+ super(http, "/users");
2786
+ }
2787
+ /** GET /users — paged, with email, role, status and org fields (read grant on users). */
2788
+ async list(params) {
2789
+ return this.http.request({
2790
+ method: "GET",
2791
+ path: this.basePath,
2792
+ params
2793
+ });
2794
+ }
2795
+ /**
2796
+ * GET /users/directory — active users' ids, names and roles, for pickers and
2797
+ * for resolving an assignee. Every role can read it.
2798
+ */
2799
+ async directory(params) {
2800
+ return this.http.request({
2801
+ method: "GET",
2802
+ path: `${this.basePath}/directory`,
2803
+ params
2804
+ });
2805
+ }
2806
+ /**
2807
+ * GET /users/:id/working-hours — the user's own weekly hours and the tenant
2808
+ * default. A non-admin caller may read only their own (403 otherwise).
2809
+ */
2810
+ async getWorkingHours(id) {
2811
+ return this.http.request({ method: "GET", path: `${this.basePath}/${id}/working-hours` });
2812
+ }
2813
+ };
2814
+
2815
+ // src/resources/teams.ts
2816
+ var TeamsResource = class extends ApiResource {
2817
+ constructor(http) {
2818
+ super(http, "/teams");
2819
+ }
2820
+ /** GET /teams — every team, with `member_count`. */
2821
+ async list() {
2822
+ return this.http.request({ method: "GET", path: this.basePath });
2823
+ }
2824
+ /** GET /teams/:id — one team, with `members`. */
2825
+ async get(id) {
2826
+ return this.http.request({ method: "GET", path: `${this.basePath}/${id}` });
2827
+ }
2828
+ };
2829
+
2830
+ // src/webhooks.ts
2831
+ function verifyWebhookSignature(payload, signature, secret) {
2832
+ if (!signature || !secret || !payload) {
2833
+ return false;
2834
+ }
2835
+ const prefix = "sha256=";
2836
+ if (!signature.startsWith(prefix)) {
2837
+ return false;
2838
+ }
2839
+ const receivedHex = signature.slice(prefix.length);
2840
+ if (!receivedHex) {
2841
+ return false;
2842
+ }
2843
+ const expectedHmac = createHmac("sha256", secret).update(payload).digest("hex");
2844
+ const receivedBuf = Buffer.from(receivedHex, "hex");
2845
+ const expectedBuf = Buffer.from(expectedHmac, "hex");
2846
+ if (receivedBuf.length !== expectedBuf.length) {
2847
+ return false;
2848
+ }
2849
+ return timingSafeEqual(receivedBuf, expectedBuf);
2850
+ }
2851
+ function parseWebhookEvent(body, signature, secret) {
2852
+ if (!verifyWebhookSignature(body, signature, secret)) {
2853
+ throw new WebhookVerificationError();
2854
+ }
2855
+ return JSON.parse(body);
2856
+ }
2857
+
2858
+ // src/webhook-router.ts
2859
+ var WebhookRouter = class {
2860
+ constructor() {
2861
+ /** pattern (composite key / entity wildcard / '*') → registered handlers. */
2862
+ this.handlers = /* @__PURE__ */ new Map();
2863
+ }
2864
+ /**
2865
+ * Register a handler for an event pattern.
2866
+ *
2867
+ * @param pattern - `"{entity_type}.{event_type}"` (e.g. `opportunity.created`),
2868
+ * an entity wildcard `"{entity_type}.*"` (e.g. `opportunity.*`), or the
2869
+ * global wildcard `"*"`. Matching is exact-string against the derived key;
2870
+ * see the class docs for the dotted-`event_type` shape.
2871
+ * @param handler - Invoked with the full {@link WebhookDelivery} on a match.
2872
+ * @returns `this`, for chaining.
2873
+ */
2874
+ on(pattern, handler) {
2875
+ const existing = this.handlers.get(pattern);
2876
+ if (existing) {
2877
+ existing.push(handler);
2878
+ } else {
2879
+ this.handlers.set(pattern, [handler]);
2880
+ }
2881
+ return this;
2882
+ }
2883
+ /**
2884
+ * Verify, parse, and dispatch a webhook delivery.
2885
+ *
2886
+ * The signature is verified first: on failure this throws
2887
+ * {@link WebhookVerificationError} and dispatches nothing. On success it
2888
+ * dispatches to every matching handler — specific key, then entity wildcard,
2889
+ * then global — awaiting async handlers before resolving.
2890
+ *
2891
+ * @param input - The raw `{ body, signature, secret }`.
2892
+ * @returns The parsed {@link WebhookDelivery}.
2893
+ * @throws WebhookVerificationError if the signature is invalid.
2894
+ */
2895
+ async process(input) {
2896
+ const delivery = parseWebhookEvent(input.body, input.signature, input.secret);
2897
+ const { entity_type, event_type } = delivery.event;
2898
+ const patterns = [`${entity_type}.${event_type}`, `${entity_type}.*`, "*"];
2899
+ for (const pattern of patterns) {
2900
+ const matched = this.handlers.get(pattern);
2901
+ if (!matched) continue;
2902
+ for (const handler of matched) {
2903
+ await handler(delivery);
2904
+ }
2905
+ }
2906
+ return delivery;
2907
+ }
2908
+ };
2909
+
2910
+ // src/client.ts
2911
+ var PlanesClient = class {
2912
+ constructor(config) {
2913
+ const hasOAuthCreds = Boolean(config.clientId) || Boolean(config.clientSecret);
2914
+ const modes = [
2915
+ config.accessToken ? "accessToken" : null,
2916
+ config.apiKey ? "apiKey" : null,
2917
+ hasOAuthCreds ? "clientId+clientSecret" : null
2918
+ ].filter((m) => m !== null);
2919
+ if (modes.length === 0) {
2920
+ throw new Error(
2921
+ "PlanesClient requires one auth mode: accessToken, apiKey, or clientId + clientSecret"
2922
+ );
2923
+ }
2924
+ if (modes.length > 1) {
2925
+ throw new Error(
2926
+ `PlanesClient requires exactly one auth mode, not multiple (got: ${modes.join(", ")})`
2927
+ );
2928
+ }
2929
+ if (hasOAuthCreds && (!config.clientId || !config.clientSecret)) {
2930
+ throw new Error("PlanesClient OAuth mode requires both clientId and clientSecret");
2931
+ }
2932
+ this.http = new HttpClient(config);
2933
+ }
2934
+ get opportunities() {
2935
+ if (!this._opportunities) {
2936
+ this._opportunities = new OpportunityResource(this.http);
2937
+ }
2938
+ return this._opportunities;
2939
+ }
2940
+ get customers() {
2941
+ if (!this._customers) {
2942
+ this._customers = new CustomerResource(this.http);
2943
+ }
2944
+ return this._customers;
2945
+ }
2946
+ get properties() {
2947
+ if (!this._properties) {
2948
+ this._properties = new PropertyResource(this.http);
2949
+ }
2950
+ return this._properties;
2951
+ }
2952
+ get calendarEvents() {
2953
+ if (!this._calendarEvents) {
2954
+ this._calendarEvents = new CalendarEventResource(this.http);
2955
+ }
2956
+ return this._calendarEvents;
2957
+ }
2958
+ get contracts() {
2959
+ if (!this._contracts) {
2960
+ this._contracts = new ContractResource(this.http);
2961
+ }
2962
+ return this._contracts;
2963
+ }
2964
+ get jobs() {
2965
+ if (!this._jobs) {
2966
+ this._jobs = new JobResource(this.http);
2967
+ }
2968
+ return this._jobs;
2969
+ }
2970
+ get estimates() {
2971
+ if (!this._estimates) {
2972
+ this._estimates = new EstimateResource(this.http);
2973
+ }
2974
+ return this._estimates;
2975
+ }
2976
+ get invoices() {
2977
+ if (!this._invoices) {
2978
+ this._invoices = new InvoiceResource(this.http);
2979
+ }
2980
+ return this._invoices;
2981
+ }
2982
+ get inventory() {
2983
+ if (!this._inventory) {
2984
+ this._inventory = new InventoryResource(this.http);
2985
+ }
2986
+ return this._inventory;
2987
+ }
2988
+ get contacts() {
2989
+ if (!this._contacts) {
2990
+ this._contacts = new ContactResource(this.http);
2991
+ }
2992
+ return this._contacts;
2993
+ }
2994
+ get activities() {
2995
+ if (!this._activities) {
2996
+ this._activities = new ActivityResource(this.http);
2997
+ }
2998
+ return this._activities;
2999
+ }
3000
+ get communications() {
3001
+ if (!this._communications) {
3002
+ this._communications = new CommunicationsResource(this.http);
3003
+ }
3004
+ return this._communications;
3005
+ }
3006
+ /** Logged meetings — manual + provider-synced, with company matching (E55). */
3007
+ get conversations() {
3008
+ if (!this._conversations) {
3009
+ this._conversations = new ConversationsResource(this.http);
3010
+ }
3011
+ return this._conversations;
3012
+ }
3013
+ get gmail() {
3014
+ if (!this._gmail) {
3015
+ this._gmail = new GmailResource(this.http);
3016
+ }
3017
+ return this._gmail;
3018
+ }
3019
+ get documents() {
3020
+ if (!this._documents) {
3021
+ this._documents = new DocumentsResource(this.http);
3022
+ }
3023
+ return this._documents;
3024
+ }
3025
+ get tags() {
3026
+ if (!this._tags) {
3027
+ this._tags = new TagResource(this.http);
3028
+ }
3029
+ return this._tags;
3030
+ }
3031
+ get lists() {
3032
+ if (!this._lists) {
3033
+ this._lists = new ListsResource(this.http);
3034
+ }
3035
+ return this._lists;
3036
+ }
3037
+ get leadSources() {
3038
+ if (!this._leadSources) {
3039
+ this._leadSources = new LeadSourcesResource(this.http);
3040
+ }
3041
+ return this._leadSources;
3042
+ }
3043
+ get tasks() {
3044
+ if (!this._tasks) {
3045
+ this._tasks = new TaskResource(this.http);
3046
+ }
3047
+ return this._tasks;
3048
+ }
3049
+ /** Record views — the "recently viewed" beacon + read (E41-F7). */
3050
+ get recordViews() {
3051
+ if (!this._recordViews) {
3052
+ this._recordViews = new RecordViewsResource(this.http);
3053
+ }
3054
+ return this._recordViews;
3055
+ }
3056
+ /** Module status — which modules are active for the caller's tenant (E51-F1-S1). */
3057
+ get modules() {
3058
+ if (!this._modules) {
3059
+ this._modules = new ModulesResource(this.http);
3060
+ }
3061
+ return this._modules;
3062
+ }
3063
+ /** The tenant's plan, billing status and plan ceiling — `plan.get()` (E54-F1-S2). */
3064
+ get plan() {
3065
+ if (!this._plan) {
3066
+ this._plan = new PlanResource(this.http);
3067
+ }
3068
+ return this._plan;
3069
+ }
3070
+ /** The authenticated caller — `me.abilities()` (E52-F1-S3). */
3071
+ get me() {
3072
+ if (!this._me) {
3073
+ this._me = new MeResource(this.http);
3074
+ }
3075
+ return this._me;
3076
+ }
3077
+ /** Settings → Roles, admin only — `roles.list/get/updateGrants/reset/history` (E52-F2-S5). */
3078
+ get roles() {
3079
+ if (!this._roles) {
3080
+ this._roles = new RolesResource(this.http);
3081
+ }
3082
+ return this._roles;
3083
+ }
3084
+ /** Invoice settings — `invoiceSettings.getOfflineInstructions/setOfflineInstructions` (E56-F5-S4). */
3085
+ get invoiceSettings() {
3086
+ if (!this._invoiceSettings) {
3087
+ this._invoiceSettings = new InvoiceSettingsResource(this.http);
3088
+ }
3089
+ return this._invoiceSettings;
3090
+ }
3091
+ /** Payment reminder settings, admin only — `invoiceReminders.list/update/preview` (E56-F8-S6). */
3092
+ get invoiceReminders() {
3093
+ if (!this._invoiceReminders) {
3094
+ this._invoiceReminders = new InvoiceRemindersResource(this.http);
3095
+ }
3096
+ return this._invoiceReminders;
3097
+ }
3098
+ /** Event automations, admin only — `eventAutomations.list/get/create/update/delete` (E60-S2). */
3099
+ get eventAutomations() {
3100
+ if (!this._eventAutomations) {
3101
+ this._eventAutomations = new EventAutomationsResource(this.http);
3102
+ }
3103
+ return this._eventAutomations;
3104
+ }
3105
+ /** Web forms and their submissions, admin only — `webForms.list/get/create/update/archive/rotateKey`, `webForms.submissions.list/get/update/route` (E60-S6). */
3106
+ get webForms() {
3107
+ if (!this._webForms) {
3108
+ this._webForms = new WebFormsResource(this.http);
3109
+ }
3110
+ return this._webForms;
3111
+ }
3112
+ /** Published sequences a contact can be enrolled in (E51-F2-S6). */
3113
+ get contactSequences() {
3114
+ if (!this._contactSequences) {
3115
+ this._contactSequences = new ContactSequencesResource(this.http);
3116
+ }
3117
+ return this._contactSequences;
3118
+ }
3119
+ /** Enroll a contact in a sequence, list its enrollments, exit one (E51-F2-S8). */
3120
+ get enrollments() {
3121
+ if (!this._enrollments) {
3122
+ this._enrollments = new EnrollmentsResource(this.http);
3123
+ }
3124
+ return this._enrollments;
3125
+ }
3126
+ /** Tenant-readable workflow reads — a workflow version's ordered stages. */
3127
+ get workflows() {
3128
+ if (!this._workflows) {
3129
+ this._workflows = new WorkflowsResource(this.http);
3130
+ }
3131
+ return this._workflows;
3132
+ }
3133
+ get serviceSchedules() {
3134
+ if (!this._serviceSchedules) {
3135
+ this._serviceSchedules = new ServiceSchedulesResource(this.http);
3136
+ }
3137
+ return this._serviceSchedules;
3138
+ }
3139
+ /**
3140
+ * Recurring billing schedules (E56-F3) — CRUD, pause/resume/end, preview,
3141
+ * the period ledger, Needs review, generate-now, skip and regenerate.
3142
+ */
3143
+ get billingSchedules() {
3144
+ if (!this._billingSchedules) {
3145
+ this._billingSchedules = new BillingScheduleResource(this.http);
3146
+ }
3147
+ return this._billingSchedules;
3148
+ }
3149
+ get customFields() {
3150
+ if (!this._customFields) {
3151
+ this._customFields = new CustomFieldsResource(this.http);
3152
+ }
3153
+ return this._customFields;
3154
+ }
3155
+ /** Ortto connector — list mappings, audiences, manual sync, sync status (E53). Admin-only. */
3156
+ get ortto() {
3157
+ if (!this._ortto) {
3158
+ this._ortto = new OrttoResource(this.http);
3159
+ }
3160
+ return this._ortto;
3161
+ }
3162
+ /**
3163
+ * Webhook subscriptions — where entity events are delivered (E64-S10). Admin
3164
+ * grants and the `open_api` feature. Not `webhooks`: that is the event router.
3165
+ */
3166
+ get webhookSubscriptions() {
3167
+ if (!this._webhookSubscriptions) {
3168
+ this._webhookSubscriptions = new WebhookSubscriptionsResource(this.http);
3169
+ }
3170
+ return this._webhookSubscriptions;
3171
+ }
3172
+ /** The tenant's users, read-only: list and directory (E64-S10). */
3173
+ get users() {
3174
+ if (!this._users) {
3175
+ this._users = new UsersResource(this.http);
3176
+ }
3177
+ return this._users;
3178
+ }
3179
+ /** Teams, read-only (E64-S10). */
3180
+ get teams() {
3181
+ if (!this._teams) {
3182
+ this._teams = new TeamsResource(this.http);
3183
+ }
3184
+ return this._teams;
3185
+ }
3186
+ /**
3187
+ * Ergonomic webhook event router — `client.webhooks.on(pattern, handler)`
3188
+ * plus `client.webhooks.process({ body, signature, secret })`. Auth-independent
3189
+ * (the signing secret is supplied per `.process()` call), so it is created
3190
+ * lazily without the HTTP client. See {@link WebhookRouter}.
3191
+ */
3192
+ get webhooks() {
3193
+ if (!this._webhooks) {
3194
+ this._webhooks = new WebhookRouter();
3195
+ }
3196
+ return this._webhooks;
3197
+ }
3198
+ };
3199
+
3200
+ // src/client-entry.ts
3201
+ var SESSION_MODE = "session";
3202
+ var PlanesClient2 = class extends PlanesClient {
3203
+ constructor(config) {
3204
+ if (typeof config?.getAccessToken !== "function") {
3205
+ throw new Error("PlanesClient (client entry) requires getAccessToken");
3206
+ }
3207
+ super({
3208
+ accessToken: SESSION_MODE,
3209
+ getAccessToken: config.getAccessToken,
3210
+ ...config.baseUrl !== void 0 ? { baseUrl: config.baseUrl } : {},
3211
+ ...config.onUnauthorized !== void 0 ? { onUnauthorized: config.onUnauthorized } : {},
3212
+ ...config.fetch !== void 0 ? { fetch: config.fetch } : {},
3213
+ ...config.timeout !== void 0 ? { timeout: config.timeout } : {},
3214
+ ...config.retryOnRateLimit !== void 0 ? { retryOnRateLimit: config.retryOnRateLimit } : {},
3215
+ ...config.maxRetries !== void 0 ? { maxRetries: config.maxRetries } : {}
3216
+ });
3217
+ }
3218
+ };
3219
+ export {
3220
+ AuthenticationError,
3221
+ AuthorizationError,
3222
+ DEFAULT_BASE_URL,
3223
+ DEFAULT_MAX_RETRIES,
3224
+ DEFAULT_TIMEOUT,
3225
+ NotFoundError,
3226
+ PlanesClient2 as PlanesClient,
3227
+ PlanesError,
3228
+ RateLimitError,
3229
+ ServerError,
3230
+ ValidationError
3231
+ };
3232
+ //# sourceMappingURL=client.mjs.map