@first-to-fly/crm-sdk 1.9.0 → 1.11.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.
@@ -1,5 +1,5 @@
1
- import { R as PartnerWorkspaceUpsertBody$1, J as PartnerWorkspaceDetail$1, N as PartnerWorkspacePatchBody$1, S as PartnerWorkspaceUsage, z as ContactRefUpsertBody, A as ContactRefUpsertResult, H as PartnerContactEraseResult, F as PartnerContactEraseByIdentityBody, G as PartnerContactEraseByIdentityResult, x as ContactChanges } from './crm-contracts-BiR0JbKC.cjs';
2
- export { y as ContactChangesQuery } from './crm-contracts-BiR0JbKC.cjs';
1
+ import { a1 as PartnerWorkspaceUpsertBody$1, Y as PartnerWorkspaceDetail$1, _ as PartnerWorkspacePatchBody$1, a2 as PartnerWorkspaceUsage, z as ContactRefUpsertBody, A as ContactRefUpsertResult, H as PartnerContactEraseResult, F as PartnerContactEraseByIdentityBody, G as PartnerContactEraseByIdentityResult, x as ContactChanges } from './crm-contracts-BeC2pzgj.cjs';
2
+ export { y as ContactChangesQuery } from './crm-contracts-BeC2pzgj.cjs';
3
3
 
4
4
  /**
5
5
  * Internal HTTP helper for the server-side `partner` entry point. Not part of the
@@ -11,6 +11,59 @@ export { y as ContactChangesQuery } from './crm-contracts-BiR0JbKC.cjs';
11
11
  */
12
12
  type FetchLike = typeof fetch;
13
13
 
14
+ /**
15
+ * Verifier for the signed webhook the CRM sends for each staff reply on the partner message
16
+ * channel (server side ONLY: it uses `node:crypto`).
17
+ *
18
+ * The CRM sends `POST <url>` with `x-crm-timestamp` (unix seconds) and `x-crm-signature`, the
19
+ * hex HMAC-SHA256 of `<timestamp>.<raw body>` keyed with the secret text from `setWebhook` or
20
+ * `rotateWebhookSecret`. Pass the body exactly as received: a body parsed and serialised again
21
+ * no longer matches the signature.
22
+ */
23
+ /** A staff reply, as delivered by the webhook. */
24
+ interface PartnerMessageSentEvent {
25
+ event: 'partner_message.sent';
26
+ /** Identifies this delivery. */
27
+ deliveryId: string;
28
+ externalRef: string;
29
+ threadRef: string;
30
+ conversationId: string;
31
+ /** Unique per reply: deduplicate on it. */
32
+ messageId: string;
33
+ body: string;
34
+ /** ISO 8601 UTC. */
35
+ sentAt: string;
36
+ sender: {
37
+ /** Your own id for the staff member, or `null` when they have none. */
38
+ userRef: string | null;
39
+ name: string;
40
+ };
41
+ }
42
+ type PartnerWebhookVerificationReason = 'missing_headers' | 'stale_timestamp' | 'bad_signature' | 'bad_payload';
43
+ /** A delivery that failed verification. The message names the reason and nothing from the request. */
44
+ declare class PartnerWebhookVerificationError extends Error {
45
+ readonly reason: PartnerWebhookVerificationReason;
46
+ constructor(reason: PartnerWebhookVerificationReason);
47
+ }
48
+ interface VerifyPartnerWebhookInput {
49
+ /** The request body exactly as received, before any JSON parsing. */
50
+ rawBody: string;
51
+ headers: Headers | Record<string, string | string[] | undefined>;
52
+ /** The signing secret as returned by `setWebhook` / `rotateWebhookSecret`. */
53
+ secret: string;
54
+ /** How far the timestamp may be from now, in either direction. Default 300. */
55
+ toleranceSeconds?: number;
56
+ /** Clock in milliseconds; for tests. Default `Date.now`. */
57
+ now?: () => number;
58
+ }
59
+ /**
60
+ * Verify a delivery and return the event. Throws {@link PartnerWebhookVerificationError}
61
+ * (answer 401); a present but malformed timestamp counts as `stale_timestamp`, a missing one as `missing_headers`. An empty or
62
+ * non-string `secret`, a non-string `rawBody` or a non-finite or negative `toleranceSeconds`
63
+ * is a caller bug and throws a plain `TypeError`. The body is parsed only after the signature has been verified.
64
+ */
65
+ declare function verifyPartnerWebhook(input: VerifyPartnerWebhookInput): PartnerMessageSentEvent;
66
+
14
67
  /**
15
68
  * CRM Partner SDK (server side ONLY).
16
69
  *
@@ -37,7 +90,7 @@ type FetchLike = typeof fetch;
37
90
  * Errors are {@link CrmPartnerError}: `status` is the HTTP status (0 for a
38
91
  * network failure or timeout), `code` is the CRM's short error code (or
39
92
  * `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` /
40
- * `invalid_limit` / `invalid_cap` / `invalid_date` / `invalid_identity` / `HTTP_<status>`).
93
+ * `invalid_thread_ref` / `invalid_limit` / `invalid_cap` / `invalid_date` / `invalid_identity` / `HTTP_<status>`).
41
94
  * The message never contains the key, a secret or a response body.
42
95
  *
43
96
  * Contact sync (`upsertContact`, `eraseContact`, `eraseContactsByIdentity`, `listContactChanges`) acts in a
@@ -50,9 +103,21 @@ type FetchLike = typeof fetch;
50
103
  * calendar month. A workspace created without one gets 5000. `getWorkspaceUsage` reports use
51
104
  * over a date range.
52
105
  *
53
- * Retryable: `status` 409 (`PROVISIONING_IN_PROGRESS`, another call for the ref is
54
- * running) and 503 (`SERVICE_BUSY`). Wait a few seconds (the CRM sends
55
- * `Retry-After: 5`) and repeat the same call; provisioning resumes where it stopped.
106
+ * Partner message channel (`sendPartnerMessage`, `deletePartnerConversation`,
107
+ * `listPartnerMessageChanges`, and the webhook methods `setWebhook`, `getWebhook`,
108
+ * `rotateWebhookSecret`, `deleteWebhook`): customer messages go in, staff replies come back
109
+ * through the change feed or a signed webhook. Turn the channel on per workspace with
110
+ * `partnerChannelEnabled`. Codes the message endpoint can return, besides the common ones:
111
+ * `NOT_FOUND`, `CONTACT_NOT_FOUND`, `WORKSPACE_DISABLED`, `PARTNER_CHANNEL_DISABLED`,
112
+ * `MESSAGE_REF_CONFLICT`, `THREAD_CONTACT_MISMATCH`, `RATE_LIMITED`, `VALIDATION_ERROR`
113
+ * and `SERVICE_BUSY`.
114
+ *
115
+ * Retryable: 409 only for `PROVISIONING_IN_PROGRESS` (another call for the ref is running),
116
+ * 429 (`RATE_LIMITED`) and 503 (`SERVICE_BUSY`). Wait (the CRM sends `Retry-After`: 5 seconds
117
+ * for 503 and 409, the 60-second window for 429) and repeat the same call; provisioning resumes
118
+ * where it stopped. Other 409s (`MESSAGE_REF_CONFLICT`, `THREAD_CONTACT_MISMATCH`,
119
+ * `PARTNER_CHANNEL_DISABLED`, `WORKSPACE_DISABLED`) last until something changes and carry no
120
+ * `Retry-After`.
56
121
  * 500 and status 0 are also safe to repeat.
57
122
  *
58
123
  * @packageDocumentation
@@ -60,9 +125,9 @@ type FetchLike = typeof fetch;
60
125
 
61
126
  /** A failed partner API call. The message never includes the key, secrets or response bodies. */
