@first-to-fly/crm-sdk 1.12.0 → 1.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -8
- package/dist/api.d.cts +2 -2
- package/dist/api.d.ts +2 -2
- package/dist/{crm-contracts-Cezh6uNS.d.cts → crm-contracts-Bl6_u353.d.cts} +55 -1
- package/dist/{crm-contracts-Cezh6uNS.d.ts → crm-contracts-Bl6_u353.d.ts} +55 -1
- package/dist/partner.cjs +1 -1
- package/dist/partner.cjs.map +1 -1
- package/dist/partner.d.cts +71 -8
- package/dist/partner.d.ts +71 -8
- package/dist/partner.js +1 -1
- package/dist/partner.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -885,7 +885,8 @@ app.post('/hooks/crm', express.raw({ type: 'application/json', limit: '1mb' }),
|
|
|
885
885
|
```
|
|
886
886
|
|
|
887
887
|
The event is `{ event: 'partner_message.sent', deliveryId, externalRef, threadRef,
|
|
888
|
-
conversationId, messageId, body, sentAt, sender: { userRef, name } }`. `
|
|
888
|
+
conversationId, messageId, body, sentAt, sender: { userRef, name }, media }`. `media` is the
|
|
889
|
+
reply's file (see "7. Photos and files"), `[]` for a text reply. `sender.userRef` is
|
|
889
890
|
`null` when the staff member has no id of yours. `verifyPartnerWebhook` checks, in this order:
|
|
890
891
|
both headers are present (`missing_headers`), the timestamp is within the tolerance of now in
|
|
891
892
|
either direction (`stale_timestamp`), the signature matches (`bad_signature`) and only then
|
|
@@ -958,7 +959,56 @@ Permanently deletes the conversation, its messages and any replies still owed to
|
|
|
958
959
|
contact stays. It is idempotent (`deleted: false` when nothing matched). Cancel your own
|
|
959
960
|
pending retries for that thread first: a later push with the same `threadRef` creates a new
|
|
960
961
|
conversation. Erasing a contact (`eraseContact`) also deletes that contact's threads on this
|
|
961
|
-
channel.
|
|
962
|
+
channel. Both delete the threads' photos and files too.
|
|
963
|
+
|
|
964
|
+
#### 7. Photos and files
|
|
965
|
+
|
|
966
|
+
Off by default. Switch them on per workspace, with the channel on as well:
|
|
967
|
+
|
|
968
|
+
```typescript
|
|
969
|
+
await partner.updateWorkspace('tenant_1', { partnerFilesEnabled: true }); // or on upsertWorkspace
|
|
970
|
+
```
|
|
971
|
+
|
|
972
|
+
A message carries at most **one file**: a JPEG, PNG or WebP photo, or a PDF, DOC or DOCX
|
|
973
|
+
document, of at most 10 MB (10,485,760 bytes). The CRM keeps the file. Your side keeps its id
|
|
974
|
+
and fetches a link when it shows the file.
|
|
975
|
+
|
|
976
|
+
**From your customer.** Pass `file`. `body` is then an optional caption (`''` for none). The
|
|
977
|
+
call goes as `multipart/form-data` to `POST /workspaces/{externalRef}/messages/file`.
|
|
978
|
+
|
|
979
|
+
```typescript
|
|
980
|
+
const { messageId, media } = await partner.sendPartnerMessage('tenant_1', {
|
|
981
|
+
contactRef: 'customer:1',
|
|
982
|
+
threadRef: 'thread:1',
|
|
983
|
+
messageRef: 'msg:2',
|
|
984
|
+
body: 'Her homework', // or '' for no caption
|
|
985
|
+
sentAt: new Date(),
|
|
986
|
+
file: { data: bytes, name: 'homework.jpg', type: 'image/jpeg' }, // a Uint8Array or a Blob
|
|
987
|
+
});
|
|
988
|
+
// media: [{ id, name, mimeType, size, kind: 'image' }]
|
|
989
|
+
```
|
|
990
|
+
|
|
991
|
+
A repeat of the same `messageRef` resolves `created: false` with the file stored the first
|
|
992
|
+
time, and stores nothing new. Besides the codes of a text push: `400` / `VALIDATION_ERROR`
|
|
993
|
+
for a missing file, another type, an empty or larger file, or a file whose content does not
|
|
994
|
+
match its type, and `409` / `PARTNER_FILES_DISABLED` while files are off (nothing is stored;
|
|
995
|
+
retry once they are on). The push counts toward the same 300 a minute.
|
|
996
|
+
|
|
997
|
+
**From staff.** A staff reply with a file comes with it in `media`, in the webhook event and in
|
|
998
|
+
the feed: `[{ id, name, mimeType, size, kind }]`, `kind` being `image` or `file`. It is `[]` for
|
|
999
|
+
a text reply, and also from a CRM from before files, so the field is always there.
|
|
1000
|
+
|
|
1001
|
+
**Showing a file.** Ask for links when you show the files, and do not store them:
|
|
1002
|
+
|
|
1003
|
+
```typescript
|
|
1004
|
+
const links = await partner.getPartnerMediaLinks('tenant_1', 'thread:1', [media[0].id]);
|
|
1005
|
+
// [{ id, url, expiresAt }]: an https url that works for about one hour
|
|
1006
|
+
```
|
|
1007
|
+
|
|
1008
|
+
Send 1 to 50 ids of that thread. Ids of another thread or workspace, unknown or deleted ones
|
|
1009
|
+
are left out (no error), so an unknown thread resolves `[]`. It works while the channel or its
|
|
1010
|
+
files are switched off, so files sent earlier stay viewable. It counts toward the 120 a minute
|
|
1011
|
+
per-IP limit only.
|
|
962
1012
|
|
|
963
1013
|
#### Retrying
|
|
964
1014
|
|
|
@@ -1065,8 +1115,8 @@ try {
|
|
|
1065
1115
|
### Can a reply be sent? `send_policy`
|
|
1066
1116
|
|
|
1067
1117
|
Every conversation the CRM returns (`crm.conversations.list`, `.get`, and the
|
|
1068
|
-
other conversation responses) carries `send_policy`. It says what
|
|
1069
|
-
that conversation right now. The CRM builds it from the rules its send check
|
|
1118
|
+
other conversation responses) carries `send_policy`. It says what a person may
|
|
1119
|
+
send from that conversation right now. The CRM builds it from the rules its send check
|
|
1070
1120
|
enforces for the window, consent and blocking (the window and consent parts are
|
|
1071
1121
|
the same code), so you do not have to copy those rules into your app.
|
|
1072
1122
|
|
|
@@ -1075,7 +1125,7 @@ the same code), so you do not have to copy those rules into your app.
|
|
|
1075
1125
|
| `free_text` | `'open'` when a normal reply may be sent now, else `'closed'`. |
|
|
1076
1126
|
| `window` | `'24h'` when replies are only allowed for 24 hours after the contact's last message on this channel. `'none'` when there is no time limit. |
|
|
1077
1127
|
| `closes_at` | When the 24-hour window closes (ISO time). It stays set, in the past, after the window has closed. `null` when `window` is `'none'` or the contact has not messaged yet. |
|
|
1078
|
-
| `reason` | Why `free_text` is `'closed'`: `blocked` (contact or conversation is blocked), `suppressed` (email only: the contact's address is on the workspace's Do Not Email list), `opted_out` (contact opted out of WhatsApp), `
|
|
1128
|
+
| `reason` | Why `free_text` is `'closed'`: `blocked` (contact or conversation is blocked), `suppressed` (email only: the contact's address is on the workspace's Do Not Email list), `opted_out` (contact opted out of WhatsApp), `window_closed`, `no_inbound_message` (the contact has never messaged on this channel), `not_supported` (SMS and voice have no reply). `null` when open. The type also lists `consent_required`; it is not given as a `reason` today and reaches you as `template_reason`. |
|
|
1079
1129
|
| `template` | `true` when an approved WhatsApp template may be sent. Only official WhatsApp has templates. |
|
|
1080
1130
|
| `template_reason` | Set when WhatsApp consent is the only thing stopping a template: `consent_required` or `opted_out`. Otherwise `null`. |
|
|
1081
1131
|
| `human_agent` | Messenger only. `available`: the 24 hours have passed and the contact messaged within 7 days, so a reply with the Human Agent tag is allowed. `enabled`: the conversation's Human Agent switch is on and `available` is true. `expires_at`: the contact's last message plus 7 days. Human Agent never makes `free_text` `'open'`: the send must carry `tag: 'HUMAN_AGENT'` and `messaging_type: 'MESSAGE_TAG'`. |
|
|
@@ -1111,9 +1161,12 @@ have the 24-hour window.
|
|
|
1111
1161
|
|
|
1112
1162
|
In a product-managed workspace, WhatsApp consent also applies on official
|
|
1113
1163
|
WhatsApp and WhatsApp Web (WhatsApp Web groups are exempt). A contact who opted
|
|
1114
|
-
out gets nothing. A contact who has not opted in
|
|
1115
|
-
|
|
1116
|
-
WhatsApp Web
|
|
1164
|
+
out gets nothing. A contact who has not opted in cannot be sent a template. On
|
|
1165
|
+
official WhatsApp the 24-hour window decides free text for them, as for anyone.
|
|
1166
|
+
On WhatsApp Web a staff member's own message to them is allowed at any time, so
|
|
1167
|
+
the policy reads `'open'` with `window: 'none'`; a scheduled or automated
|
|
1168
|
+
free-text send to them is only sent within 24 hours of their last message and is
|
|
1169
|
+
otherwise refused with `WHATSAPP_CONSENT_REQUIRED`.
|
|
1117
1170
|
|
|
1118
1171
|
The policy describes the conversation on its own channel (`metadata.channel`).
|
|
1119
1172
|
For a merged conversation that is the channel of the conversation you read, not
|
|
@@ -1125,6 +1178,14 @@ or the window may have closed since you read the policy. So a send can still be
|
|
|
1125
1178
|
refused when the policy said open. Handle the error from `messages.send` as
|
|
1126
1179
|
before.
|
|
1127
1180
|
|
|
1181
|
+
On WhatsApp Web one such check is the pre-send risk check. It answers 422 with
|
|
1182
|
+
code `RISK_WARNING` and a list of `signals` when the message looks risky for the
|
|
1183
|
+
number, for example the first message to a contact who has never written, a
|
|
1184
|
+
link, or the same text sent to many contacts. Nothing is sent. Show the signals
|
|
1185
|
+
and let the person choose; to send anyway, repeat the send with
|
|
1186
|
+
`risk_acknowledged: true`. A contact who has never written always raises it, so
|
|
1187
|
+
a client that starts chats on WhatsApp Web has to handle this answer.
|
|
1188
|
+
|
|
1128
1189
|
### Server-to-server with an API key
|
|
1129
1190
|
|
|
1130
1191
|
For machine-to-machine calls you can pass an `X-API-Key` instead of a bearer:
|
package/dist/api.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as ContactQuery, a as ContactList, b as Contact, c as ContactCreate, d as ContactUpdate, L as LeadQuery, e as ListEnvelope, f as Lead, g as LeadCreate, h as LeadUpdate, T as TaskQuery, i as Task, j as LegacyTaskUpdate, k as LegacyTask, P as ProductQuery, l as Product, m as ProductCreate, n as ProductUpdate, o as ConversationQuery, p as Conversation, q as ConversationUpdate, M as MessageQuery, r as Message, s as MessageCreate, t as TagQuery, u as TagWithUsage, v as TagCreate, w as Tag } from './crm-contracts-
|
|
2
|
-
export { x as ContactChanges, y as ContactChangesQuery, z as ContactRefUpsertBody, A as ContactRefUpsertResult, B as LeadCapture, D as LeadNote, E as LeadNoteCreate, F as PartnerContactEraseByIdentityBody, G as PartnerContactEraseByIdentityResult, H as PartnerContactEraseResult, I as
|
|
1
|
+
import { C as ContactQuery, a as ContactList, b as Contact, c as ContactCreate, d as ContactUpdate, L as LeadQuery, e as ListEnvelope, f as Lead, g as LeadCreate, h as LeadUpdate, T as TaskQuery, i as Task, j as LegacyTaskUpdate, k as LegacyTask, P as ProductQuery, l as Product, m as ProductCreate, n as ProductUpdate, o as ConversationQuery, p as Conversation, q as ConversationUpdate, M as MessageQuery, r as Message, s as MessageCreate, t as TagQuery, u as TagWithUsage, v as TagCreate, w as Tag } from './crm-contracts-Bl6_u353.cjs';
|
|
2
|
+
export { x as ContactChanges, y as ContactChangesQuery, z as ContactRefUpsertBody, A as ContactRefUpsertResult, B as LeadCapture, D as LeadNote, E as LeadNoteCreate, F as PartnerContactEraseByIdentityBody, G as PartnerContactEraseByIdentityResult, H as PartnerContactEraseResult, I as PartnerInboundFileFields, J as PartnerInboundMessageBody, K as PartnerInboundMessageResult, N as PartnerMediaLinksBody, O as PartnerMediaLinksResult, Q as PartnerMessageChange, R as PartnerMessageChanges, S as PartnerMessageChangesQuery, U as PartnerMessageMedia, V as PartnerThreadDeleteResult, W as PartnerWebhookCreated, X as PartnerWebhookGet, Y as PartnerWebhookPutBody, Z as PartnerWebhookRotate, _ as PartnerWebhookUpdated, $ as PartnerWorkspaceCreated, a0 as PartnerWorkspaceDetail, a1 as PartnerWorkspaceExisting, a2 as PartnerWorkspacePatchBody, a3 as PartnerWorkspaceSecret, a4 as PartnerWorkspaceStatus, a5 as PartnerWorkspaceUpsertBody, a6 as PartnerWorkspaceUsage, a7 as PartnerWorkspaceUsageQuery, a8 as TagList } from './crm-contracts-Bl6_u353.cjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Typed CRM REST API client for SaaS backends.
|
package/dist/api.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as ContactQuery, a as ContactList, b as Contact, c as ContactCreate, d as ContactUpdate, L as LeadQuery, e as ListEnvelope, f as Lead, g as LeadCreate, h as LeadUpdate, T as TaskQuery, i as Task, j as LegacyTaskUpdate, k as LegacyTask, P as ProductQuery, l as Product, m as ProductCreate, n as ProductUpdate, o as ConversationQuery, p as Conversation, q as ConversationUpdate, M as MessageQuery, r as Message, s as MessageCreate, t as TagQuery, u as TagWithUsage, v as TagCreate, w as Tag } from './crm-contracts-
|
|
2
|
-
export { x as ContactChanges, y as ContactChangesQuery, z as ContactRefUpsertBody, A as ContactRefUpsertResult, B as LeadCapture, D as LeadNote, E as LeadNoteCreate, F as PartnerContactEraseByIdentityBody, G as PartnerContactEraseByIdentityResult, H as PartnerContactEraseResult, I as
|
|
1
|
+
import { C as ContactQuery, a as ContactList, b as Contact, c as ContactCreate, d as ContactUpdate, L as LeadQuery, e as ListEnvelope, f as Lead, g as LeadCreate, h as LeadUpdate, T as TaskQuery, i as Task, j as LegacyTaskUpdate, k as LegacyTask, P as ProductQuery, l as Product, m as ProductCreate, n as ProductUpdate, o as ConversationQuery, p as Conversation, q as ConversationUpdate, M as MessageQuery, r as Message, s as MessageCreate, t as TagQuery, u as TagWithUsage, v as TagCreate, w as Tag } from './crm-contracts-Bl6_u353.js';
|
|
2
|
+
export { x as ContactChanges, y as ContactChangesQuery, z as ContactRefUpsertBody, A as ContactRefUpsertResult, B as LeadCapture, D as LeadNote, E as LeadNoteCreate, F as PartnerContactEraseByIdentityBody, G as PartnerContactEraseByIdentityResult, H as PartnerContactEraseResult, I as PartnerInboundFileFields, J as PartnerInboundMessageBody, K as PartnerInboundMessageResult, N as PartnerMediaLinksBody, O as PartnerMediaLinksResult, Q as PartnerMessageChange, R as PartnerMessageChanges, S as PartnerMessageChangesQuery, U as PartnerMessageMedia, V as PartnerThreadDeleteResult, W as PartnerWebhookCreated, X as PartnerWebhookGet, Y as PartnerWebhookPutBody, Z as PartnerWebhookRotate, _ as PartnerWebhookUpdated, $ as PartnerWorkspaceCreated, a0 as PartnerWorkspaceDetail, a1 as PartnerWorkspaceExisting, a2 as PartnerWorkspacePatchBody, a3 as PartnerWorkspaceSecret, a4 as PartnerWorkspaceStatus, a5 as PartnerWorkspaceUpsertBody, a6 as PartnerWorkspaceUsage, a7 as PartnerWorkspaceUsageQuery, a8 as TagList } from './crm-contracts-Bl6_u353.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Typed CRM REST API client for SaaS backends.
|
|
@@ -359,6 +359,7 @@ type PartnerWorkspaceUpsertBody = {
|
|
|
359
359
|
currency?: string | undefined;
|
|
360
360
|
timezone?: string | undefined;
|
|
361
361
|
partner_channel_enabled?: boolean | undefined;
|
|
362
|
+
partner_files_enabled?: boolean | undefined;
|
|
362
363
|
webhook_url?: (string | null) | undefined;
|
|
363
364
|
};
|
|
364
365
|
type PartnerWorkspacePatchBody = {
|
|
@@ -366,6 +367,7 @@ type PartnerWorkspacePatchBody = {
|
|
|
366
367
|
name?: string | undefined;
|
|
367
368
|
ai_monthly_cap_credits?: (number | null) | undefined;
|
|
368
369
|
partner_channel_enabled?: boolean | undefined;
|
|
370
|
+
partner_files_enabled?: boolean | undefined;
|
|
369
371
|
webhook_url?: (string | null) | undefined;
|
|
370
372
|
};
|
|
371
373
|
type PartnerWorkspaceCreated = {
|
|
@@ -375,6 +377,7 @@ type PartnerWorkspaceCreated = {
|
|
|
375
377
|
enabled: boolean;
|
|
376
378
|
ai_monthly_cap_credits: number | null;
|
|
377
379
|
partner_channel_enabled: boolean;
|
|
380
|
+
partner_files_enabled: boolean;
|
|
378
381
|
webhook_url: string | null;
|
|
379
382
|
embed_app_secret: string;
|
|
380
383
|
created: true;
|
|
@@ -386,6 +389,7 @@ type PartnerWorkspaceExisting = {
|
|
|
386
389
|
enabled: boolean;
|
|
387
390
|
ai_monthly_cap_credits: number | null;
|
|
388
391
|
partner_channel_enabled: boolean;
|
|
392
|
+
partner_files_enabled: boolean;
|
|
389
393
|
webhook_url: string | null;
|
|
390
394
|
created: false;
|
|
391
395
|
};
|
|
@@ -396,6 +400,7 @@ type PartnerWorkspaceStatus = {
|
|
|
396
400
|
enabled: boolean;
|
|
397
401
|
ai_monthly_cap_credits: number | null;
|
|
398
402
|
partner_channel_enabled: boolean;
|
|
403
|
+
partner_files_enabled: boolean;
|
|
399
404
|
webhook_url: string | null;
|
|
400
405
|
};
|
|
401
406
|
type PartnerWorkspaceDetail = {
|
|
@@ -405,6 +410,7 @@ type PartnerWorkspaceDetail = {
|
|
|
405
410
|
enabled: boolean;
|
|
406
411
|
ai_monthly_cap_credits: number | null;
|
|
407
412
|
partner_channel_enabled: boolean;
|
|
413
|
+
partner_files_enabled: boolean;
|
|
408
414
|
webhook_url: string | null;
|
|
409
415
|
state: "pending" | "owner_created" | "workspace_created" | "app_installed" | "sub_app_created" | "active";
|
|
410
416
|
ai: {
|
|
@@ -502,6 +508,40 @@ type PartnerInboundMessageResult = {
|
|
|
502
508
|
conversation_id: string;
|
|
503
509
|
message_id: string;
|
|
504
510
|
created: boolean;
|
|
511
|
+
media?: {
|
|
512
|
+
id: string;
|
|
513
|
+
name: string;
|
|
514
|
+
mime_type: string;
|
|
515
|
+
size: number;
|
|
516
|
+
kind: "image" | "file";
|
|
517
|
+
}[] | undefined;
|
|
518
|
+
};
|
|
519
|
+
type PartnerInboundFileFields = {
|
|
520
|
+
contact_ref: string;
|
|
521
|
+
thread_ref: string;
|
|
522
|
+
message_ref: string;
|
|
523
|
+
body?: string;
|
|
524
|
+
sent_at: string;
|
|
525
|
+
title?: string | undefined;
|
|
526
|
+
team_ref?: string | undefined;
|
|
527
|
+
direction?: "inbound" | undefined;
|
|
528
|
+
};
|
|
529
|
+
type PartnerMessageMedia = {
|
|
530
|
+
id: string;
|
|
531
|
+
name: string;
|
|
532
|
+
mime_type: string;
|
|
533
|
+
size: number;
|
|
534
|
+
kind: "image" | "file";
|
|
535
|
+
};
|
|
536
|
+
type PartnerMediaLinksBody = {
|
|
537
|
+
media_ids: string[];
|
|
538
|
+
};
|
|
539
|
+
type PartnerMediaLinksResult = {
|
|
540
|
+
items: {
|
|
541
|
+
id: string;
|
|
542
|
+
url: string;
|
|
543
|
+
expires_at: string;
|
|
544
|
+
}[];
|
|
505
545
|
};
|
|
506
546
|
type PartnerThreadDeleteResult = {
|
|
507
547
|
deleted: boolean;
|
|
@@ -523,6 +563,13 @@ type PartnerMessageChange = {
|
|
|
523
563
|
name: string;
|
|
524
564
|
};
|
|
525
565
|
delivery_status: "pending" | "delivered" | "failed";
|
|
566
|
+
media: {
|
|
567
|
+
id: string;
|
|
568
|
+
name: string;
|
|
569
|
+
mime_type: string;
|
|
570
|
+
size: number;
|
|
571
|
+
kind: "image" | "file";
|
|
572
|
+
}[];
|
|
526
573
|
};
|
|
527
574
|
type PartnerMessageChanges = {
|
|
528
575
|
items: {
|
|
@@ -538,6 +585,13 @@ type PartnerMessageChanges = {
|
|
|
538
585
|
name: string;
|
|
539
586
|
};
|
|
540
587
|
delivery_status: "pending" | "delivered" | "failed";
|
|
588
|
+
media: {
|
|
589
|
+
id: string;
|
|
590
|
+
name: string;
|
|
591
|
+
mime_type: string;
|
|
592
|
+
size: number;
|
|
593
|
+
kind: "image" | "file";
|
|
594
|
+
}[];
|
|
541
595
|
}[];
|
|
542
596
|
next_cursor: string | null;
|
|
543
597
|
};
|
|
@@ -1205,4 +1259,4 @@ interface ListEnvelope<T> {
|
|
|
1205
1259
|
pageSize: number;
|
|
1206
1260
|
}
|
|
1207
1261
|
|
|
1208
|
-
export type {
|
|
1262
|
+
export type { PartnerWorkspaceCreated as $, ContactRefUpsertResult as A, LeadCapture as B, ContactQuery as C, LeadNote as D, LeadNoteCreate as E, PartnerContactEraseByIdentityBody as F, PartnerContactEraseByIdentityResult as G, PartnerContactEraseResult as H, PartnerInboundFileFields as I, PartnerInboundMessageBody as J, PartnerInboundMessageResult as K, LeadQuery as L, MessageQuery as M, PartnerMediaLinksBody as N, PartnerMediaLinksResult as O, ProductQuery as P, PartnerMessageChange as Q, PartnerMessageChanges as R, PartnerMessageChangesQuery as S, TaskQuery as T, PartnerMessageMedia as U, PartnerThreadDeleteResult as V, PartnerWebhookCreated as W, PartnerWebhookGet as X, PartnerWebhookPutBody as Y, PartnerWebhookRotate as Z, PartnerWebhookUpdated as _, ContactList as a, PartnerWorkspaceDetail as a0, PartnerWorkspaceExisting as a1, PartnerWorkspacePatchBody as a2, PartnerWorkspaceSecret as a3, PartnerWorkspaceStatus as a4, PartnerWorkspaceUpsertBody as a5, PartnerWorkspaceUsage as a6, PartnerWorkspaceUsageQuery as a7, TagList as a8, Contact as b, ContactCreate as c, ContactUpdate as d, ListEnvelope as e, Lead as f, LeadCreate as g, LeadUpdate as h, Task as i, LegacyTaskUpdate as j, LegacyTask as k, Product as l, ProductCreate as m, ProductUpdate as n, ConversationQuery as o, Conversation as p, ConversationUpdate as q, Message as r, MessageCreate as s, TagQuery as t, TagWithUsage as u, TagCreate as v, Tag as w, ContactChanges as x, ContactChangesQuery as y, ContactRefUpsertBody as z };
|
|
@@ -359,6 +359,7 @@ type PartnerWorkspaceUpsertBody = {
|
|
|
359
359
|
currency?: string | undefined;
|
|
360
360
|
timezone?: string | undefined;
|
|
361
361
|
partner_channel_enabled?: boolean | undefined;
|
|
362
|
+
partner_files_enabled?: boolean | undefined;
|
|
362
363
|
webhook_url?: (string | null) | undefined;
|
|
363
364
|
};
|
|
364
365
|
type PartnerWorkspacePatchBody = {
|
|
@@ -366,6 +367,7 @@ type PartnerWorkspacePatchBody = {
|
|
|
366
367
|
name?: string | undefined;
|
|
367
368
|
ai_monthly_cap_credits?: (number | null) | undefined;
|
|
368
369
|
partner_channel_enabled?: boolean | undefined;
|
|
370
|
+
partner_files_enabled?: boolean | undefined;
|
|
369
371
|
webhook_url?: (string | null) | undefined;
|
|
370
372
|
};
|
|
371
373
|
type PartnerWorkspaceCreated = {
|
|
@@ -375,6 +377,7 @@ type PartnerWorkspaceCreated = {
|
|
|
375
377
|
enabled: boolean;
|
|
376
378
|
ai_monthly_cap_credits: number | null;
|
|
377
379
|
partner_channel_enabled: boolean;
|
|
380
|
+
partner_files_enabled: boolean;
|
|
378
381
|
webhook_url: string | null;
|
|
379
382
|
embed_app_secret: string;
|
|
380
383
|
created: true;
|
|
@@ -386,6 +389,7 @@ type PartnerWorkspaceExisting = {
|
|
|
386
389
|
enabled: boolean;
|
|
387
390
|
ai_monthly_cap_credits: number | null;
|
|
388
391
|
partner_channel_enabled: boolean;
|
|
392
|
+
partner_files_enabled: boolean;
|
|
389
393
|
webhook_url: string | null;
|
|
390
394
|
created: false;
|
|
391
395
|
};
|
|
@@ -396,6 +400,7 @@ type PartnerWorkspaceStatus = {
|
|
|
396
400
|
enabled: boolean;
|
|
397
401
|
ai_monthly_cap_credits: number | null;
|
|
398
402
|
partner_channel_enabled: boolean;
|
|
403
|
+
partner_files_enabled: boolean;
|
|
399
404
|
webhook_url: string | null;
|
|
400
405
|
};
|
|
401
406
|
type PartnerWorkspaceDetail = {
|
|
@@ -405,6 +410,7 @@ type PartnerWorkspaceDetail = {
|
|
|
405
410
|
enabled: boolean;
|
|
406
411
|
ai_monthly_cap_credits: number | null;
|
|
407
412
|
partner_channel_enabled: boolean;
|
|
413
|
+
partner_files_enabled: boolean;
|
|
408
414
|
webhook_url: string | null;
|
|
409
415
|
state: "pending" | "owner_created" | "workspace_created" | "app_installed" | "sub_app_created" | "active";
|
|
410
416
|
ai: {
|
|
@@ -502,6 +508,40 @@ type PartnerInboundMessageResult = {
|
|
|
502
508
|
conversation_id: string;
|
|
503
509
|
message_id: string;
|
|
504
510
|
created: boolean;
|
|
511
|
+
media?: {
|
|
512
|
+
id: string;
|
|
513
|
+
name: string;
|
|
514
|
+
mime_type: string;
|
|
515
|
+
size: number;
|
|
516
|
+
kind: "image" | "file";
|
|
517
|
+
}[] | undefined;
|
|
518
|
+
};
|
|
519
|
+
type PartnerInboundFileFields = {
|
|
520
|
+
contact_ref: string;
|
|
521
|
+
thread_ref: string;
|
|
522
|
+
message_ref: string;
|
|
523
|
+
body?: string;
|
|
524
|
+
sent_at: string;
|
|
525
|
+
title?: string | undefined;
|
|
526
|
+
team_ref?: string | undefined;
|
|
527
|
+
direction?: "inbound" | undefined;
|
|
528
|
+
};
|
|
529
|
+
type PartnerMessageMedia = {
|
|
530
|
+
id: string;
|
|
531
|
+
name: string;
|
|
532
|
+
mime_type: string;
|
|
533
|
+
size: number;
|
|
534
|
+
kind: "image" | "file";
|
|
535
|
+
};
|
|
536
|
+
type PartnerMediaLinksBody = {
|
|
537
|
+
media_ids: string[];
|
|
538
|
+
};
|
|
539
|
+
type PartnerMediaLinksResult = {
|
|
540
|
+
items: {
|
|
541
|
+
id: string;
|
|
542
|
+
url: string;
|
|
543
|
+
expires_at: string;
|
|
544
|
+
}[];
|
|
505
545
|
};
|
|
506
546
|
type PartnerThreadDeleteResult = {
|
|
507
547
|
deleted: boolean;
|
|
@@ -523,6 +563,13 @@ type PartnerMessageChange = {
|
|
|
523
563
|
name: string;
|
|
524
564
|
};
|
|
525
565
|
delivery_status: "pending" | "delivered" | "failed";
|
|
566
|
+
media: {
|
|
567
|
+
id: string;
|
|
568
|
+
name: string;
|
|
569
|
+
mime_type: string;
|
|
570
|
+
size: number;
|
|
571
|
+
kind: "image" | "file";
|
|
572
|
+
}[];
|
|
526
573
|
};
|
|
527
574
|
type PartnerMessageChanges = {
|
|
528
575
|
items: {
|
|
@@ -538,6 +585,13 @@ type PartnerMessageChanges = {
|
|
|
538
585
|
name: string;
|
|
539
586
|
};
|
|
540
587
|
delivery_status: "pending" | "delivered" | "failed";
|
|
588
|
+
media: {
|
|
589
|
+
id: string;
|
|
590
|
+
name: string;
|
|
591
|
+
mime_type: string;
|
|
592
|
+
size: number;
|
|
593
|
+
kind: "image" | "file";
|
|
594
|
+
}[];
|
|
541
595
|
}[];
|
|
542
596
|
next_cursor: string | null;
|
|
543
597
|
};
|
|
@@ -1205,4 +1259,4 @@ interface ListEnvelope<T> {
|
|
|
1205
1259
|
pageSize: number;
|
|
1206
1260
|
}
|
|
1207
1261
|
|
|
1208
|
-
export type {
|
|
1262
|
+
export type { PartnerWorkspaceCreated as $, ContactRefUpsertResult as A, LeadCapture as B, ContactQuery as C, LeadNote as D, LeadNoteCreate as E, PartnerContactEraseByIdentityBody as F, PartnerContactEraseByIdentityResult as G, PartnerContactEraseResult as H, PartnerInboundFileFields as I, PartnerInboundMessageBody as J, PartnerInboundMessageResult as K, LeadQuery as L, MessageQuery as M, PartnerMediaLinksBody as N, PartnerMediaLinksResult as O, ProductQuery as P, PartnerMessageChange as Q, PartnerMessageChanges as R, PartnerMessageChangesQuery as S, TaskQuery as T, PartnerMessageMedia as U, PartnerThreadDeleteResult as V, PartnerWebhookCreated as W, PartnerWebhookGet as X, PartnerWebhookPutBody as Y, PartnerWebhookRotate as Z, PartnerWebhookUpdated as _, ContactList as a, PartnerWorkspaceDetail as a0, PartnerWorkspaceExisting as a1, PartnerWorkspacePatchBody as a2, PartnerWorkspaceSecret as a3, PartnerWorkspaceStatus as a4, PartnerWorkspaceUpsertBody as a5, PartnerWorkspaceUsage as a6, PartnerWorkspaceUsageQuery as a7, TagList as a8, Contact as b, ContactCreate as c, ContactUpdate as d, ListEnvelope as e, Lead as f, LeadCreate as g, LeadUpdate as h, Task as i, LegacyTaskUpdate as j, LegacyTask as k, Product as l, ProductCreate as m, ProductUpdate as n, ConversationQuery as o, Conversation as p, ConversationUpdate as q, Message as r, MessageCreate as s, TagQuery as t, TagWithUsage as u, TagCreate as v, Tag as w, ContactChanges as x, ContactChangesQuery as y, ContactRefUpsertBody as z };
|
package/dist/partner.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var I=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var K=Object.prototype.hasOwnProperty;var X=(e,n)=>{for(var c in n)I(e,c,{get:n[c],enumerable:!0})},Z=(e,n,c,f)=>{if(n&&typeof n=="object"||typeof n=="function")for(let p of z(n))!K.call(e,p)&&p!==c&&I(e,p,{get:()=>n[p],enumerable:!(f=V(n,p))||f.enumerable});return e};var J=e=>Z(I({},"__esModule",{value:!0}),e);var ce={};X(ce,{AI_MONTHLY_CAP_MAX_CREDITS:()=>H,CONTACT_CHANGES_MAX_LIMIT:()=>G,CONTACT_REF_PATTERN:()=>T,CrmPartnerError:()=>g,EXTERNAL_REF_PATTERN:()=>F,PARTNER_MESSAGE_CHANGES_MAX_LIMIT:()=>q,PartnerWebhookVerificationError:()=>_,createCrmPartnerClient:()=>ie,verifyPartnerWebhook:()=>j});module.exports=J(ce);function B(e){return e.replace(/\/+$/,"").replace(/\/api$/,"")}function M(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 $(e,n,c,f){let p=new AbortController,h=!1,u=setTimeout(()=>{h=!0,p.abort()},n);try{let m={Accept:"application/json",...f.headers},l=f.body!==void 0;l&&(m["Content-Type"]="application/json");let R=await e(c,{method:f.method,headers:m,body:l?JSON.stringify(f.body):void 0,signal:p.signal}),s=await R.json().catch(()=>null);return h?{ok:!1,kind:"timeout"}:{ok:!0,status:R.status,json:s}}catch{return{ok:!1,kind:h?"timeout":"network"}}finally{clearTimeout(u)}}var Q=/^[A-Za-z0-9_.:-]{1,60}$/;function v(e,n,c){let f=`HTTP_${n}`,p=h=>typeof h!="string"||!Q.test(h)||c.some(u=>u&&h.includes(u))?null:h;if(e&&typeof e=="object"){let h=e,u=h.error;return p(h.code)??p(u)??(u&&typeof u=="object"?p(u.code):null)??f}return f}var y=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var W=require("crypto"),_=class e extends Error{constructor(n){super(`Partner webhook verification failed (${n})`),this.name="PartnerWebhookVerificationError",this.reason=n,Object.setPrototypeOf(this,e.prototype)}},Y=300,ee=/^[0-9a-fA-F]{64}$/,te=/^[0-9]{1,15}$/;function N(e,n){if(typeof e.get=="function")return e.get(n)||void 0;let c=e;for(let f of Object.keys(c)){if(f.toLowerCase()!==n)continue;let p=c[f],h=Array.isArray(p)?p[0]:p;if(typeof h=="string"&&h!=="")return h}}var C=e=>typeof e=="string",D=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function re(e){let n;try{n=JSON.parse(e)}catch{throw new _("bad_payload")}if(!D(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)||!D(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 j(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=N(e.headers,"x-crm-timestamp"),c=N(e.headers,"x-crm-signature");if(n===void 0||c===void 0)throw new _("missing_headers");let f=e.toleranceSeconds??Y,p=(e.now??Date.now)()/1e3;if(!te.test(n)||!Number.isFinite(p)||Math.abs(p-Number(n))>f)throw new _("stale_timestamp");if(!ee.test(c))throw new _("bad_signature");let h=(0,W.createHmac)("sha256",e.secret).update(`${n}.${e.rawBody}`).digest();if(!(0,W.timingSafeEqual)(h,Buffer.from(c,"hex")))throw new _("bad_signature");return re(e.rawBody)}var g=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)}},F=/^[A-Za-z0-9_-]{1,64}$/,T=/^[A-Za-z0-9._:-]{1,200}$/,G=200,q=500,H=1e8,E=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 se(e){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new g(400,"invalid_date");return e.toISOString()}if(typeof e!="string")throw new g(400,"invalid_date");return e}function ae(e){return y(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"&&y(e.sender)&&U(e.sender.user_ref)&&typeof e.sender.name=="string"&&(e.delivery_status==="pending"||e.delivery_status==="delivered"||e.delivery_status==="failed")}var oe=/^\d{4}-\d{2}-\d{2}$/;function O(e){let n=e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e;if(typeof n!="string"||!oe.test(n)||Number.isNaN(Date.parse(`${n}T00:00:00Z`))||new Date(`${n}T00:00:00Z`).toISOString().slice(0,10)!==n)throw new g(400,"invalid_date");return n}function L(e){if(e==null)return e;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>H)throw new g(400,"invalid_cap");return e}var U=e=>e===null||typeof e=="string";function A(e){return y(e)&&typeof e.external_ref=="string"&&U(e.workspace_id)&&U(e.embed_app_id)&&typeof e.enabled=="boolean"}function ie(e){if(!e.crmBaseUrl)throw new Error("createCrmPartnerClient: `crmBaseUrl` is required.");if(!e.partnerKey)throw new Error("createCrmPartnerClient: `partnerKey` is required.");let n=M(e.fetch,"createCrmPartnerClient"),c=e.timeoutMs??15e3,f=`${B(e.crmBaseUrl)}/api/partner/v1`,p=`${f}/workspaces`,h=[e.partnerKey];function u(s){if(typeof s!="string"||!F.test(s))throw new g(400,"invalid_external_ref");return s}async function m(s,t,i,a=p){let r=await $(n,c,`${a}/${t}`,{method:s,headers:{Authorization:`Bearer ${e.partnerKey}`},body:i});if(!r.ok)throw new g(0,r.kind);if(r.status<200||r.status>=300)throw new g(r.status,v(r.json,r.status,h));return{status:r.status,json:r.json}}let l=s=>new g(s,"bad_response");function R(s){if(typeof s!="string"||!T.test(s))throw new g(400,"invalid_contact_ref");return s}return{async upsertWorkspace(s,t){let i=u(s),{aiMonthlyCapCredits:a,partnerChannelEnabled:r,webhookUrl:o,...d}=t,w=L(a),b={...d};w!==void 0&&(b.ai_monthly_cap_credits=w),r!==void 0&&(b.partner_channel_enabled=r),o!==void 0&&(b.webhook_url=o);let{status:P,json:x}=await m("PUT",i,b);if(!A(x))throw l(P);let k=x;if(k.created===!0){let S=k.embed_app_secret;if(typeof S!="string"||!S)throw l(P);return{...E(k),created:!0,embedAppSecret:S}}if(k.created===!1)return{...E(k),created:!1};throw l(P)},async getWorkspace(s){let t=u(s);try{let{status:i,json:a}=await m("GET",t);if(!A(a)||typeof a.state!="string")throw l(i);let r=a.ai;return{...E(a),state:a.state,ai:y(r)&&typeof r.period=="string"&&typeof r.used_credits=="number"?{period:r.period,usedCredits:r.used_credits}:null}}catch(i){if(i instanceof g&&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=L(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 m("PATCH",i,a);if(!A(d))throw l(o);return E(d)},async getWorkspaceUsage(s,t){let i=u(s),a=new URLSearchParams({from:O(t.from),to:O(t.to)});try{let{status:r,json:o}=await m("GET",`${i}/usage?${a.toString()}`);if(!y(o)||!y(o.totals)||!y(o.cap)||!Array.isArray(o.by_operation))throw l(r);return o}catch(r){if(r instanceof g&&r.status===404)return null;throw r}},async rotateWorkspaceSecret(s){let t=u(s),{status:i,json:a}=await m("POST",`${t}/rotate-secret`),r=a;if(!y(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 m("PUT",`${a}/contacts/${encodeURIComponent(r)}`,i);if(!y(d)||!y(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 m("DELETE",`${i}/contacts/${encodeURIComponent(a)}`);if(!y(o)||o.erased!==!0||typeof o.contact_id!="string")throw l(r);return o}catch(r){if(r instanceof g&&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 g(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:b,json:P}=await m("POST",`${i}/contacts/erase-by-identity`,w);if(!y(P)||typeof P.erased!="number"||!Array.isArray(P.contact_ids)||typeof P.skipped_linked_elsewhere!="number")throw l(b);return P}catch(b){if(b instanceof g&&b.status===404)return null;throw b}},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>G))throw new g(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:b,json:P}=await m("GET",`${i}/contacts/changes${w?`?${w}`:""}`);if(!y(P)||!Array.isArray(P.items)||!(P.next_cursor===null||typeof P.next_cursor=="string"))throw l(b);return P},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:se(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 m("POST",`${i}/messages`,a);if(!y(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"||!T.test(t)||t==="."||t==="..")throw new g(400,"invalid_thread_ref");let{status:a,json:r}=await m("DELETE",`${i}/conversations/${encodeURIComponent(t)}`);if(!y(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>q))throw new g(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:b}=await m("GET",`${i}/messages/changes${d?`?${d}`:""}`);if(!y(b)||!Array.isArray(b.items)||!(b.next_cursor===null||typeof b.next_cursor=="string"))throw l(w);let P=b;return{items:P.items.map(k=>{if(!ae(k))throw l(w);return{deliveryId:k.delivery_id,externalRef:k.external_ref,threadRef:k.thread_ref,conversationId:k.conversation_id,messageId:k.message_id,body:k.body,sentAt:k.sent_at,sender:{userRef:k.sender.user_ref,name:k.sender.name},deliveryStatus:k.delivery_status}}),nextCursor:P.next_cursor}},async setWebhook(s){let t={url:s.url},{status:i,json:a}=await m("PUT","webhook",t,f);if(!y(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 m("GET","webhook",void 0,f);if(!y(t)||typeof t.url!="string"||t.has_secret!==!0)throw l(s);return{url:t.url,hasSecret:!0}}catch(s){if(s instanceof g&&s.status===404)return null;throw s}},async rotateWebhookSecret(){let{status:s,json:t}=await m("POST","webhook/rotate-secret",void 0,f),i=y(t)?t.secret:void 0;if(typeof i!="string"||!i)throw l(s);return{secret:i}},async deleteWebhook(){await m("DELETE","webhook",void 0,f)}}}0&&(module.exports={AI_MONTHLY_CAP_MAX_CREDITS,CONTACT_CHANGES_MAX_LIMIT,CONTACT_REF_PATTERN,CrmPartnerError,EXTERNAL_REF_PATTERN,PARTNER_MESSAGE_CHANGES_MAX_LIMIT,PartnerWebhookVerificationError,createCrmPartnerClient,verifyPartnerWebhook});
|
|
1
|
+
"use strict";var B=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var ee=Object.getOwnPropertyNames;var te=Object.prototype.hasOwnProperty;var re=(e,n)=>{for(var i in n)B(e,i,{get:n[i],enumerable:!0})},ne=(e,n,i,u)=>{if(n&&typeof n=="object"||typeof n=="function")for(let p of ee(n))!te.call(e,p)&&p!==i&&B(e,p,{get:()=>n[p],enumerable:!(u=Y(n,p))||u.enumerable});return e};var se=e=>ne(B({},"__esModule",{value:!0}),e);var me={};re(me,{AI_MONTHLY_CAP_MAX_CREDITS:()=>J,CONTACT_CHANGES_MAX_LIMIT:()=>X,CONTACT_REF_PATTERN:()=>j,CrmPartnerError:()=>b,EXTERNAL_REF_PATTERN:()=>K,PARTNER_MESSAGE_CHANGES_MAX_LIMIT:()=>Z,PartnerWebhookVerificationError:()=>C,createCrmPartnerClient:()=>ye,verifyPartnerWebhook:()=>q});module.exports=se(me);function D(e){return e.replace(/\/+$/,"").replace(/\/api$/,"")}function N(e,n){let i=e??globalThis.fetch;if(typeof i!="function")throw new Error(`${n}: no fetch implementation available. Pass \`fetch\` explicitly.`);return i}async function O(e,n,i,u){let p=new AbortController,y=!1,g=setTimeout(()=>{y=!0,p.abort()},n);try{let h={Accept:"application/json",...u.headers},E=u.body!==void 0;E&&(h["Content-Type"]="application/json");let f=await e(i,{method:u.method,headers:h,body:E?JSON.stringify(u.body):void 0,signal:p.signal}),S=await f.json().catch(()=>null);return y?{ok:!1,kind:"timeout"}:{ok:!0,status:f.status,json:S}}catch{return{ok:!1,kind:y?"timeout":"network"}}finally{clearTimeout(g)}}async function L(e,n,i,u){let p=new AbortController,y=!1,g=setTimeout(()=>{y=!0,p.abort()},n);try{let h=await e(i,{method:u.method,headers:{Accept:"application/json",...u.headers},body:u.form,signal:p.signal}),E=await h.json().catch(()=>null);return y?{ok:!1,kind:"timeout"}:{ok:!0,status:h.status,json:E}}catch{return{ok:!1,kind:y?"timeout":"network"}}finally{clearTimeout(g)}}var ae=/^[A-Za-z0-9_.:-]{1,60}$/;function U(e,n,i){let u=`HTTP_${n}`,p=y=>typeof y!="string"||!ae.test(y)||i.some(g=>g&&y.includes(g))?null:y;if(e&&typeof e=="object"){let y=e,g=y.error;return p(y.code)??p(g)??(g&&typeof g=="object"?p(g.code):null)??u}return u}var P=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var oe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function A(e){if(e===void 0)return[];if(!Array.isArray(e))return null;let n=[];for(let i of e){if(!oe(i)||typeof i.id!="string"||typeof i.name!="string"||typeof i.mime_type!="string"||typeof i.size!="number"||!Number.isFinite(i.size)||i.kind!=="image"&&i.kind!=="file")return null;n.push({id:i.id,name:i.name,mimeType:i.mime_type,size:i.size,kind:i.kind})}return n}var I=require("crypto");var C=class e extends Error{constructor(n){super(`Partner webhook verification failed (${n})`),this.name="PartnerWebhookVerificationError",this.reason=n,Object.setPrototypeOf(this,e.prototype)}},ie=300,ce=/^[0-9a-fA-F]{64}$/,de=/^[0-9]{1,15}$/;function G(e,n){if(typeof e.get=="function")return e.get(n)||void 0;let i=e;for(let u of Object.keys(i)){if(u.toLowerCase()!==n)continue;let p=i[u],y=Array.isArray(p)?p[0]:p;if(typeof y=="string"&&y!=="")return y}}var R=e=>typeof e=="string",z=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ue(e){let n;try{n=JSON.parse(e)}catch{throw new C("bad_payload")}if(!z(n)||n.event!=="partner_message.sent")throw new C("bad_payload");let{sender:i}=n;if(!R(n.delivery_id)||!R(n.external_ref)||!R(n.thread_ref)||!R(n.conversation_id)||!R(n.message_id)||!R(n.body)||!R(n.sent_at)||!z(i)||!R(i.name)||!(i.user_ref===null||R(i.user_ref)))throw new C("bad_payload");let u=A(n.media);if(u===null)throw new C("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:i.user_ref,name:i.name},media:u}}function q(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=G(e.headers,"x-crm-timestamp"),i=G(e.headers,"x-crm-signature");if(n===void 0||i===void 0)throw new C("missing_headers");let u=e.toleranceSeconds??ie,p=(e.now??Date.now)()/1e3;if(!de.test(n)||!Number.isFinite(p)||Math.abs(p-Number(n))>u)throw new C("stale_timestamp");if(!ce.test(i))throw new C("bad_signature");let y=(0,I.createHmac)("sha256",e.secret).update(`${n}.${e.rawBody}`).digest();if(!(0,I.timingSafeEqual)(y,Buffer.from(i,"hex")))throw new C("bad_signature");return ue(e.rawBody)}var b=class e extends Error{constructor(n,i){super(n===0?`CRM partner API unreachable (${i})`:`CRM partner API ${n} ${i}`),this.name="CrmPartnerError",this.status=n,this.code=i,Object.setPrototypeOf(this,e.prototype)}},K=/^[A-Za-z0-9_-]{1,64}$/,j=/^[A-Za-z0-9._:-]{1,200}$/,X=200,Z=500,J=1e8,T=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,partnerFilesEnabled:e.partner_files_enabled===!0,webhookUrl:typeof e.webhook_url=="string"?e.webhook_url:null});function fe(e){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new b(400,"invalid_date");return e.toISOString()}if(typeof e!="string")throw new b(400,"invalid_date");return e}function pe(e){return P(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"&&P(e.sender)&&v(e.sender.user_ref)&&typeof e.sender.name=="string"&&(e.delivery_status==="pending"||e.delivery_status==="delivered"||e.delivery_status==="failed")}var ge=/^\d{4}-\d{2}-\d{2}$/;function H(e){let n=e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e;if(typeof n!="string"||!ge.test(n)||Number.isNaN(Date.parse(`${n}T00:00:00Z`))||new Date(`${n}T00:00:00Z`).toISOString().slice(0,10)!==n)throw new b(400,"invalid_date");return n}function V(e){if(e==null)return e;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>J)throw new b(400,"invalid_cap");return e}var v=e=>e===null||typeof e=="string";function $(e){return P(e)&&typeof e.external_ref=="string"&&v(e.workspace_id)&&v(e.embed_app_id)&&typeof e.enabled=="boolean"}function ye(e){if(!e.crmBaseUrl)throw new Error("createCrmPartnerClient: `crmBaseUrl` is required.");if(!e.partnerKey)throw new Error("createCrmPartnerClient: `partnerKey` is required.");let n=N(e.fetch,"createCrmPartnerClient"),i=e.timeoutMs??15e3,u=`${D(e.crmBaseUrl)}/api/partner/v1`,p=`${u}/workspaces`,y=[e.partnerKey];function g(s){if(typeof s!="string"||!K.test(s))throw new b(400,"invalid_external_ref");return s}async function h(s,t,o,a=p){let r=await O(n,i,`${a}/${t}`,{method:s,headers:{Authorization:`Bearer ${e.partnerKey}`},body:o});if(!r.ok)throw new b(0,r.kind);if(r.status<200||r.status>=300)throw new b(r.status,U(r.json,r.status,y));return{status:r.status,json:r.json}}async function E(s,t){let o=await L(n,i,`${p}/${s}`,{method:"POST",headers:{Authorization:`Bearer ${e.partnerKey}`},form:t});if(!o.ok)throw new b(0,o.kind);if(o.status<200||o.status>=300)throw new b(o.status,U(o.json,o.status,y));return{status:o.status,json:o.json}}let f=s=>new b(s,"bad_response");function S(s){if(typeof s!="string"||!j.test(s)||s==="."||s==="..")throw new b(400,"invalid_thread_ref");return s}function M(s){if(typeof s!="string"||!j.test(s))throw new b(400,"invalid_contact_ref");return s}return{async upsertWorkspace(s,t){let o=g(s),{aiMonthlyCapCredits:a,partnerChannelEnabled:r,partnerFilesEnabled:c,webhookUrl:d,...k}=t,l=V(a),m={...k};l!==void 0&&(m.ai_monthly_cap_credits=l),r!==void 0&&(m.partner_channel_enabled=r),c!==void 0&&(m.partner_files_enabled=c),d!==void 0&&(m.webhook_url=d);let{status:W,json:w}=await h("PUT",o,m);if(!$(w))throw f(W);let _=w;if(_.created===!0){let x=_.embed_app_secret;if(typeof x!="string"||!x)throw f(W);return{...T(_),created:!0,embedAppSecret:x}}if(_.created===!1)return{...T(_),created:!1};throw f(W)},async getWorkspace(s){let t=g(s);try{let{status:o,json:a}=await h("GET",t);if(!$(a)||typeof a.state!="string")throw f(o);let r=a.ai;return{...T(a),state:a.state,ai:P(r)&&typeof r.period=="string"&&typeof r.used_credits=="number"?{period:r.period,usedCredits:r.used_credits}:null}}catch(o){if(o instanceof b&&o.status===404)return null;throw o}},async updateWorkspace(s,t){let o=g(s),a={};t.enabled!==void 0&&(a.enabled=t.enabled),t.name!==void 0&&(a.name=t.name);let r=V(t.aiMonthlyCapCredits);r!==void 0&&(a.ai_monthly_cap_credits=r),t.partnerChannelEnabled!==void 0&&(a.partner_channel_enabled=t.partnerChannelEnabled),t.partnerFilesEnabled!==void 0&&(a.partner_files_enabled=t.partnerFilesEnabled),t.webhookUrl!==void 0&&(a.webhook_url=t.webhookUrl);let{status:c,json:d}=await h("PATCH",o,a);if(!$(d))throw f(c);return T(d)},async getWorkspaceUsage(s,t){let o=g(s),a=new URLSearchParams({from:H(t.from),to:H(t.to)});try{let{status:r,json:c}=await h("GET",`${o}/usage?${a.toString()}`);if(!P(c)||!P(c.totals)||!P(c.cap)||!Array.isArray(c.by_operation))throw f(r);return c}catch(r){if(r instanceof b&&r.status===404)return null;throw r}},async rotateWorkspaceSecret(s){let t=g(s),{status:o,json:a}=await h("POST",`${t}/rotate-secret`),r=a;if(!P(a)||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,t,o){let a=g(s),r=M(t),{status:c,json:d}=await h("PUT",`${a}/contacts/${encodeURIComponent(r)}`,o);if(!P(d)||!P(d.contact)||typeof d.created!="boolean"||typeof d.consent_applied!="boolean")throw f(c);return d},async eraseContact(s,t){let o=g(s),a=M(t);try{let{status:r,json:c}=await h("DELETE",`${o}/contacts/${encodeURIComponent(a)}`);if(!P(c)||c.erased!==!0||typeof c.contact_id!="string")throw f(r);return c}catch(r){if(r instanceof b&&r.status===404)return null;throw r}},async eraseContactsByIdentity(s,t){let o=g(s),a=typeof t?.phone=="string"?t.phone.trim():void 0,r=typeof t?.email=="string"?t.email.trim():void 0,c=a!==void 0&&/\d/.test(a),d=r!==void 0&&r.includes("@");if(t?.phone!==void 0&&!c||t?.email!==void 0&&!d||!c&&!d)throw new b(400,"invalid_identity");t.ref!==void 0&&M(t.ref);let k={};c&&(k.phone=a),d&&(k.email=r),t.ref!==void 0&&(k.ref=t.ref);try{let{status:l,json:m}=await h("POST",`${o}/contacts/erase-by-identity`,k);if(!P(m)||typeof m.erased!="number"||!Array.isArray(m.contact_ids)||typeof m.skipped_linked_elsewhere!="number")throw f(l);return m}catch(l){if(l instanceof b&&l.status===404)return null;throw l}},async listContactChanges(s,t={}){let o=g(s),{since:a,cursor:r,limit:c}=t;if(c!==void 0&&(!Number.isInteger(c)||c<1||c>X))throw new b(400,"invalid_limit");let d=new URLSearchParams;a!==void 0&&d.set("since",a),r!==void 0&&d.set("cursor",r),c!==void 0&&d.set("limit",String(c));let k=d.toString(),{status:l,json:m}=await h("GET",`${o}/contacts/changes${k?`?${k}`:""}`);if(!P(m)||!Array.isArray(m.items)||!(m.next_cursor===null||typeof m.next_cursor=="string"))throw f(l);return m},async sendPartnerMessage(s,t){let o=g(s),a={contact_ref:M(t.contactRef),thread_ref:t.threadRef,message_ref:t.messageRef,body:t.body,sent_at:fe(t.sentAt)};t.title!==void 0&&(a.title=t.title),t.teamRef!==void 0&&(a.team_ref=t.teamRef);let r;if(t.file){let m=new FormData;for(let[Q,F]of Object.entries(a))F!==void 0&&m.append(Q,String(F));let{data:W,name:w,type:_}=t.file,x=W instanceof Blob?W:new Blob([W],{type:_});m.append("file",x.type===_?x:new Blob([x],{type:_}),w),r=await E(`${o}/messages/file`,m)}else r=await h("POST",`${o}/messages`,a);let{status:c,json:d}=r;if(!P(d)||typeof d.conversation_id!="string"||typeof d.message_id!="string"||typeof d.created!="boolean")throw f(c);let k=d,l=A(k.media);if(l===null)throw f(c);return{conversationId:k.conversation_id,messageId:k.message_id,created:k.created,media:l}},async getPartnerMediaLinks(s,t,o){let a=g(s),r=S(t),c={media_ids:o},{status:d,json:k}=await h("POST",`${a}/conversations/${encodeURIComponent(r)}/media-links`,c);if(!P(k)||!Array.isArray(k.items))throw f(d);return k.items.map(l=>{if(!P(l)||typeof l.id!="string"||typeof l.url!="string"||typeof l.expires_at!="string")throw f(d);return{id:l.id,url:l.url,expiresAt:l.expires_at}})},async deletePartnerConversation(s,t){let o=g(s),a=S(t),{status:r,json:c}=await h("DELETE",`${o}/conversations/${encodeURIComponent(a)}`);if(!P(c)||typeof c.deleted!="boolean")throw f(r);return{deleted:c.deleted}},async listPartnerMessageChanges(s,t={}){let o=g(s),{cursor:a,limit:r}=t;if(r!==void 0&&(!Number.isInteger(r)||r<1||r>Z))throw new b(400,"invalid_limit");let c=new URLSearchParams;a!==void 0&&c.set("cursor",a),r!==void 0&&c.set("limit",String(r));let d=c.toString(),{status:k,json:l}=await h("GET",`${o}/messages/changes${d?`?${d}`:""}`);if(!P(l)||!Array.isArray(l.items)||!(l.next_cursor===null||typeof l.next_cursor=="string"))throw f(k);let m=l;return{items:m.items.map(w=>{if(!pe(w))throw f(k);let _=A(w.media);if(_===null)throw f(k);return{deliveryId:w.delivery_id,externalRef:w.external_ref,threadRef:w.thread_ref,conversationId:w.conversation_id,messageId:w.message_id,body:w.body,sentAt:w.sent_at,sender:{userRef:w.sender.user_ref,name:w.sender.name},deliveryStatus:w.delivery_status,media:_}}),nextCursor:m.next_cursor}},async setWebhook(s){let t={url:s.url},{status:o,json:a}=await h("PUT","webhook",t,u);if(!P(a)||typeof a.url!="string")throw f(o);if(o===201){let r=a.secret;if(typeof r!="string"||!r)throw f(o);return{url:a.url,secret:r}}return{url:a.url}},async getWebhook(){try{let{status:s,json:t}=await h("GET","webhook",void 0,u);if(!P(t)||typeof t.url!="string"||t.has_secret!==!0)throw f(s);return{url:t.url,hasSecret:!0}}catch(s){if(s instanceof b&&s.status===404)return null;throw s}},async rotateWebhookSecret(){let{status:s,json:t}=await h("POST","webhook/rotate-secret",void 0,u),o=P(t)?t.secret:void 0;if(typeof o!="string"||!o)throw f(s);return{secret:o}},async deleteWebhook(){await h("DELETE","webhook",void 0,u)}}}0&&(module.exports={AI_MONTHLY_CAP_MAX_CREDITS,CONTACT_CHANGES_MAX_LIMIT,CONTACT_REF_PATTERN,CrmPartnerError,EXTERNAL_REF_PATTERN,PARTNER_MESSAGE_CHANGES_MAX_LIMIT,PartnerWebhookVerificationError,createCrmPartnerClient,verifyPartnerWebhook});
|
|
2
2
|
//# sourceMappingURL=partner.cjs.map
|