62
127
  declare class CrmPartnerError extends Error {
63
- /** HTTP status; 0 when the CRM could not be reached (network failure or timeout). 409 and 503 mean retry shortly. */
128
+ /** HTTP status; 0 when the CRM could not be reached (network failure or timeout). 409 `PROVISIONING_IN_PROGRESS`, 429 and 503 are retryable; other 409s (for example `MESSAGE_REF_CONFLICT`, `THREAD_CONTACT_MISMATCH`, `PARTNER_CHANNEL_DISABLED`, `WORKSPACE_DISABLED`) last until something changes, so do not retry them unchanged. */
64
129
  readonly status: number;
65
- /** The CRM's error code, or `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` / `invalid_limit` / `invalid_cap` / `invalid_date` / `invalid_identity` / `HTTP_<status>`. */
130
+ /** The CRM's error code, or `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` / `invalid_thread_ref` / `invalid_limit` / `invalid_cap` / `invalid_date` / `invalid_identity` / `HTTP_<status>`. */
66
131
  readonly code: string;
67
132
  constructor(status: number, code: string);
68
133
  }
@@ -71,6 +136,8 @@ declare const EXTERNAL_REF_PATTERN: RegExp;
71
136
  /** Same pattern the CRM enforces on a `contactRef`. */
72
137
  declare const CONTACT_REF_PATTERN: RegExp;
73
138
  declare const CONTACT_CHANGES_MAX_LIMIT = 200;
139
+ /** Upper bound the CRM accepts for the `limit` of {@link CrmPartnerClient.listPartnerMessageChanges}. */
140
+ declare const PARTNER_MESSAGE_CHANGES_MAX_LIMIT = 500;
74
141
  interface CrmPartnerClientOptions {
75
142
  /** CRM base URL, e.g. `https://crm.example.com` (a trailing `/api` is tolerated). */
76
143
  crmBaseUrl: string;
@@ -96,9 +163,17 @@ interface PartnerWorkspace {
96
163
  * returns), `0` = AI off, N = N credits per UTC calendar month.
97
164
  */
98
165
  aiMonthlyCapCredits: number | null;
166
+ /** Whether the partner message channel is on for this workspace (false from a CRM that does not report it). */
167
+ partnerChannelEnabled: boolean;
168
+ /** The workspace's own webhook URL; `null` = deliveries go to the URL set with `setWebhook`. */
169
+ webhookUrl: string | null;
99
170
  }
100
171
  /** Body of {@link CrmPartnerClient.upsertWorkspace}. */
101
- type PartnerWorkspaceUpsertBody = Omit<PartnerWorkspaceUpsertBody$1, 'ai_monthly_cap_credits'> & {
172
+ type PartnerWorkspaceUpsertBody = Omit<PartnerWorkspaceUpsertBody$1, 'ai_monthly_cap_credits' | 'partner_channel_enabled' | 'webhook_url'> & {
173
+ /** Turns the partner message channel on or off. Omit to leave it unchanged (off on create). */
174
+ partnerChannelEnabled?: boolean;
175
+ /** Webhook URL for this workspace, used instead of the partner's. `null` clears it; omit to leave it unchanged. */
176
+ webhookUrl?: string | null;
102
177
  /**
103
178
  * Monthly AI cap in credits (integer, 0 to {@link AI_MONTHLY_CAP_MAX_CREDITS}, or `null` for none).
104
179
  * Omit on create for the default of 5000; omit on a later call to leave it unchanged.
@@ -106,7 +181,11 @@ type PartnerWorkspaceUpsertBody = Omit<PartnerWorkspaceUpsertBody$1, 'ai_monthly
106
181
  aiMonthlyCapCredits?: number | null;
107
182
  };
108
183
  /** Body of {@link CrmPartnerClient.updateWorkspace}. At least one field is required. */
109
- type PartnerWorkspacePatchBody = Omit<PartnerWorkspacePatchBody$1, 'ai_monthly_cap_credits'> & {
184
+ type PartnerWorkspacePatchBody = Omit<PartnerWorkspacePatchBody$1, 'ai_monthly_cap_credits' | 'partner_channel_enabled' | 'webhook_url'> & {
185
+ /** Turns the partner message channel on or off. */
186
+ partnerChannelEnabled?: boolean;
187
+ /** Webhook URL for this workspace, used instead of the partner's. `null` clears it. */
188
+ webhookUrl?: string | null;
110
189
  /** Monthly AI cap in credits; `null` removes the cap, `0` switches AI off. */
111
190
  aiMonthlyCapCredits?: number | null;
112
191
  };
@@ -148,6 +227,52 @@ interface PartnerRotatedSecret {
148
227
  embedAppId: string;
149
228
  embedAppSecret: string;
150
229
  }
230
+ /** A customer message to hand to the CRM with {@link CrmPartnerClient.sendPartnerMessage}. */
231
+ interface PartnerMessageInput {
232
+ /** Your key for the person, as used by contact sync. */
233
+ contactRef: string;
234
+ /** Your id for the conversation. One thread belongs to one contact. */
235
+ threadRef: string;
236
+ /** Your id for the message. Repeating it stores nothing new. */
237
+ messageRef: string;
238
+ /** Plain text, 1 to 10,000 characters, not whitespace only. */
239
+ body: string;
240
+ /** When it was sent: a `Date`, or ISO 8601 with an offset. */
241
+ sentAt: string | Date;
242
+ /** Thread title (1 to 200 characters); set on create, updated when it changes. */
243
+ title?: string;
244
+ /** Your team key; the team is created if new. */
245
+ teamRef?: string;
246
+ }
247
+ /** Result of {@link CrmPartnerClient.sendPartnerMessage}. `created` is false for a repeat of a stored `messageRef`. */
248
+ interface PartnerMessageResult {
249
+ conversationId: string;
250
+ messageId: string;
251
+ created: boolean;
252
+ }
253
+ /** One staff reply owed to you, from {@link CrmPartnerClient.listPartnerMessageChanges}. */
254
+ interface PartnerMessageChange {
255
+ deliveryId: string;
256
+ externalRef: string;
257
+ threadRef: string;
258
+ conversationId: string;
259
+ /** Unique per reply: deduplicate on it. */
260
+ messageId: string;
261
+ body: string;
262
+ /** ISO 8601 UTC. */
263
+ sentAt: string;
264
+ sender: {
265
+ /** Your own id for the staff member, or `null` when they have none. */
266
+ userRef: string | null;
267
+ name: string;
268
+ };
269
+ deliveryStatus: 'pending' | 'delivered' | 'failed';
270
+ }
271
+ /** One page of {@link CrmPartnerClient.listPartnerMessageChanges}. */
272
+ interface PartnerMessageChangesPage {
273
+ items: PartnerMessageChange[];
274
+ nextCursor: string | null;
275
+ }
151
276
  interface CrmPartnerClient {
152
277
  /**
153
278
  * Idempotent: provisions the workspace for `externalRef`, or resumes/returns it. Optional
@@ -207,7 +332,57 @@ interface CrmPartnerClient {
207
332
  cursor?: string;
208
333
  limit?: number;
209
334
  }): Promise<ContactChanges>;
335
+ /**
336
+ * Hand a customer message to the CRM. Idempotent on `messageRef`: 201 resolves `created: true`,
337
+ * a repeat (200) resolves `created: false` with the same ids. One `threadRef` belongs to one
338
+ * contact. Rejections surface as {@link CrmPartnerError} with the CRM's code, for example
339
+ * `PARTNER_CHANNEL_DISABLED`, `CONTACT_NOT_FOUND`, `MESSAGE_REF_CONFLICT` (the `messageRef` is already used on
340
+ * another thread; not retryable), `THREAD_CONTACT_MISMATCH`, `WORKSPACE_DISABLED`,
341
+ * `RATE_LIMITED` and `SERVICE_BUSY`.
342
+ */
343
+ sendPartnerMessage(externalRef: string, message: PartnerMessageInput): Promise<PartnerMessageResult>;
344
+ /** Delete the conversation for `threadRef`. `deleted: false` when there is none (already deleted, or never sent). */
345
+ deletePartnerConversation(externalRef: string, threadRef: string): Promise<{
346
+ deleted: boolean;
347
+ }>;
348
+ /**
349
+ * One page of staff replies owed to you, oldest first. `limit` is 1 to 500 (default 100).
350
+ *
351
+ * Presenting a `cursor` acknowledges every row before it, so persist a page before calling
352
+ * again with its `nextCursor`. Keep calling until `items` is empty and store the cursor that
353
+ * call returns for the next poll. `nextCursor` is null only when no cursor was sent and there
354
+ * are no rows. Never construct a cursor, and never reuse one across workspaces. A 400
355
+ * `VALIDATION_ERROR` on a stored cursor means drop it and restart with none. Rows are kept 30
356
+ * days. A reply appears a few seconds after it is sent. Delivered rows are included
357
+ * (`deliveryStatus`); deduplicate on `messageId`.
358
+ */
359
+ listPartnerMessageChanges(externalRef: string, query?: {
360
+ cursor?: string;
361
+ limit?: number;
362
+ }): Promise<PartnerMessageChangesPage>;
363
+ /**
364
+ * Register (or change) the URL that receives staff replies. The first registration returns the
365
+ * signing `secret`, shown once: store it. Changing the URL returns no secret. The URL must be
366
+ * HTTPS (400 `VALIDATION_ERROR` otherwise).
367
+ */
368
+ setWebhook(input: {
369
+ url: string;
370
+ }): Promise<{
371
+ url: string;
372
+ secret?: string;
373
+ }>;
374
+ /** The registered webhook, or `null` when none is registered (404). The secret is never returned. */
375
+ getWebhook(): Promise<{
376
+ url: string;
377
+ hasSecret: true;
378
+ } | null>;
379
+ /** Replace the signing secret; the old one stops working at once. Throws a 404 error when no webhook is registered. */
380
+ rotateWebhookSecret(): Promise<{
381
+ secret: string;
382
+ }>;
383
+ /** Remove the webhook. Resolves also when none was registered. */
384
+ deleteWebhook(): Promise<void>;
210
385
  }
211
386
  declare function createCrmPartnerClient(opts: CrmPartnerClientOptions): CrmPartnerClient;
212
387
 
213
- export { AI_MONTHLY_CAP_MAX_CREDITS, CONTACT_CHANGES_MAX_LIMIT, CONTACT_REF_PATTERN, ContactChanges, ContactRefUpsertBody, ContactRefUpsertResult, type CrmPartnerClient, type CrmPartnerClientOptions, CrmPartnerError, EXTERNAL_REF_PATTERN, PartnerContactEraseByIdentityBody, PartnerContactEraseByIdentityResult, PartnerContactEraseResult, type PartnerRotatedSecret, type PartnerUsageRange, type PartnerWorkspace, type PartnerWorkspaceDetail, type PartnerWorkspacePatchBody, type PartnerWorkspaceUpsertBody, type PartnerWorkspaceUpsertResult, PartnerWorkspaceUsage, createCrmPartnerClient };
388
+ export { AI_MONTHLY_CAP_MAX_CREDITS, CONTACT_CHANGES_MAX_LIMIT, CONTACT_REF_PATTERN, ContactChanges, ContactRefUpsertBody, ContactRefUpsertResult, type CrmPartnerClient, type CrmPartnerClientOptions, CrmPartnerError, EXTERNAL_REF_PATTERN, PARTNER_MESSAGE_CHANGES_MAX_LIMIT, PartnerContactEraseByIdentityBody, PartnerContactEraseByIdentityResult, PartnerContactEraseResult, type PartnerMessageChange, type PartnerMessageChangesPage, type PartnerMessageInput, type PartnerMessageResult, type PartnerMessageSentEvent, type PartnerRotatedSecret, type PartnerUsageRange, PartnerWebhookVerificationError, type PartnerWebhookVerificationReason, type PartnerWorkspace, type PartnerWorkspaceDetail, type PartnerWorkspacePatchBody, type PartnerWorkspaceUpsertBody, type PartnerWorkspaceUpsertResult, PartnerWorkspaceUsage, type VerifyPartnerWebhookInput, createCrmPartnerClient, verifyPartnerWebhook };
package/dist/partner.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { R as PartnerWorkspaceUpsertBody$1, J as PartnerWorkspaceDetail$1, N as PartnerWorkspacePatchBody$1, S as PartnerWorkspaceUsage, z as ContactRefUpsertBody, A as ContactRefUpsertResult, H as PartnerContactEraseResult, F as PartnerContactEraseByIdentityBody, G as PartnerContactEraseByIdentityResult, x as ContactChanges } from './crm-contracts-BiR0JbKC.js';
2
- export { y as ContactChangesQuery } from './crm-contracts-BiR0JbKC.js';
1
+ import { a1 as PartnerWorkspaceUpsertBody$1, Y as PartnerWorkspaceDetail$1, _ as PartnerWorkspacePatchBody$1, a2 as PartnerWorkspaceUsage, z as ContactRefUpsertBody, A as ContactRefUpsertResult, H as PartnerContactEraseResult, F as PartnerContactEraseByIdentityBody, G as PartnerContactEraseByIdentityResult, x as ContactChanges } from './crm-contracts-BeC2pzgj.js';
2
+ export { y as ContactChangesQuery } from './crm-contracts-BeC2pzgj.js';
3
3
 
4
4
  /**
5
5
  * Internal HTTP helper for the server-side `partner` entry point. Not part of the
@@ -11,6 +11,59 @@ export { y as ContactChangesQuery } from './crm-contracts-BiR0JbKC.js';
11
11
  */
12
12
  type FetchLike = typeof fetch;
13
13
 
14
+ /**
15
+ * Verifier for the signed webhook the CRM sends for each staff reply on the partner message
16
+ * channel (server side ONLY: it uses `node:crypto`).
17
+ *
18
+ * The CRM sends `POST <url>` with `x-crm-timestamp` (unix seconds) and `x-crm-signature`, the
19
+ * hex HMAC-SHA256 of `<timestamp>.<raw body>` keyed with the secret text from `setWebhook` or
20
+ * `rotateWebhookSecret`. Pass the body exactly as received: a body parsed and serialised again
21
+ * no longer matches the signature.
22
+ */
23
+ /** A staff reply, as delivered by the webhook. */
24
+ interface PartnerMessageSentEvent {
25
+ event: 'partner_message.sent';
26
+ /** Identifies this delivery. */
27
+ deliveryId: string;
28
+ externalRef: string;
29
+ threadRef: string;
30
+ conversationId: string;
31
+ /** Unique per reply: deduplicate on it. */
32
+ messageId: string;
33
+ body: string;
34
+ /** ISO 8601 UTC. */
35
+ sentAt: string;
36
+ sender: {
37
+ /** Your own id for the staff member, or `null` when they have none. */
38
+ userRef: string | null;
39
+ name: string;
40
+ };
41
+ }
42
+ type PartnerWebhookVerificationReason = 'missing_headers' | 'stale_timestamp' | 'bad_signature' | 'bad_payload';
43
+ /** A delivery that failed verification. The message names the reason and nothing from the request. */
44
+ declare class PartnerWebhookVerificationError extends Error {
45
+ readonly reason: PartnerWebhookVerificationReason;
46
+ constructor(reason: PartnerWebhookVerificationReason);
47
+ }
48
+ interface VerifyPartnerWebhookInput {
49
+ /** The request body exactly as received, before any JSON parsing. */
50
+ rawBody: string;
51
+ headers: Headers | Record<string, string | string[] | undefined>;
52
+ /** The signing secret as returned by `setWebhook` / `rotateWebhookSecret`. */
53
+ secret: string;
54
+ /** How far the timestamp may be from now, in either direction. Default 300. */
55
+ toleranceSeconds?: number;
56
+ /** Clock in milliseconds; for tests. Default `Date.now`. */
57
+ now?: () => number;
58
+ }
59
+ /**
60
+ * Verify a delivery and return the event. Throws {@link PartnerWebhookVerificationError}
61
+ * (answer 401); a present but malformed timestamp counts as `stale_timestamp`, a missing one as `missing_headers`. An empty or
62
+ * non-string `secret`, a non-string `rawBody` or a non-finite or negative `toleranceSeconds`
63
+ * is a caller bug and throws a plain `TypeError`. The body is parsed only after the signature has been verified.
64
+ */
65
+ declare function verifyPartnerWebhook(input: VerifyPartnerWebhookInput): PartnerMessageSentEvent;
66
+
14
67
  /**
15
68
  * CRM Partner SDK (server side ONLY).
16
69
  *
@@ -37,7 +90,7 @@ type FetchLike = typeof fetch;
37
90
  * Errors are {@link CrmPartnerError}: `status` is the HTTP status (0 for a
38
91
  * network failure or timeout), `code` is the CRM's short error code (or
39
92
  * `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` /
40
- * `invalid_limit` / `invalid_cap` / `invalid_date` / `invalid_identity` / `HTTP_<status>`).
93
+ * `invalid_thread_ref` / `invalid_limit` / `invalid_cap` / `invalid_date` / `invalid_identity` / `HTTP_<status>`).
41
94
  * The message never contains the key, a secret or a response body.
42
95
  *
43
96
  * Contact sync (`upsertContact`, `eraseContact`, `eraseContactsByIdentity`, `listContactChanges`) acts in a
@@ -50,9 +103,21 @@ type FetchLike = typeof fetch;
50
103
  * calendar month. A workspace created without one gets 5000. `getWorkspaceUsage` reports use
51
104
  * over a date range.
52
105
  *
53
- * Retryable: `status` 409 (`PROVISIONING_IN_PROGRESS`, another call for the ref is
54
- * running) and 503 (`SERVICE_BUSY`). Wait a few seconds (the CRM sends
55
- * `Retry-After: 5`) and repeat the same call; provisioning resumes where it stopped.
106
+ * Partner message channel (`sendPartnerMessage`, `deletePartnerConversation`,
107
+ * `listPartnerMessageChanges`, and the webhook methods `setWebhook`, `getWebhook`,
108
+ * `rotateWebhookSecret`, `deleteWebhook`): customer messages go in, staff replies come back
109
+ * through the change feed or a signed webhook. Turn the channel on per workspace with
110
+ * `partnerChannelEnabled`. Codes the message endpoint can return, besides the common ones:
111
+ * `NOT_FOUND`, `CONTACT_NOT_FOUND`, `WORKSPACE_DISABLED`, `PARTNER_CHANNEL_DISABLED`,
112
+ * `MESSAGE_REF_CONFLICT`, `THREAD_CONTACT_MISMATCH`, `RATE_LIMITED`, `VALIDATION_ERROR`
113
+ * and `SERVICE_BUSY`.
114
+ *
115
+ * Retryable: 409 only for `PROVISIONING_IN_PROGRESS` (another call for the ref is running),
116
+ * 429 (`RATE_LIMITED`) and 503 (`SERVICE_BUSY`). Wait (the CRM sends `Retry-After`: 5 seconds
117
+ * for 503 and 409, the 60-second window for 429) and repeat the same call; provisioning resumes
118
+ * where it stopped. Other 409s (`MESSAGE_REF_CONFLICT`, `THREAD_CONTACT_MISMATCH`,
119
+ * `PARTNER_CHANNEL_DISABLED`, `WORKSPACE_DISABLED`) last until something changes and carry no
120
+ * `Retry-After`.
56
121
  * 500 and status 0 are also safe to repeat.
57
122
  *
58
123
  * @packageDocumentation
@@ -60,9 +125,9 @@ type FetchLike = typeof fetch;
60
125
 
61
126
  /** A failed partner API call. The message never includes the key, secrets or response bodies. */
62
127
  declare class CrmPartnerError extends Error {
63
- /** HTTP status; 0 when the CRM could not be reached (network failure or timeout). 409 and 503 mean retry shortly. */
128
+ /** HTTP status; 0 when the CRM could not be reached (network failure or timeout). 409 `PROVISIONING_IN_PROGRESS`, 429 and 503 are retryable; other 409s (for example `MESSAGE_REF_CONFLICT`, `THREAD_CONTACT_MISMATCH`, `PARTNER_CHANNEL_DISABLED`, `WORKSPACE_DISABLED`) last until something changes, so do not retry them unchanged. */
64
129
  readonly status: number;
65
- /** The CRM's error code, or `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` / `invalid_limit` / `invalid_cap` / `invalid_date` / `invalid_identity` / `HTTP_<status>`. */
130
+ /** The CRM's error code, or `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` / `invalid_thread_ref` / `invalid_limit` / `invalid_cap` / `invalid_date` / `invalid_identity` / `HTTP_<status>`. */
66
131
  readonly code: string;
67
132
  constructor(status: number, code: string);
68
133
  }
@@ -71,6 +136,8 @@ declare const EXTERNAL_REF_PATTERN: RegExp;
71
136
  /** Same pattern the CRM enforces on a `contactRef`. */
72
137
  declare const CONTACT_REF_PATTERN: RegExp;
73
138
  declare const CONTACT_CHANGES_MAX_LIMIT = 200;
139
+ /** Upper bound the CRM accepts for the `limit` of {@link CrmPartnerClient.listPartnerMessageChanges}. */
140
+ declare const PARTNER_MESSAGE_CHANGES_MAX_LIMIT = 500;
74
141
  interface CrmPartnerClientOptions {
75
142
  /** CRM base URL, e.g. `https://crm.example.com` (a trailing `/api` is tolerated). */
76
143
  crmBaseUrl: string;
@@ -96,9 +163,17 @@ interface PartnerWorkspace {
96
163
  * returns), `0` = AI off, N = N credits per UTC calendar month.
97
164
  */
98
165
  aiMonthlyCapCredits: number | null;
166
+ /** Whether the partner message channel is on for this workspace (false from a CRM that does not report it). */
167
+ partnerChannelEnabled: boolean;
168
+ /** The workspace's own webhook URL; `null` = deliveries go to the URL set with `setWebhook`. */
169
+ webhookUrl: string | null;
99
170
  }
100
171
  /** Body of {@link CrmPartnerClient.upsertWorkspace}. */
101
- type PartnerWorkspaceUpsertBody = Omit<PartnerWorkspaceUpsertBody$1, 'ai_monthly_cap_credits'> & {
172
+ type PartnerWorkspaceUpsertBody = Omit<PartnerWorkspaceUpsertBody$1, 'ai_monthly_cap_credits' | 'partner_channel_enabled' | 'webhook_url'> & {
173
+ /** Turns the partner message channel on or off. Omit to leave it unchanged (off on create). */
174
+ partnerChannelEnabled?: boolean;
175
+ /** Webhook URL for this workspace, used instead of the partner's. `null` clears it; omit to leave it unchanged. */
176
+ webhookUrl?: string | null;
102
177
  /**
103
178
  * Monthly AI cap in credits (integer, 0 to {@link AI_MONTHLY_CAP_MAX_CREDITS}, or `null` for none).
104
179
  * Omit on create for the default of 5000; omit on a later call to leave it unchanged.
@@ -106,7 +181,11 @@ type PartnerWorkspaceUpsertBody = Omit<PartnerWorkspaceUpsertBody$1, 'ai_monthly
106
181
  aiMonthlyCapCredits?: number | null;
107
182
  };
108
183
  /** Body of {@link CrmPartnerClient.updateWorkspace}. At least one field is required. */
109
- type PartnerWorkspacePatchBody = Omit<PartnerWorkspacePatchBody$1, 'ai_monthly_cap_credits'> & {
184
+ type PartnerWorkspacePatchBody = Omit<PartnerWorkspacePatchBody$1, 'ai_monthly_cap_credits' | 'partner_channel_enabled' | 'webhook_url'> & {
185
+ /** Turns the partner message channel on or off. */
186
+ partnerChannelEnabled?: boolean;
187
+ /** Webhook URL for this workspace, used instead of the partner's. `null` clears it. */
188
+ webhookUrl?: string | null;
110
189
  /** Monthly AI cap in credits; `null` removes the cap, `0` switches AI off. */
111
190
  aiMonthlyCapCredits?: number | null;
112
191
  };
@@ -148,6 +227,52 @@ interface PartnerRotatedSecret {
148
227
  embedAppId: string;
149
228
  embedAppSecret: string;
150
229
  }
230
+ /** A customer message to hand to the CRM with {@link CrmPartnerClient.sendPartnerMessage}. */
231
+ interface PartnerMessageInput {
232
+ /** Your key for the person, as used by contact sync. */
233
+ contactRef: string;
234
+ /** Your id for the conversation. One thread belongs to one contact. */
235
+ threadRef: string;
236
+ /** Your id for the message. Repeating it stores nothing new. */
237
+ messageRef: string;
238
+ /** Plain text, 1 to 10,000 characters, not whitespace only. */
239
+ body: string;
240
+ /** When it was sent: a `Date`, or ISO 8601 with an offset. */
241
+ sentAt: string | Date;
242
+ /** Thread title (1 to 200 characters); set on create, updated when it changes. */
243
+ title?: string;
244
+ /** Your team key; the team is created if new. */
245
+ teamRef?: string;
246
+ }
247
+ /** Result of {@link CrmPartnerClient.sendPartnerMessage}. `created` is false for a repeat of a stored `messageRef`. */
248
+ interface PartnerMessageResult {
249
+ conversationId: string;
250
+ messageId: string;
251
+ created: boolean;
252
+ }
253
+ /** One staff reply owed to you, from {@link CrmPartnerClient.listPartnerMessageChanges}. */
254
+ interface PartnerMessageChange {
255
+ deliveryId: string;
256
+ externalRef: string;
257
+ threadRef: string;
258
+ conversationId: string;
259
+ /** Unique per reply: deduplicate on it. */
260
+ messageId: string;
261
+ body: string;
262
+ /** ISO 8601 UTC. */
263
+ sentAt: string;
264
+ sender: {
265
+ /** Your own id for the staff member, or `null` when they have none. */
266
+ userRef: string | null;
267
+ name: string;
268
+ };
269
+ deliveryStatus: 'pending' | 'delivered' | 'failed';
270
+ }
271
+ /** One page of {@link CrmPartnerClient.listPartnerMessageChanges}. */
272
+ interface PartnerMessageChangesPage {
273
+ items: PartnerMessageChange[];
274
+ nextCursor: string | null;
275
+ }
151
276
  interface CrmPartnerClient {
152
277
  /**
153
278
  * Idempotent: provisions the workspace for `externalRef`, or resumes/returns it. Optional
@@ -207,7 +332,57 @@ interface CrmPartnerClient {
207
332
  cursor?: string;
208
333
  limit?: number;
209
334
  }): Promise<ContactChanges>;
335
+ /**
336
+ * Hand a customer message to the CRM. Idempotent on `messageRef`: 201 resolves `created: true`,
337
+ * a repeat (200) resolves `created: false` with the same ids. One `threadRef` belongs to one
338
+ * contact. Rejections surface as {@link CrmPartnerError} with the CRM's code, for example
339
+ * `PARTNER_CHANNEL_DISABLED`, `CONTACT_NOT_FOUND`, `MESSAGE_REF_CONFLICT` (the `messageRef` is already used on
340
+ * another thread; not retryable), `THREAD_CONTACT_MISMATCH`, `WORKSPACE_DISABLED`,
341
+ * `RATE_LIMITED` and `SERVICE_BUSY`.
342
+ */
343
+ sendPartnerMessage(externalRef: string, message: PartnerMessageInput): Promise<PartnerMessageResult>;
344
+ /** Delete the conversation for `threadRef`. `deleted: false` when there is none (already deleted, or never sent). */
345
+ deletePartnerConversation(externalRef: string, threadRef: string): Promise<{
346
+ deleted: boolean;
347
+ }>;
348
+ /**
349
+ * One page of staff replies owed to you, oldest first. `limit` is 1 to 500 (default 100).
350
+ *
351
+ * Presenting a `cursor` acknowledges every row before it, so persist a page before calling
352
+ * again with its `nextCursor`. Keep calling until `items` is empty and store the cursor that
353
+ * call returns for the next poll. `nextCursor` is null only when no cursor was sent and there
354
+ * are no rows. Never construct a cursor, and never reuse one across workspaces. A 400
355
+ * `VALIDATION_ERROR` on a stored cursor means drop it and restart with none. Rows are kept 30
356
+ * days. A reply appears a few seconds after it is sent. Delivered rows are included
357
+ * (`deliveryStatus`); deduplicate on `messageId`.
358
+ */
359
+ listPartnerMessageChanges(externalRef: string, query?: {
360
+ cursor?: string;
361
+ limit?: number;
362
+ }): Promise<PartnerMessageChangesPage>;
363
+ /**
364
+ * Register (or change) the URL that receives staff replies. The first registration returns the
365
+ * signing `secret`, shown once: store it. Changing the URL returns no secret. The URL must be
366
+ * HTTPS (400 `VALIDATION_ERROR` otherwise).
367
+ */
368
+ setWebhook(input: {
369
+ url: string;
370
+ }): Promise<{
371
+ url: string;
372
+ secret?: string;
373
+ }>;
374
+ /** The registered webhook, or `null` when none is registered (404). The secret is never returned. */
375
+ getWebhook(): Promise<{
376
+ url: string;
377
+ hasSecret: true;
378
+ } | null>;
379
+ /** Replace the signing secret; the old one stops working at once. Throws a 404 error when no webhook is registered. */
380
+ rotateWebhookSecret(): Promise<{
381
+ secret: string;
382
+ }>;
383
+ /** Remove the webhook. Resolves also when none was registered. */
384
+ deleteWebhook(): Promise<void>;
210
385
  }
211
386
  declare function createCrmPartnerClient(opts: CrmPartnerClientOptions): CrmPartnerClient;
212
387
 
213
- export { AI_MONTHLY_CAP_MAX_CREDITS, CONTACT_CHANGES_MAX_LIMIT, CONTACT_REF_PATTERN, ContactChanges, ContactRefUpsertBody, ContactRefUpsertResult, type CrmPartnerClient, type CrmPartnerClientOptions, CrmPartnerError, EXTERNAL_REF_PATTERN, PartnerContactEraseByIdentityBody, PartnerContactEraseByIdentityResult, PartnerContactEraseResult, type PartnerRotatedSecret, type PartnerUsageRange, type PartnerWorkspace, type PartnerWorkspaceDetail, type PartnerWorkspacePatchBody, type PartnerWorkspaceUpsertBody, type PartnerWorkspaceUpsertResult, PartnerWorkspaceUsage, createCrmPartnerClient };
388
+ export { AI_MONTHLY_CAP_MAX_CREDITS, CONTACT_CHANGES_MAX_LIMIT, CONTACT_REF_PATTERN, ContactChanges, ContactRefUpsertBody, ContactRefUpsertResult, type CrmPartnerClient, type CrmPartnerClientOptions, CrmPartnerError, EXTERNAL_REF_PATTERN, PARTNER_MESSAGE_CHANGES_MAX_LIMIT, PartnerContactEraseByIdentityBody, PartnerContactEraseByIdentityResult, PartnerContactEraseResult, type PartnerMessageChange, type PartnerMessageChangesPage, type PartnerMessageInput, type PartnerMessageResult, type PartnerMessageSentEvent, type PartnerRotatedSecret, type PartnerUsageRange, PartnerWebhookVerificationError, type PartnerWebhookVerificationReason, type PartnerWorkspace, type PartnerWorkspaceDetail, type PartnerWorkspacePatchBody, type PartnerWorkspaceUpsertBody, type PartnerWorkspaceUpsertResult, PartnerWorkspaceUsage, type VerifyPartnerWebhookInput, createCrmPartnerClient, verifyPartnerWebhook };
package/dist/partner.js CHANGED
@@ -1,2 +1,2 @@
1
- function W(e){return e.replace(/\/+$/,"").replace(/\/api$/,"")}function R(e,p){let y=e??globalThis.fetch;if(typeof y!="function")throw new Error(`${p}: no fetch implementation available. Pass \`fetch\` explicitly.`);return y}async function x(e,p,y,h){let P=new AbortController,i=!1,c=setTimeout(()=>{i=!0,P.abort()},p);try{let f={Accept:"application/json",...h.headers},C=h.body!==void 0;C&&(f["Content-Type"]="application/json");let s=await e(y,{method:h.method,headers:f,body:C?JSON.stringify(h.body):void 0,signal:P.signal}),n=await s.json().catch(()=>null);return i?{ok:!1,kind:"timeout"}:{ok:!0,status:s.status,json:n}}catch{return{ok:!1,kind:i?"timeout":"network"}}finally{clearTimeout(c)}}var U=/^[A-Za-z0-9_.:-]{1,60}$/;function A(e,p,y){let h=`HTTP_${p}`,P=i=>typeof i!="string"||!U.test(i)||y.some(c=>c&&i.includes(c))?null:i;if(e&&typeof e=="object"){let i=e,c=i.error;return P(i.code)??P(c)??(c&&typeof c=="object"?P(c.code):null)??h}return h}var m=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var l=class e extends Error{constructor(p,y){super(p===0?`CRM partner API unreachable (${y})`:`CRM partner API ${p} ${y}`),this.name="CrmPartnerError",this.status=p,this.code=y,Object.setPrototypeOf(this,e.prototype)}},I=/^[A-Za-z0-9_-]{1,64}$/,$=/^[A-Za-z0-9._:-]{1,200}$/,j=200,D=1e8,w=e=>({externalRef:e.external_ref,workspaceId:e.workspace_id,embedAppId:e.embed_app_id,enabled:e.enabled,aiMonthlyCapCredits:typeof e.ai_monthly_cap_credits=="number"?e.ai_monthly_cap_credits:null}),M=/^\d{4}-\d{2}-\d{2}$/;function E(e){let p=e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e;if(typeof p!="string"||!M.test(p)||Number.isNaN(Date.parse(`${p}T00:00:00Z`))||new Date(`${p}T00:00:00Z`).toISOString().slice(0,10)!==p)throw new l(400,"invalid_date");return p}function T(e){if(e==null)return e;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>D)throw new l(400,"invalid_cap");return e}var B=e=>e===null||typeof e=="string";function b(e){return m(e)&&typeof e.external_ref=="string"&&B(e.workspace_id)&&B(e.embed_app_id)&&typeof e.enabled=="boolean"}function F(e){if(!e.crmBaseUrl)throw new Error("createCrmPartnerClient: `crmBaseUrl` is required.");if(!e.partnerKey)throw new Error("createCrmPartnerClient: `partnerKey` is required.");let p=R(e.fetch,"createCrmPartnerClient"),y=e.timeoutMs??15e3,h=`${W(e.crmBaseUrl)}/api/partner/v1/workspaces`,P=[e.partnerKey];function i(s){if(typeof s!="string"||!I.test(s))throw new l(400,"invalid_external_ref");return s}async function c(s,n,o){let t=await x(p,y,`${h}/${n}`,{method:s,headers:{Authorization:`Bearer ${e.partnerKey}`},body:o});if(!t.ok)throw new l(0,t.kind);if(t.status<200||t.status>=300)throw new l(t.status,A(t.json,t.status,P));return{status:t.status,json:t.json}}let f=s=>new l(s,"bad_response");function C(s){if(typeof s!="string"||!$.test(s))throw new l(400,"invalid_contact_ref");return s}return{async upsertWorkspace(s,n){let o=i(s),{aiMonthlyCapCredits:t,...r}=n,a=T(t),u=a===void 0?r:{...r,ai_monthly_cap_credits:a},{status:g,json:k}=await c("PUT",o,u);if(!b(k))throw f(g);let d=k;if(d.created===!0){let _=d.embed_app_secret;if(typeof _!="string"||!_)throw f(g);return{...w(d),created:!0,embedAppSecret:_}}if(d.created===!1)return{...w(d),created:!1};throw f(g)},async getWorkspace(s){let n=i(s);try{let{status:o,json:t}=await c("GET",n);if(!b(t)||typeof t.state!="string")throw f(o);let r=t.ai;return{...w(t),state:t.state,ai:m(r)&&typeof r.period=="string"&&typeof r.used_credits=="number"?{period:r.period,usedCredits:r.used_credits}:null}}catch(o){if(o instanceof l&&o.status===404)return null;throw o}},async updateWorkspace(s,n){let o=i(s),t={};n.enabled!==void 0&&(t.enabled=n.enabled),n.name!==void 0&&(t.name=n.name);let r=T(n.aiMonthlyCapCredits);r!==void 0&&(t.ai_monthly_cap_credits=r);let{status:a,json:u}=await c("PATCH",o,t);if(!b(u))throw f(a);return w(u)},async getWorkspaceUsage(s,n){let o=i(s),t=new URLSearchParams({from:E(n.from),to:E(n.to)});try{let{status:r,json:a}=await c("GET",`${o}/usage?${t.toString()}`);if(!m(a)||!m(a.totals)||!m(a.cap)||!Array.isArray(a.by_operation))throw f(r);return a}catch(r){if(r instanceof l&&r.status===404)return null;throw r}},async rotateWorkspaceSecret(s){let n=i(s),{status:o,json:t}=await c("POST",`${n}/rotate-secret`),r=t;if(!m(t)||typeof r?.embed_app_id!="string"||typeof r.embed_app_secret!="string"||!r.embed_app_secret)throw f(o);return{embedAppId:r.embed_app_id,embedAppSecret:r.embed_app_secret}},async upsertContact(s,n,o){let t=i(s),r=C(n),{status:a,json:u}=await c("PUT",`${t}/contacts/${encodeURIComponent(r)}`,o);if(!m(u)||!m(u.contact)||typeof u.created!="boolean"||typeof u.consent_applied!="boolean")throw f(a);return u},async eraseContact(s,n){let o=i(s),t=C(n);try{let{status:r,json:a}=await c("DELETE",`${o}/contacts/${encodeURIComponent(t)}`);if(!m(a)||a.erased!==!0||typeof a.contact_id!="string")throw f(r);return a}catch(r){if(r instanceof l&&r.status===404)return null;throw r}},async eraseContactsByIdentity(s,n){let o=i(s),t=typeof n?.phone=="string"?n.phone.trim():void 0,r=typeof n?.email=="string"?n.email.trim():void 0,a=t!==void 0&&/\d/.test(t),u=r!==void 0&&r.includes("@");if(n?.phone!==void 0&&!a||n?.email!==void 0&&!u||!a&&!u)throw new l(400,"invalid_identity");n.ref!==void 0&&C(n.ref);let g={};a&&(g.phone=t),u&&(g.email=r),n.ref!==void 0&&(g.ref=n.ref);try{let{status:k,json:d}=await c("POST",`${o}/contacts/erase-by-identity`,g);if(!m(d)||typeof d.erased!="number"||!Array.isArray(d.contact_ids)||typeof d.skipped_linked_elsewhere!="number")throw f(k);return d}catch(k){if(k instanceof l&&k.status===404)return null;throw k}},async listContactChanges(s,n={}){let o=i(s),{since:t,cursor:r,limit:a}=n;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>j))throw new l(400,"invalid_limit");let u=new URLSearchParams;t!==void 0&&u.set("since",t),r!==void 0&&u.set("cursor",r),a!==void 0&&u.set("limit",String(a));let g=u.toString(),{status:k,json:d}=await c("GET",`${o}/contacts/changes${g?`?${g}`:""}`);if(!m(d)||!Array.isArray(d.items)||!(d.next_cursor===null||typeof d.next_cursor=="string"))throw f(k);return d}}}export{D as AI_MONTHLY_CAP_MAX_CREDITS,j as CONTACT_CHANGES_MAX_LIMIT,$ as CONTACT_REF_PATTERN,l as CrmPartnerError,I as EXTERNAL_REF_PATTERN,F as createCrmPartnerClient};
1
+ function A(e){return e.replace(/\/+$/,"").replace(/\/api$/,"")}function T(e,n){let c=e??globalThis.fetch;if(typeof c!="function")throw new Error(`${n}: no fetch implementation available. Pass \`fetch\` explicitly.`);return c}async function U(e,n,c,h){let k=new AbortController,g=!1,u=setTimeout(()=>{g=!0,k.abort()},n);try{let y={Accept:"application/json",...h.headers},l=h.body!==void 0;l&&(y["Content-Type"]="application/json");let R=await e(c,{method:h.method,headers:y,body:l?JSON.stringify(h.body):void 0,signal:k.signal}),s=await R.json().catch(()=>null);return g?{ok:!1,kind:"timeout"}:{ok:!0,status:R.status,json:s}}catch{return{ok:!1,kind:g?"timeout":"network"}}finally{clearTimeout(u)}}var j=/^[A-Za-z0-9_.:-]{1,60}$/;function B(e,n,c){let h=`HTTP_${n}`,k=g=>typeof g!="string"||!j.test(g)||c.some(u=>u&&g.includes(u))?null:g;if(e&&typeof e=="object"){let g=e,u=g.error;return k(g.code)??k(u)??(u&&typeof u=="object"?k(u.code):null)??h}return h}var f=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);import{createHmac as O,timingSafeEqual as L}from"crypto";var _=class e extends Error{constructor(n){super(`Partner webhook verification failed (${n})`),this.name="PartnerWebhookVerificationError",this.reason=n,Object.setPrototypeOf(this,e.prototype)}},F=300,G=/^[0-9a-fA-F]{64}$/,q=/^[0-9]{1,15}$/;function M(e,n){if(typeof e.get=="function")return e.get(n)||void 0;let c=e;for(let h of Object.keys(c)){if(h.toLowerCase()!==n)continue;let k=c[h],g=Array.isArray(k)?k[0]:k;if(typeof g=="string"&&g!=="")return g}}var C=e=>typeof e=="string",$=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function H(e){let n;try{n=JSON.parse(e)}catch{throw new _("bad_payload")}if(!$(n)||n.event!=="partner_message.sent")throw new _("bad_payload");let{sender:c}=n;if(!C(n.delivery_id)||!C(n.external_ref)||!C(n.thread_ref)||!C(n.conversation_id)||!C(n.message_id)||!C(n.body)||!C(n.sent_at)||!$(c)||!C(c.name)||!(c.user_ref===null||C(c.user_ref)))throw new _("bad_payload");return{event:"partner_message.sent",deliveryId:n.delivery_id,externalRef:n.external_ref,threadRef:n.thread_ref,conversationId:n.conversation_id,messageId:n.message_id,body:n.body,sentAt:n.sent_at,sender:{userRef:c.user_ref,name:c.name}}}function V(e){if(typeof e.secret!="string"||e.secret==="")throw new TypeError("verifyPartnerWebhook: secret must be a non-empty string");if(typeof e.rawBody!="string")throw new TypeError("verifyPartnerWebhook: rawBody must be a string (the body exactly as received)");if(e.toleranceSeconds!==void 0&&!(Number.isFinite(e.toleranceSeconds)&&e.toleranceSeconds>=0))throw new TypeError("verifyPartnerWebhook: toleranceSeconds must be a finite number of at least 0");let n=M(e.headers,"x-crm-timestamp"),c=M(e.headers,"x-crm-signature");if(n===void 0||c===void 0)throw new _("missing_headers");let h=e.toleranceSeconds??F,k=(e.now??Date.now)()/1e3;if(!q.test(n)||!Number.isFinite(k)||Math.abs(k-Number(n))>h)throw new _("stale_timestamp");if(!G.test(c))throw new _("bad_signature");let g=O("sha256",e.secret).update(`${n}.${e.rawBody}`).digest();if(!L(g,Buffer.from(c,"hex")))throw new _("bad_signature");return H(e.rawBody)}var p=class e extends Error{constructor(n,c){super(n===0?`CRM partner API unreachable (${c})`:`CRM partner API ${n} ${c}`),this.name="CrmPartnerError",this.status=n,this.code=c,Object.setPrototypeOf(this,e.prototype)}},K=/^[A-Za-z0-9_-]{1,64}$/,v=/^[A-Za-z0-9._:-]{1,200}$/,X=200,Z=500,J=1e8,W=e=>({externalRef:e.external_ref,workspaceId:e.workspace_id,embedAppId:e.embed_app_id,enabled:e.enabled,aiMonthlyCapCredits:typeof e.ai_monthly_cap_credits=="number"?e.ai_monthly_cap_credits:null,partnerChannelEnabled:e.partner_channel_enabled===!0,webhookUrl:typeof e.webhook_url=="string"?e.webhook_url:null});function Q(e){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new p(400,"invalid_date");return e.toISOString()}if(typeof e!="string")throw new p(400,"invalid_date");return e}function Y(e){return f(e)&&typeof e.delivery_id=="string"&&typeof e.external_ref=="string"&&typeof e.thread_ref=="string"&&typeof e.conversation_id=="string"&&typeof e.message_id=="string"&&typeof e.body=="string"&&typeof e.sent_at=="string"&&f(e.sender)&&I(e.sender.user_ref)&&typeof e.sender.name=="string"&&(e.delivery_status==="pending"||e.delivery_status==="delivered"||e.delivery_status==="failed")}var ee=/^\d{4}-\d{2}-\d{2}$/;function N(e){let n=e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e;if(typeof n!="string"||!ee.test(n)||Number.isNaN(Date.parse(`${n}T00:00:00Z`))||new Date(`${n}T00:00:00Z`).toISOString().slice(0,10)!==n)throw new p(400,"invalid_date");return n}function D(e){if(e==null)return e;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>J)throw new p(400,"invalid_cap");return e}var I=e=>e===null||typeof e=="string";function S(e){return f(e)&&typeof e.external_ref=="string"&&I(e.workspace_id)&&I(e.embed_app_id)&&typeof e.enabled=="boolean"}function ae(e){if(!e.crmBaseUrl)throw new Error("createCrmPartnerClient: `crmBaseUrl` is required.");if(!e.partnerKey)throw new Error("createCrmPartnerClient: `partnerKey` is required.");let n=T(e.fetch,"createCrmPartnerClient"),c=e.timeoutMs??15e3,h=`${A(e.crmBaseUrl)}/api/partner/v1`,k=`${h}/workspaces`,g=[e.partnerKey];function u(s){if(typeof s!="string"||!K.test(s))throw new p(400,"invalid_external_ref");return s}async function y(s,t,i,a=k){let r=await U(n,c,`${a}/${t}`,{method:s,headers:{Authorization:`Bearer ${e.partnerKey}`},body:i});if(!r.ok)throw new p(0,r.kind);if(r.status<200||r.status>=300)throw new p(r.status,B(r.json,r.status,g));return{status:r.status,json:r.json}}let l=s=>new p(s,"bad_response");function R(s){if(typeof s!="string"||!v.test(s))throw new p(400,"invalid_contact_ref");return s}return{async upsertWorkspace(s,t){let i=u(s),{aiMonthlyCapCredits:a,partnerChannelEnabled:r,webhookUrl:o,...d}=t,w=D(a),m={...d};w!==void 0&&(m.ai_monthly_cap_credits=w),r!==void 0&&(m.partner_channel_enabled=r),o!==void 0&&(m.webhook_url=o);let{status:b,json:E}=await y("PUT",i,m);if(!S(E))throw l(b);let P=E;if(P.created===!0){let x=P.embed_app_secret;if(typeof x!="string"||!x)throw l(b);return{...W(P),created:!0,embedAppSecret:x}}if(P.created===!1)return{...W(P),created:!1};throw l(b)},async getWorkspace(s){let t=u(s);try{let{status:i,json:a}=await y("GET",t);if(!S(a)||typeof a.state!="string")throw l(i);let r=a.ai;return{...W(a),state:a.state,ai:f(r)&&typeof r.period=="string"&&typeof r.used_credits=="number"?{period:r.period,usedCredits:r.used_credits}:null}}catch(i){if(i instanceof p&&i.status===404)return null;throw i}},async updateWorkspace(s,t){let i=u(s),a={};t.enabled!==void 0&&(a.enabled=t.enabled),t.name!==void 0&&(a.name=t.name);let r=D(t.aiMonthlyCapCredits);r!==void 0&&(a.ai_monthly_cap_credits=r),t.partnerChannelEnabled!==void 0&&(a.partner_channel_enabled=t.partnerChannelEnabled),t.webhookUrl!==void 0&&(a.webhook_url=t.webhookUrl);let{status:o,json:d}=await y("PATCH",i,a);if(!S(d))throw l(o);return W(d)},async getWorkspaceUsage(s,t){let i=u(s),a=new URLSearchParams({from:N(t.from),to:N(t.to)});try{let{status:r,json:o}=await y("GET",`${i}/usage?${a.toString()}`);if(!f(o)||!f(o.totals)||!f(o.cap)||!Array.isArray(o.by_operation))throw l(r);return o}catch(r){if(r instanceof p&&r.status===404)return null;throw r}},async rotateWorkspaceSecret(s){let t=u(s),{status:i,json:a}=await y("POST",`${t}/rotate-secret`),r=a;if(!f(a)||typeof r?.embed_app_id!="string"||typeof r.embed_app_secret!="string"||!r.embed_app_secret)throw l(i);return{embedAppId:r.embed_app_id,embedAppSecret:r.embed_app_secret}},async upsertContact(s,t,i){let a=u(s),r=R(t),{status:o,json:d}=await y("PUT",`${a}/contacts/${encodeURIComponent(r)}`,i);if(!f(d)||!f(d.contact)||typeof d.created!="boolean"||typeof d.consent_applied!="boolean")throw l(o);return d},async eraseContact(s,t){let i=u(s),a=R(t);try{let{status:r,json:o}=await y("DELETE",`${i}/contacts/${encodeURIComponent(a)}`);if(!f(o)||o.erased!==!0||typeof o.contact_id!="string")throw l(r);return o}catch(r){if(r instanceof p&&r.status===404)return null;throw r}},async eraseContactsByIdentity(s,t){let i=u(s),a=typeof t?.phone=="string"?t.phone.trim():void 0,r=typeof t?.email=="string"?t.email.trim():void 0,o=a!==void 0&&/\d/.test(a),d=r!==void 0&&r.includes("@");if(t?.phone!==void 0&&!o||t?.email!==void 0&&!d||!o&&!d)throw new p(400,"invalid_identity");t.ref!==void 0&&R(t.ref);let w={};o&&(w.phone=a),d&&(w.email=r),t.ref!==void 0&&(w.ref=t.ref);try{let{status:m,json:b}=await y("POST",`${i}/contacts/erase-by-identity`,w);if(!f(b)||typeof b.erased!="number"||!Array.isArray(b.contact_ids)||typeof b.skipped_linked_elsewhere!="number")throw l(m);return b}catch(m){if(m instanceof p&&m.status===404)return null;throw m}},async listContactChanges(s,t={}){let i=u(s),{since:a,cursor:r,limit:o}=t;if(o!==void 0&&(!Number.isInteger(o)||o<1||o>X))throw new p(400,"invalid_limit");let d=new URLSearchParams;a!==void 0&&d.set("since",a),r!==void 0&&d.set("cursor",r),o!==void 0&&d.set("limit",String(o));let w=d.toString(),{status:m,json:b}=await y("GET",`${i}/contacts/changes${w?`?${w}`:""}`);if(!f(b)||!Array.isArray(b.items)||!(b.next_cursor===null||typeof b.next_cursor=="string"))throw l(m);return b},async sendPartnerMessage(s,t){let i=u(s),a={contact_ref:R(t.contactRef),thread_ref:t.threadRef,message_ref:t.messageRef,body:t.body,sent_at:Q(t.sentAt)};t.title!==void 0&&(a.title=t.title),t.teamRef!==void 0&&(a.team_ref=t.teamRef);let{status:r,json:o}=await y("POST",`${i}/messages`,a);if(!f(o)||typeof o.conversation_id!="string"||typeof o.message_id!="string"||typeof o.created!="boolean")throw l(r);let d=o;return{conversationId:d.conversation_id,messageId:d.message_id,created:d.created}},async deletePartnerConversation(s,t){let i=u(s);if(typeof t!="string"||!v.test(t)||t==="."||t==="..")throw new p(400,"invalid_thread_ref");let{status:a,json:r}=await y("DELETE",`${i}/conversations/${encodeURIComponent(t)}`);if(!f(r)||typeof r.deleted!="boolean")throw l(a);return{deleted:r.deleted}},async listPartnerMessageChanges(s,t={}){let i=u(s),{cursor:a,limit:r}=t;if(r!==void 0&&(!Number.isInteger(r)||r<1||r>Z))throw new p(400,"invalid_limit");let o=new URLSearchParams;a!==void 0&&o.set("cursor",a),r!==void 0&&o.set("limit",String(r));let d=o.toString(),{status:w,json:m}=await y("GET",`${i}/messages/changes${d?`?${d}`:""}`);if(!f(m)||!Array.isArray(m.items)||!(m.next_cursor===null||typeof m.next_cursor=="string"))throw l(w);let b=m;return{items:b.items.map(P=>{if(!Y(P))throw l(w);return{deliveryId:P.delivery_id,externalRef:P.external_ref,threadRef:P.thread_ref,conversationId:P.conversation_id,messageId:P.message_id,body:P.body,sentAt:P.sent_at,sender:{userRef:P.sender.user_ref,name:P.sender.name},deliveryStatus:P.delivery_status}}),nextCursor:b.next_cursor}},async setWebhook(s){let t={url:s.url},{status:i,json:a}=await y("PUT","webhook",t,h);if(!f(a)||typeof a.url!="string")throw l(i);if(i===201){let r=a.secret;if(typeof r!="string"||!r)throw l(i);return{url:a.url,secret:r}}return{url:a.url}},async getWebhook(){try{let{status:s,json:t}=await y("GET","webhook",void 0,h);if(!f(t)||typeof t.url!="string"||t.has_secret!==!0)throw l(s);return{url:t.url,hasSecret:!0}}catch(s){if(s instanceof p&&s.status===404)return null;throw s}},async rotateWebhookSecret(){let{status:s,json:t}=await y("POST","webhook/rotate-secret",void 0,h),i=f(t)?t.secret:void 0;if(typeof i!="string"||!i)throw l(s);return{secret:i}},async deleteWebhook(){await y("DELETE","webhook",void 0,h)}}}export{J as AI_MONTHLY_CAP_MAX_CREDITS,X as CONTACT_CHANGES_MAX_LIMIT,v as CONTACT_REF_PATTERN,p as CrmPartnerError,K as EXTERNAL_REF_PATTERN,Z as PARTNER_MESSAGE_CHANGES_MAX_LIMIT,_ as PartnerWebhookVerificationError,ae as createCrmPartnerClient,V as verifyPartnerWebhook};
2
2
  //# sourceMappingURL=partner.js.map