@cossistant/core 0.0.26 → 0.0.29
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/client.d.ts +48 -6
- package/client.d.ts.map +1 -1
- package/client.js +50 -1
- package/client.js.map +1 -1
- package/conversation.d.ts +3 -0
- package/conversation.d.ts.map +1 -1
- package/index.d.ts +6 -4
- package/index.js +3 -1
- package/package.json +1 -1
- package/realtime-events.d.ts +163 -0
- package/realtime-events.d.ts.map +1 -1
- package/rest-client.d.ts +32 -1
- package/rest-client.d.ts.map +1 -1
- package/rest-client.js +75 -0
- package/rest-client.js.map +1 -1
- package/schemas.d.ts +1 -0
- package/schemas.d.ts.map +1 -1
- package/store/conversations-store.d.ts +6 -6
- package/store/conversations-store.d.ts.map +1 -1
- package/store/conversations-store.js +2 -1
- package/store/conversations-store.js.map +1 -1
- package/store/typing-store.d.ts.map +1 -1
- package/store/typing-store.js +6 -6
- package/store/typing-store.js.map +1 -1
- package/types/src/enums.js +4 -1
- package/types/src/enums.js.map +1 -1
- package/typing-reporter.d.ts +71 -0
- package/typing-reporter.d.ts.map +1 -0
- package/typing-reporter.js +145 -0
- package/typing-reporter.js.map +1 -0
- package/upload-constants.d.ts +40 -0
- package/upload-constants.d.ts.map +1 -0
- package/upload-constants.js +70 -0
- package/upload-constants.js.map +1 -0
- package/upload.d.ts +47 -0
- package/upload.d.ts.map +1 -0
package/rest-client.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { logger } from "./logger.js";
|
|
2
2
|
import { CossistantAPIError } from "./types.js";
|
|
3
|
+
import { isAllowedMimeType, validateFile } from "./upload-constants.js";
|
|
3
4
|
import { generateConversationId } from "./utils.js";
|
|
4
5
|
import { collectVisitorData } from "./visitor-data.js";
|
|
5
6
|
import { getExistingVisitorId, getVisitorId, setVisitorId } from "./visitor-tracker.js";
|
|
@@ -360,6 +361,80 @@ var CossistantRestClient = class {
|
|
|
360
361
|
hasNextPage: response.hasNextPage
|
|
361
362
|
};
|
|
362
363
|
}
|
|
364
|
+
/**
|
|
365
|
+
* Generate a presigned URL for uploading a file to S3.
|
|
366
|
+
* The URL can be used to PUT a file directly to S3.
|
|
367
|
+
*/
|
|
368
|
+
async generateUploadUrl(params) {
|
|
369
|
+
if (!this.websiteId) throw new Error("Website ID is required. Call getWebsite() first to initialize the client.");
|
|
370
|
+
const visitorId = this.resolveVisitorId();
|
|
371
|
+
if (!isAllowedMimeType(params.contentType)) throw new Error(`File type "${params.contentType}" is not allowed`);
|
|
372
|
+
const headers = {};
|
|
373
|
+
if (visitorId) headers["X-Visitor-Id"] = visitorId;
|
|
374
|
+
const websiteResponse = await this.request("/websites", { headers });
|
|
375
|
+
const body = {
|
|
376
|
+
contentType: params.contentType,
|
|
377
|
+
websiteId: this.websiteId,
|
|
378
|
+
scope: {
|
|
379
|
+
type: "conversation",
|
|
380
|
+
organizationId: websiteResponse.organizationId,
|
|
381
|
+
websiteId: this.websiteId,
|
|
382
|
+
conversationId: params.conversationId
|
|
383
|
+
},
|
|
384
|
+
fileName: params.fileName,
|
|
385
|
+
fileExtension: params.fileExtension,
|
|
386
|
+
path: params.path,
|
|
387
|
+
useCdn: false,
|
|
388
|
+
expiresInSeconds: params.expiresInSeconds
|
|
389
|
+
};
|
|
390
|
+
return await this.request("/uploads/sign-url", {
|
|
391
|
+
method: "POST",
|
|
392
|
+
body: JSON.stringify(body),
|
|
393
|
+
headers
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Upload a file to S3 using a presigned URL.
|
|
398
|
+
* @returns The public URL of the uploaded file
|
|
399
|
+
*/
|
|
400
|
+
async uploadFile(file, uploadUrl, contentType) {
|
|
401
|
+
const validationError = validateFile(file);
|
|
402
|
+
if (validationError) throw new Error(validationError);
|
|
403
|
+
const response = await fetch(uploadUrl, {
|
|
404
|
+
method: "PUT",
|
|
405
|
+
body: file,
|
|
406
|
+
headers: { "Content-Type": contentType }
|
|
407
|
+
});
|
|
408
|
+
if (!response.ok) throw new Error(`Failed to upload file: ${response.status} ${response.statusText}`);
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Upload multiple files for a conversation message.
|
|
412
|
+
* Files are uploaded in parallel and the function returns timeline parts
|
|
413
|
+
* that can be included in a message.
|
|
414
|
+
*/
|
|
415
|
+
async uploadFilesForMessage(files, conversationId) {
|
|
416
|
+
if (files.length === 0) return [];
|
|
417
|
+
for (const file of files) {
|
|
418
|
+
const error = validateFile(file);
|
|
419
|
+
if (error) throw new Error(error);
|
|
420
|
+
}
|
|
421
|
+
const uploadPromises = files.map(async (file) => {
|
|
422
|
+
const uploadInfo = await this.generateUploadUrl({
|
|
423
|
+
conversationId,
|
|
424
|
+
contentType: file.type,
|
|
425
|
+
fileName: file.name
|
|
426
|
+
});
|
|
427
|
+
await this.uploadFile(file, uploadInfo.uploadUrl, file.type);
|
|
428
|
+
return {
|
|
429
|
+
type: file.type.startsWith("image/") ? "image" : "file",
|
|
430
|
+
url: uploadInfo.publicUrl,
|
|
431
|
+
mediaType: file.type,
|
|
432
|
+
fileName: file.name,
|
|
433
|
+
size: file.size
|
|
434
|
+
};
|
|
435
|
+
});
|
|
436
|
+
return Promise.all(uploadPromises);
|
|
437
|
+
}
|
|
363
438
|
};
|
|
364
439
|
|
|
365
440
|
//#endregion
|
package/rest-client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rest-client.js","names":["headers: Record<string, string>","body: CreateConversationRequestBody","body: MarkConversationSeenRequestBody","body: SetConversationTypingRequestBody"],"sources":["../src/rest-client.ts"],"sourcesContent":["import type { IdentifyContactResponse } from \"@cossistant/types/api/contact\";\nimport type {\n\tCreateConversationRequestBody,\n\tCreateConversationResponseBody,\n\tGetConversationRequest,\n\tGetConversationResponse,\n\tGetConversationSeenDataResponse,\n\tListConversationsRequest,\n\tListConversationsResponse,\n\tMarkConversationSeenRequestBody,\n\tMarkConversationSeenResponseBody,\n\tSetConversationTypingRequestBody,\n\tSetConversationTypingResponseBody,\n} from \"@cossistant/types/api/conversation\";\nimport type {\n\tGetConversationTimelineItemsRequest,\n\tGetConversationTimelineItemsResponse,\n\tSendTimelineItemRequest,\n\tSendTimelineItemResponse,\n} from \"@cossistant/types/api/timeline-item\";\nimport { logger } from \"./logger\";\nimport {\n\tCossistantAPIError,\n\ttype CossistantConfig,\n\ttype PublicWebsiteResponse,\n\ttype UpdateVisitorRequest,\n\ttype VisitorMetadata,\n\ttype VisitorResponse,\n} from \"./types\";\nimport { generateConversationId } from \"./utils\";\nimport { collectVisitorData } from \"./visitor-data\";\nimport {\n\tgetExistingVisitorId,\n\tgetVisitorId,\n\tsetVisitorId,\n} from \"./visitor-tracker\";\n\nexport class CossistantRestClient {\n\tprivate config: CossistantConfig;\n\tprivate baseHeaders: Record<string, string>;\n\tprivate publicKey: string;\n\tprivate websiteId: string | null = null;\n\tprivate visitorId: string | null = null;\n\tprivate visitorBlocked = false;\n\n\tconstructor(config: CossistantConfig) {\n\t\tthis.config = config;\n\n\t\t// Get public key from config or environment variables\n\t\tthis.publicKey =\n\t\t\tconfig.publicKey ||\n\t\t\t(typeof process !== \"undefined\"\n\t\t\t\t? process.env.NEXT_PUBLIC_COSSISTANT_API_KEY\n\t\t\t\t: undefined) ||\n\t\t\t(typeof process !== \"undefined\"\n\t\t\t\t? process.env.COSSISTANT_API_KEY\n\t\t\t\t: undefined) ||\n\t\t\t(typeof process !== \"undefined\"\n\t\t\t\t? process.env.NEXT_PUBLIC_COSSISTANT_KEY\n\t\t\t\t: undefined) ||\n\t\t\t\"\";\n\n\t\tif (!this.publicKey) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Public key is required. Please provide it in the config or set NEXT_PUBLIC_COSSISTANT_API_KEY or COSSISTANT_API_KEY environment variable.\"\n\t\t\t);\n\t\t}\n\n\t\tthis.baseHeaders = {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\"X-Public-Key\": this.publicKey,\n\t\t};\n\n\t\tif (config.userId) {\n\t\t\tthis.baseHeaders[\"X-User-ID\"] = config.userId;\n\t\t}\n\n\t\tif (config.organizationId) {\n\t\t\tthis.baseHeaders[\"X-Organization-ID\"] = config.organizationId;\n\t\t}\n\t}\n\n\tprivate normalizeVisitorResponse(payload: VisitorResponse): VisitorResponse {\n\t\tconst contact = payload.contact ? payload.contact : null;\n\t\treturn {\n\t\t\t...payload,\n\t\t\t// Ensure latitude and longitude are numbers or null\n\t\t\tlatitude:\n\t\t\t\ttypeof payload.latitude === \"string\"\n\t\t\t\t\t? Number.parseFloat(payload.latitude)\n\t\t\t\t\t: payload.latitude,\n\t\t\tlongitude:\n\t\t\t\ttypeof payload.longitude === \"string\"\n\t\t\t\t\t? Number.parseFloat(payload.longitude)\n\t\t\t\t\t: payload.longitude,\n\t\t\tcreatedAt: payload.createdAt,\n\t\t\tupdatedAt: payload.updatedAt,\n\t\t\tlastSeenAt: payload.lastSeenAt ? payload.lastSeenAt : null,\n\t\t\tblockedAt: payload.blockedAt ? payload.blockedAt : null,\n\t\t\tcontact: payload.contact ? payload.contact : null,\n\t\t};\n\t}\n\n\tprivate resolveVisitorId(): string {\n\t\tif (this.visitorId) {\n\t\t\treturn this.visitorId;\n\t\t}\n\n\t\tif (this.websiteId) {\n\t\t\tconst storedVisitorId = getVisitorId(this.websiteId);\n\t\t\tif (storedVisitorId) {\n\t\t\t\tthis.visitorId = storedVisitorId;\n\t\t\t\treturn storedVisitorId;\n\t\t\t}\n\t\t}\n\n\t\tthrow new Error(\"Visitor ID is required\");\n\t}\n\n\tprivate async syncVisitorSnapshot(visitorId: string): Promise<void> {\n\t\ttry {\n\t\t\tconst visitorData = await collectVisitorData();\n\t\t\tif (!visitorData) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst payload = Object.entries(visitorData).reduce<\n\t\t\t\tPartial<UpdateVisitorRequest>\n\t\t\t>((acc, [key, value]) => {\n\t\t\t\tif (value === null || value === undefined) {\n\t\t\t\t\treturn acc;\n\t\t\t\t}\n\t\t\t\t(acc as Record<string, unknown>)[key] = value;\n\t\t\t\treturn acc;\n\t\t\t}, {});\n\n\t\t\tif (Object.keys(payload).length === 0) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tawait this.request<VisitorResponse>(`/visitors/${visitorId}`, {\n\t\t\t\tmethod: \"PATCH\",\n\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t\theaders: {\n\t\t\t\t\t\"X-Visitor-Id\": visitorId,\n\t\t\t\t},\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlogger.warn(\"Failed to sync visitor data\", error);\n\t\t}\n\t}\n\n\tprivate async request<T>(\n\t\tpath: string,\n\t\toptions: RequestInit = {}\n\t): Promise<T> {\n\t\tif (this.visitorBlocked) {\n\t\t\tconst method = (options.method ?? \"GET\").toUpperCase();\n\t\t\tconst [rawPath] = path.split(\"?\");\n\t\t\tconst normalizedPath = rawPath?.endsWith(\"/\")\n\t\t\t\t? rawPath.slice(0, -1)\n\t\t\t\t: rawPath;\n\t\t\tconst isWebsitesRoot = normalizedPath === \"/websites\";\n\t\t\tconst isSafeMethod = method === \"GET\" || method === \"HEAD\";\n\n\t\t\tif (!(isWebsitesRoot && isSafeMethod)) {\n\t\t\t\tthrow new CossistantAPIError({\n\t\t\t\t\tcode: \"VISITOR_BLOCKED\",\n\t\t\t\t\tmessage: \"Visitor is blocked and cannot perform this action.\",\n\t\t\t\t\tdetails: { path, method },\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tconst url = `${this.config.apiUrl}${path}`;\n\n\t\tconst response = await fetch(url, {\n\t\t\t...options,\n\t\t\theaders: {\n\t\t\t\t...this.baseHeaders,\n\t\t\t\t...options.headers,\n\t\t\t},\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tconst errorData = await response.json().catch(() => ({}));\n\t\t\tconst statusCode = response.status;\n\t\t\tconst errorCode = errorData.code || `HTTP_${statusCode}`;\n\t\t\tconst serverMessage = errorData.message;\n\n\t\t\t// Determine if this is an authentication/authorization error\n\t\t\tconst isAuthError =\n\t\t\t\tstatusCode === 401 ||\n\t\t\t\tstatusCode === 403 ||\n\t\t\t\terrorCode === \"UNAUTHORIZED\" ||\n\t\t\t\terrorCode === \"FORBIDDEN\" ||\n\t\t\t\terrorCode === \"INVALID_API_KEY\" ||\n\t\t\t\terrorCode === \"API_KEY_EXPIRED\" ||\n\t\t\t\terrorCode === \"API_KEY_MISSING\" ||\n\t\t\t\terrorCode?.toUpperCase().includes(\"AUTH\") ||\n\t\t\t\terrorCode?.toUpperCase().includes(\"API_KEY\");\n\n\t\t\t// Use appropriate error message based on error type\n\t\t\tconst errorMessage = isAuthError\n\t\t\t\t? \"Your Cossistant public API key is invalid, expired, missing or not authorized to access this resource.\"\n\t\t\t\t: serverMessage || `Request failed with status ${statusCode}`;\n\n\t\t\t// Log with appropriate level based on error type\n\t\t\tif (isAuthError) {\n\t\t\t\tlogger.error(errorMessage, {\n\t\t\t\t\tdetails: errorData.details,\n\t\t\t\t\tpath,\n\t\t\t\t\tstatus: statusCode,\n\t\t\t\t\tcode: errorCode,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tlogger.error(\"API request failed\", {\n\t\t\t\t\tmessage: errorMessage,\n\t\t\t\t\tdetails: errorData.details,\n\t\t\t\t\tpath,\n\t\t\t\t\tstatus: statusCode,\n\t\t\t\t\tcode: errorCode,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthrow new CossistantAPIError({\n\t\t\t\tcode: errorCode,\n\t\t\t\tmessage: errorMessage,\n\t\t\t\tdetails: errorData.details,\n\t\t\t});\n\t\t}\n\n\t\treturn response.json();\n\t}\n\n\tasync getWebsite(): Promise<PublicWebsiteResponse> {\n\t\t// Make the request with visitor ID if we have one stored\n\t\tconst headers: Record<string, string> = {};\n\n\t\t// First, check if we already know the website ID and have a visitor ID for it\n\t\tif (this.websiteId) {\n\t\t\tconst storedVisitorId = getVisitorId(this.websiteId);\n\t\t\tif (storedVisitorId) {\n\t\t\t\theaders[\"X-Visitor-Id\"] = storedVisitorId;\n\t\t\t}\n\t\t} else {\n\t\t\t// We don't know the website ID yet, but check if we have any existing visitor\n\t\t\t// This prevents creating duplicate visitors on page refresh\n\t\t\tconst existingVisitor = getExistingVisitorId(this.publicKey);\n\t\t\tif (existingVisitor) {\n\t\t\t\theaders[\"X-Visitor-Id\"] = existingVisitor.visitorId;\n\t\t\t\t// Pre-populate our local state\n\t\t\t\tthis.websiteId = existingVisitor.websiteId;\n\t\t\t\tthis.visitorId = existingVisitor.visitorId;\n\t\t\t}\n\t\t}\n\n\t\tconst response = await this.request<PublicWebsiteResponse>(\"/websites\", {\n\t\t\theaders,\n\t\t});\n\n\t\t// Store the website ID for future requests\n\t\tthis.websiteId = response.id;\n\n\t\t// Store the visitor ID if we got one\n\t\tthis.visitorBlocked = response.visitor?.isBlocked ?? false;\n\n\t\tif (response.visitor?.id) {\n\t\t\tif (this.visitorBlocked) {\n\t\t\t\tthis.visitorId = response.visitor.id;\n\t\t\t\tsetVisitorId(response.id, response.visitor.id);\n\t\t\t\treturn response;\n\t\t\t}\n\n\t\t\tthis.visitorId = response.visitor.id;\n\t\t\tsetVisitorId(response.id, response.visitor.id);\n\t\t\tthis.syncVisitorSnapshot(response.visitor.id);\n\t\t}\n\n\t\treturn response;\n\t}\n\n\t// Manually prime website and visitor context when the caller already has it\n\tsetWebsiteContext(websiteId: string, visitorId?: string): void {\n\t\tthis.websiteId = websiteId;\n\t\tif (visitorId) {\n\t\t\tthis.visitorId = visitorId;\n\t\t\tsetVisitorId(websiteId, visitorId);\n\t\t}\n\t}\n\n\tsetVisitorBlocked(isBlocked: boolean): void {\n\t\tthis.visitorBlocked = isBlocked;\n\t}\n\n\tgetCurrentWebsiteId(): string | null {\n\t\treturn this.websiteId;\n\t}\n\n\tgetCurrentVisitorId(): string | null {\n\t\tif (this.visitorId) {\n\t\t\treturn this.visitorId;\n\t\t}\n\n\t\tif (!this.websiteId) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn getVisitorId(this.websiteId) ?? null;\n\t}\n\n\tasync updateVisitorMetadata(\n\t\tmetadata: VisitorMetadata\n\t): Promise<VisitorResponse> {\n\t\tconst visitorId = this.resolveVisitorId();\n\t\tconst response = await this.request<VisitorResponse>(\n\t\t\t`/visitors/${visitorId}/metadata`,\n\t\t\t{\n\t\t\t\tmethod: \"PATCH\",\n\t\t\t\tbody: JSON.stringify({ metadata }),\n\t\t\t\theaders: {\n\t\t\t\t\t\"X-Visitor-Id\": visitorId,\n\t\t\t\t},\n\t\t\t}\n\t\t);\n\n\t\treturn this.normalizeVisitorResponse(response);\n\t}\n\n\t/**\n\t * Identify a visitor by creating or updating their contact information\n\t * This will link the visitor to a contact record that can be tracked across devices\n\t */\n\tasync identify(params: {\n\t\texternalId?: string;\n\t\temail?: string;\n\t\tname?: string;\n\t\timage?: string;\n\t\tmetadata?: Record<string, unknown>;\n\t\tcontactOrganizationId?: string;\n\t}): Promise<IdentifyContactResponse> {\n\t\tconst visitorId = this.resolveVisitorId();\n\n\t\tconst response = await this.request<IdentifyContactResponse>(\n\t\t\t\"/contacts/identify\",\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tvisitorId,\n\t\t\t\t\t...params,\n\t\t\t\t}),\n\t\t\t\theaders: {\n\t\t\t\t\t\"X-Visitor-Id\": visitorId,\n\t\t\t\t},\n\t\t\t}\n\t\t);\n\n\t\treturn {\n\t\t\tcontact: {\n\t\t\t\t...response.contact,\n\t\t\t\t// Ensure metadata is properly typed\n\t\t\t\tmetadata:\n\t\t\t\t\ttypeof response.contact.metadata === \"string\"\n\t\t\t\t\t\t? JSON.parse(response.contact.metadata)\n\t\t\t\t\t\t: response.contact.metadata,\n\t\t\t\tcreatedAt: response.contact.createdAt,\n\t\t\t\tupdatedAt: response.contact.updatedAt,\n\t\t\t},\n\t\t\tvisitorId: response.visitorId,\n\t\t};\n\t}\n\n\t/**\n\t * Update metadata for the contact associated with the current visitor\n\t * Note: The visitor must be identified first via the identify() method\n\t */\n\tasync updateContactMetadata(\n\t\tmetadata: Record<string, unknown>\n\t): Promise<VisitorResponse> {\n\t\t// This still uses the visitor metadata endpoint for backward compatibility\n\t\t// The endpoint will internally update the contact metadata\n\t\treturn this.updateVisitorMetadata(metadata as VisitorMetadata);\n\t}\n\n\tasync createConversation(\n\t\tparams: Partial<CreateConversationRequestBody> = {}\n\t): Promise<CreateConversationResponseBody> {\n\t\tconst conversationId = params.conversationId || generateConversationId();\n\n\t\t// Get visitor ID from storage if we have the website ID, or use the provided one\n\t\tconst storedVisitorId = this.websiteId\n\t\t\t? getVisitorId(this.websiteId)\n\t\t\t: undefined;\n\t\tconst visitorId = params.visitorId || storedVisitorId;\n\n\t\tif (!visitorId) {\n\t\t\tthrow new Error(\"Visitor ID is required\");\n\t\t}\n\n\t\tconst body: CreateConversationRequestBody = {\n\t\t\tconversationId,\n\t\t\tvisitorId,\n\t\t\tdefaultTimelineItems: params.defaultTimelineItems || [],\n\t\t\tchannel: params.channel || \"widget\",\n\t\t};\n\n\t\t// Add visitor ID header if available\n\t\tconst headers: Record<string, string> = {};\n\t\tif (visitorId) {\n\t\t\theaders[\"X-Visitor-Id\"] = visitorId;\n\t\t}\n\n\t\tconst response = await this.request<CreateConversationResponseBody>(\n\t\t\t\"/conversations\",\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\theaders,\n\t\t\t}\n\t\t);\n\n\t\t// Convert date strings to Date objects\n\t\treturn {\n\t\t\tconversation: {\n\t\t\t\t...response.conversation,\n\t\t\t\tcreatedAt: response.conversation.createdAt,\n\t\t\t\tupdatedAt: response.conversation.updatedAt,\n\t\t\t\tdeletedAt: response.conversation.deletedAt ?? null,\n\t\t\t\tlastTimelineItem: response.conversation.lastTimelineItem,\n\t\t\t},\n\t\t\tinitialTimelineItems: response.initialTimelineItems,\n\t\t};\n\t}\n\n\tasync updateConfiguration(config: Partial<CossistantConfig>): Promise<void> {\n\t\tif (config.publicKey) {\n\t\t\tthis.publicKey = config.publicKey;\n\t\t\tthis.baseHeaders[\"X-Public-Key\"] = config.publicKey;\n\t\t}\n\n\t\tif (config.userId) {\n\t\t\tthis.baseHeaders[\"X-User-ID\"] = config.userId;\n\t\t} else if (config.userId === null) {\n\t\t\tconst { \"X-User-ID\": _, ...rest } = this.baseHeaders;\n\t\t\tthis.baseHeaders = rest;\n\t\t}\n\n\t\tif (config.organizationId) {\n\t\t\tthis.baseHeaders[\"X-Organization-ID\"] = config.organizationId;\n\t\t} else if (config.organizationId === null) {\n\t\t\tconst { \"X-Organization-ID\": _, ...rest } = this.baseHeaders;\n\t\t\tthis.baseHeaders = rest;\n\t\t}\n\n\t\tthis.config = { ...this.config, ...config };\n\t}\n\n\tasync listConversations(\n\t\tparams: Partial<ListConversationsRequest> = {}\n\t): Promise<ListConversationsResponse> {\n\t\t// Get visitor ID from storage if we have the website ID, or use the provided one\n\t\tconst storedVisitorId = this.websiteId\n\t\t\t? getVisitorId(this.websiteId)\n\t\t\t: undefined;\n\t\tconst visitorId = params.visitorId || storedVisitorId;\n\n\t\tif (!visitorId) {\n\t\t\tthrow new Error(\"Visitor ID is required\");\n\t\t}\n\n\t\t// Create query parameters\n\t\tconst queryParams = new URLSearchParams();\n\n\t\tif (visitorId) {\n\t\t\tqueryParams.set(\"visitorId\", visitorId);\n\t\t}\n\n\t\tif (params.page) {\n\t\t\tqueryParams.set(\"page\", params.page.toString());\n\t\t}\n\n\t\tif (params.limit) {\n\t\t\tqueryParams.set(\"limit\", params.limit.toString());\n\t\t}\n\n\t\tif (params.status) {\n\t\t\tqueryParams.set(\"status\", params.status);\n\t\t}\n\n\t\tif (params.orderBy) {\n\t\t\tqueryParams.set(\"orderBy\", params.orderBy);\n\t\t}\n\n\t\tif (params.order) {\n\t\t\tqueryParams.set(\"order\", params.order);\n\t\t}\n\n\t\t// Add visitor ID header if available\n\t\tconst headers: Record<string, string> = {};\n\t\tif (visitorId) {\n\t\t\theaders[\"X-Visitor-Id\"] = visitorId;\n\t\t}\n\n\t\tconst response = await this.request<ListConversationsResponse>(\n\t\t\t`/conversations?${queryParams.toString()}`,\n\t\t\t{\n\t\t\t\theaders,\n\t\t\t}\n\t\t);\n\n\t\t// Convert date strings to Date objects\n\t\treturn {\n\t\t\tconversations: response.conversations.map((conv) => ({\n\t\t\t\t...conv,\n\t\t\t\tcreatedAt: conv.createdAt,\n\t\t\t\tupdatedAt: conv.updatedAt,\n\t\t\t\tdeletedAt: conv.deletedAt ?? null,\n\t\t\t\tlastTimelineItem: conv.lastTimelineItem,\n\t\t\t})),\n\t\t\tpagination: response.pagination,\n\t\t};\n\t}\n\n\tasync getConversation(\n\t\tparams: GetConversationRequest\n\t): Promise<GetConversationResponse> {\n\t\t// Get visitor ID from storage if we have the website ID\n\t\tconst visitorId = this.websiteId ? getVisitorId(this.websiteId) : undefined;\n\n\t\t// Add visitor ID header if available\n\t\tconst headers: Record<string, string> = {};\n\t\tif (visitorId) {\n\t\t\theaders[\"X-Visitor-Id\"] = visitorId;\n\t\t}\n\n\t\tconst response = await this.request<GetConversationResponse>(\n\t\t\t`/conversations/${params.conversationId}`,\n\t\t\t{\n\t\t\t\theaders,\n\t\t\t}\n\t\t);\n\n\t\t// Convert date strings to Date objects\n\t\treturn {\n\t\t\tconversation: {\n\t\t\t\t...response.conversation,\n\t\t\t\tcreatedAt: response.conversation.createdAt,\n\t\t\t\tupdatedAt: response.conversation.updatedAt,\n\t\t\t\tdeletedAt: response.conversation.deletedAt ?? null,\n\t\t\t\tlastTimelineItem: response.conversation.lastTimelineItem,\n\t\t\t},\n\t\t};\n\t}\n\n\tasync markConversationSeen(\n\t\tparams: {\n\t\t\tconversationId: string;\n\t\t} & Partial<MarkConversationSeenRequestBody>\n\t): Promise<MarkConversationSeenResponseBody> {\n\t\tconst storedVisitorId = this.websiteId\n\t\t\t? getVisitorId(this.websiteId)\n\t\t\t: undefined;\n\t\tconst visitorId = params.visitorId || storedVisitorId;\n\n\t\tif (!visitorId) {\n\t\t\tthrow new Error(\"Visitor ID is required to mark a conversation as seen\");\n\t\t}\n\n\t\tconst headers: Record<string, string> = {};\n\t\tif (visitorId) {\n\t\t\theaders[\"X-Visitor-Id\"] = visitorId;\n\t\t}\n\n\t\tconst body: MarkConversationSeenRequestBody = {};\n\t\tif (params.visitorId) {\n\t\t\tbody.visitorId = params.visitorId;\n\t\t}\n\n\t\tconst response = await this.request<MarkConversationSeenResponseBody>(\n\t\t\t`/conversations/${params.conversationId}/seen`,\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\theaders,\n\t\t\t}\n\t\t);\n\n\t\treturn {\n\t\t\tconversationId: response.conversationId,\n\t\t\tlastSeenAt: response.lastSeenAt,\n\t\t};\n\t}\n\n\tasync getConversationSeenData(params: {\n\t\tconversationId: string;\n\t}): Promise<GetConversationSeenDataResponse> {\n\t\tconst response = await this.request<GetConversationSeenDataResponse>(\n\t\t\t`/conversations/${params.conversationId}/seen`,\n\t\t\t{\n\t\t\t\tmethod: \"GET\",\n\t\t\t}\n\t\t);\n\n\t\treturn {\n\t\t\tseenData: response.seenData.map((item) => ({\n\t\t\t\t...item,\n\t\t\t\tlastSeenAt: item.lastSeenAt,\n\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\tupdatedAt: item.updatedAt,\n\t\t\t\tdeletedAt: item.deletedAt ? item.deletedAt : null,\n\t\t\t})),\n\t\t};\n\t}\n\n\tasync setConversationTyping(params: {\n\t\tconversationId: string;\n\t\tisTyping: boolean;\n\t\tvisitorPreview?: string | null;\n\t\tvisitorId?: string;\n\t}): Promise<SetConversationTypingResponseBody> {\n\t\tconst storedVisitorId = this.websiteId\n\t\t\t? getVisitorId(this.websiteId)\n\t\t\t: undefined;\n\t\tconst visitorId = params.visitorId || storedVisitorId;\n\n\t\tif (!visitorId) {\n\t\t\tthrow new Error(\"Visitor ID is required to report typing state\");\n\t\t}\n\n\t\tconst headers: Record<string, string> = {};\n\t\tif (visitorId) {\n\t\t\theaders[\"X-Visitor-Id\"] = visitorId;\n\t\t}\n\n\t\tconst body: SetConversationTypingRequestBody = {\n\t\t\tisTyping: params.isTyping,\n\t\t};\n\n\t\tif (params.visitorId) {\n\t\t\tbody.visitorId = params.visitorId;\n\t\t}\n\n\t\tif (params.visitorPreview && params.isTyping) {\n\t\t\tbody.visitorPreview = params.visitorPreview.slice(0, 2000);\n\t\t}\n\n\t\tconst response = await this.request<SetConversationTypingResponseBody>(\n\t\t\t`/conversations/${params.conversationId}/typing`,\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\theaders,\n\t\t\t}\n\t\t);\n\n\t\treturn {\n\t\t\tconversationId: response.conversationId,\n\t\t\tisTyping: response.isTyping,\n\t\t\tvisitorPreview: response.visitorPreview,\n\t\t\tsentAt: response.sentAt,\n\t\t};\n\t}\n\n\tasync sendMessage(\n\t\tparams: SendTimelineItemRequest\n\t): Promise<SendTimelineItemResponse> {\n\t\t// Get visitor ID from storage if we have the website ID\n\t\tconst visitorId = this.websiteId ? getVisitorId(this.websiteId) : undefined;\n\n\t\t// Add visitor ID header if available\n\t\tconst headers: Record<string, string> = {};\n\t\tif (visitorId) {\n\t\t\theaders[\"X-Visitor-Id\"] = visitorId;\n\t\t}\n\n\t\tconst response = await this.request<SendTimelineItemResponse>(\"/messages\", {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(params),\n\t\t\theaders,\n\t\t});\n\n\t\treturn {\n\t\t\titem: response.item,\n\t\t};\n\t}\n\n\tasync getConversationTimelineItems(\n\t\tparams: GetConversationTimelineItemsRequest & { conversationId: string }\n\t): Promise<GetConversationTimelineItemsResponse> {\n\t\t// Get visitor ID from storage if we have the website ID\n\t\tconst visitorId = this.websiteId ? getVisitorId(this.websiteId) : undefined;\n\n\t\t// Create query parameters\n\t\tconst queryParams = new URLSearchParams();\n\n\t\tif (params.limit) {\n\t\t\tqueryParams.set(\"limit\", params.limit.toString());\n\t\t}\n\n\t\tif (params.cursor) {\n\t\t\tqueryParams.set(\"cursor\", params.cursor);\n\t\t}\n\n\t\t// Add visitor ID header if available\n\t\tconst headers: Record<string, string> = {};\n\t\tif (visitorId) {\n\t\t\theaders[\"X-Visitor-Id\"] = visitorId;\n\t\t}\n\n\t\tconst response = await this.request<GetConversationTimelineItemsResponse>(\n\t\t\t`/conversations/${params.conversationId}/timeline?${queryParams.toString()}`,\n\t\t\t{\n\t\t\t\theaders,\n\t\t\t}\n\t\t);\n\n\t\treturn {\n\t\t\titems: response.items,\n\t\t\tnextCursor: response.nextCursor,\n\t\t\thasNextPage: response.hasNextPage,\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;AAqCA,IAAa,uBAAb,MAAkC;CACjC,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ,YAA2B;CACnC,AAAQ,YAA2B;CACnC,AAAQ,iBAAiB;CAEzB,YAAY,QAA0B;AACrC,OAAK,SAAS;AAGd,OAAK,YACJ,OAAO,cACN,OAAO,YAAY,cACjB,QAAQ,IAAI,iCACZ,YACF,OAAO,YAAY,cACjB,QAAQ,IAAI,qBACZ,YACF,OAAO,YAAY,cACjB,QAAQ,IAAI,6BACZ,WACH;AAED,MAAI,CAAC,KAAK,UACT,OAAM,IAAI,MACT,4IACA;AAGF,OAAK,cAAc;GAClB,gBAAgB;GAChB,gBAAgB,KAAK;GACrB;AAED,MAAI,OAAO,OACV,MAAK,YAAY,eAAe,OAAO;AAGxC,MAAI,OAAO,eACV,MAAK,YAAY,uBAAuB,OAAO;;CAIjD,AAAQ,yBAAyB,SAA2C;AAC3D,UAAQ,WAAU,QAAQ;AAC1C,SAAO;GACN,GAAG;GAEH,UACC,OAAO,QAAQ,aAAa,WACzB,OAAO,WAAW,QAAQ,SAAS,GACnC,QAAQ;GACZ,WACC,OAAO,QAAQ,cAAc,WAC1B,OAAO,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Ae,UACxC;GACC,QAAQ;GACR,MAAM,KAAK,UAAU,KAAK;GAC1B;GACA,CACD;AAED,SAAO;GACN,gBAAgB,SAAS;GACzB,UAAU,SAAS;GACnB,gBAAgB,SAAS;GACzB,QAAQ,SAAS;GACjB;;CAGF,MAAM,YACL,QACoC;EAEpC,MAAM,YAAY,KAAK,YAAY,aAAa,KAAK,UAAU,GAAG;EAGlE,MAAMH,UAAkC,EAAE;AAC1C,MAAI,UACH,SAAQ,kBAAkB;AAS3B,SAAO,EACN,OAPgB,MAAM,KAAK,QAAkC,aAAa;GAC1E,QAAQ;GACR,MAAM,KAAK,UAAU,OAAO;GAC5B;GACA,CAAC,EAGc,MACf;;CAGF,MAAM,6BACL,QACgD;EAEhD,MAAM,YAAY,KAAK,YAAY,aAAa,KAAK,UAAU,GAAG;EAGlE,MAAM,cAAc,IAAI,iBAAiB;AAEzC,MAAI,OAAO,MACV,aAAY,IAAI,SAAS,OAAO,MAAM,UAAU,CAAC;AAGlD,MAAI,OAAO,OACV,aAAY,IAAI,UAAU,OAAO,OAAO;EAIzC,MAAMA,UAAkC,EAAE;AAC1C,MAAI,UACH,SAAQ,kBAAkB;EAG3B,MAAM,WAAW,MAAM,KAAK,QAC3B,kBAAkB,OAAO,eAAe,YAAY,YAAY,UAAU,IAC1E,EACC,SACA,CACD;AAED,SAAO;GACN,OAAO,SAAS;GAChB,YAAY,SAAS;GACrB,aAAa,SAAS;GACtB"}
|
|
1
|
+
{"version":3,"file":"rest-client.js","names":["headers: Record<string, string>","body: CreateConversationRequestBody","body: MarkConversationSeenRequestBody","body: SetConversationTypingRequestBody","body: GenerateUploadUrlRequest"],"sources":["../src/rest-client.ts"],"sourcesContent":["import type { IdentifyContactResponse } from \"@cossistant/types/api/contact\";\nimport type {\n\tCreateConversationRequestBody,\n\tCreateConversationResponseBody,\n\tGetConversationRequest,\n\tGetConversationResponse,\n\tGetConversationSeenDataResponse,\n\tListConversationsRequest,\n\tListConversationsResponse,\n\tMarkConversationSeenRequestBody,\n\tMarkConversationSeenResponseBody,\n\tSetConversationTypingRequestBody,\n\tSetConversationTypingResponseBody,\n} from \"@cossistant/types/api/conversation\";\nimport type {\n\tGetConversationTimelineItemsRequest,\n\tGetConversationTimelineItemsResponse,\n\tSendTimelineItemRequest,\n\tSendTimelineItemResponse,\n} from \"@cossistant/types/api/timeline-item\";\nimport type {\n\tGenerateUploadUrlRequest,\n\tGenerateUploadUrlResponse,\n} from \"@cossistant/types/api/upload\";\nimport { logger } from \"./logger\";\nimport {\n\tCossistantAPIError,\n\ttype CossistantConfig,\n\ttype PublicWebsiteResponse,\n\ttype UpdateVisitorRequest,\n\ttype VisitorMetadata,\n\ttype VisitorResponse,\n} from \"./types\";\nimport {\n\tisAllowedMimeType,\n\tMAX_FILE_SIZE,\n\tvalidateFile,\n} from \"./upload-constants\";\nimport { generateConversationId } from \"./utils\";\nimport { collectVisitorData } from \"./visitor-data\";\nimport {\n\tgetExistingVisitorId,\n\tgetVisitorId,\n\tsetVisitorId,\n} from \"./visitor-tracker\";\n\nexport class CossistantRestClient {\n\tprivate config: CossistantConfig;\n\tprivate baseHeaders: Record<string, string>;\n\tprivate publicKey: string;\n\tprivate websiteId: string | null = null;\n\tprivate visitorId: string | null = null;\n\tprivate visitorBlocked = false;\n\n\tconstructor(config: CossistantConfig) {\n\t\tthis.config = config;\n\n\t\t// Get public key from config or environment variables\n\t\tthis.publicKey =\n\t\t\tconfig.publicKey ||\n\t\t\t(typeof process !== \"undefined\"\n\t\t\t\t? process.env.NEXT_PUBLIC_COSSISTANT_API_KEY\n\t\t\t\t: undefined) ||\n\t\t\t(typeof process !== \"undefined\"\n\t\t\t\t? process.env.COSSISTANT_API_KEY\n\t\t\t\t: undefined) ||\n\t\t\t(typeof process !== \"undefined\"\n\t\t\t\t? process.env.NEXT_PUBLIC_COSSISTANT_KEY\n\t\t\t\t: undefined) ||\n\t\t\t\"\";\n\n\t\tif (!this.publicKey) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Public key is required. Please provide it in the config or set NEXT_PUBLIC_COSSISTANT_API_KEY or COSSISTANT_API_KEY environment variable.\"\n\t\t\t);\n\t\t}\n\n\t\tthis.baseHeaders = {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\"X-Public-Key\": this.publicKey,\n\t\t};\n\n\t\tif (config.userId) {\n\t\t\tthis.baseHeaders[\"X-User-ID\"] = config.userId;\n\t\t}\n\n\t\tif (config.organizationId) {\n\t\t\tthis.baseHeaders[\"X-Organization-ID\"] = config.organizationId;\n\t\t}\n\t}\n\n\tprivate normalizeVisitorResponse(payload: VisitorResponse): VisitorResponse {\n\t\tconst contact = payload.contact ? payload.contact : null;\n\t\treturn {\n\t\t\t...payload,\n\t\t\t// Ensure latitude and longitude are numbers or null\n\t\t\tlatitude:\n\t\t\t\ttypeof payload.latitude === \"string\"\n\t\t\t\t\t? Number.parseFloat(payload.latitude)\n\t\t\t\t\t: payload.latitude,\n\t\t\tlongitude:\n\t\t\t\ttypeof payload.longitude === \"string\"\n\t\t\t\t\t? Number.parseFloat(payload.longitude)\n\t\t\t\t\t: payload.longitude,\n\t\t\tcreatedAt: payload.createdAt,\n\t\t\tupdatedAt: payload.updatedAt,\n\t\t\tlastSeenAt: payload.lastSeenAt ? payload.lastSeenAt : null,\n\t\t\tblockedAt: payload.blockedAt ? payload.blockedAt : null,\n\t\t\tcontact: payload.contact ? payload.contact : null,\n\t\t};\n\t}\n\n\tprivate resolveVisitorId(): string {\n\t\tif (this.visitorId) {\n\t\t\treturn this.visitorId;\n\t\t}\n\n\t\tif (this.websiteId) {\n\t\t\tconst storedVisitorId = getVisitorId(this.websiteId);\n\t\t\tif (storedVisitorId) {\n\t\t\t\tthis.visitorId = storedVisitorId;\n\t\t\t\treturn storedVisitorId;\n\t\t\t}\n\t\t}\n\n\t\tthrow new Error(\"Visitor ID is required\");\n\t}\n\n\tprivate async syncVisitorSnapshot(visitorId: string): Promise<void> {\n\t\ttry {\n\t\t\tconst visitorData = await collectVisitorData();\n\t\t\tif (!visitorData) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst payload = Object.entries(visitorData).reduce<\n\t\t\t\tPartial<UpdateVisitorRequest>\n\t\t\t>((acc, [key, value]) => {\n\t\t\t\tif (value === null || value === undefined) {\n\t\t\t\t\treturn acc;\n\t\t\t\t}\n\t\t\t\t(acc as Record<string, unknown>)[key] = value;\n\t\t\t\treturn acc;\n\t\t\t}, {});\n\n\t\t\tif (Object.keys(payload).length === 0) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tawait this.request<VisitorResponse>(`/visitors/${visitorId}`, {\n\t\t\t\tmethod: \"PATCH\",\n\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t\theaders: {\n\t\t\t\t\t\"X-Visitor-Id\": visitorId,\n\t\t\t\t},\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlogger.warn(\"Failed to sync visitor data\", error);\n\t\t}\n\t}\n\n\tprivate async request<T>(\n\t\tpath: string,\n\t\toptions: RequestInit = {}\n\t): Promise<T> {\n\t\tif (this.visitorBlocked) {\n\t\t\tconst method = (options.method ?? \"GET\").toUpperCase();\n\t\t\tconst [rawPath] = path.split(\"?\");\n\t\t\tconst normalizedPath = rawPath?.endsWith(\"/\")\n\t\t\t\t? rawPath.slice(0, -1)\n\t\t\t\t: rawPath;\n\t\t\tconst isWebsitesRoot = normalizedPath === \"/websites\";\n\t\t\tconst isSafeMethod = method === \"GET\" || method === \"HEAD\";\n\n\t\t\tif (!(isWebsitesRoot && isSafeMethod)) {\n\t\t\t\tthrow new CossistantAPIError({\n\t\t\t\t\tcode: \"VISITOR_BLOCKED\",\n\t\t\t\t\tmessage: \"Visitor is blocked and cannot perform this action.\",\n\t\t\t\t\tdetails: { path, method },\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tconst url = `${this.config.apiUrl}${path}`;\n\n\t\tconst response = await fetch(url, {\n\t\t\t...options,\n\t\t\theaders: {\n\t\t\t\t...this.baseHeaders,\n\t\t\t\t...options.headers,\n\t\t\t},\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tconst errorData = await response.json().catch(() => ({}));\n\t\t\tconst statusCode = response.status;\n\t\t\tconst errorCode = errorData.code || `HTTP_${statusCode}`;\n\t\t\tconst serverMessage = errorData.message;\n\n\t\t\t// Determine if this is an authentication/authorization error\n\t\t\tconst isAuthError =\n\t\t\t\tstatusCode === 401 ||\n\t\t\t\tstatusCode === 403 ||\n\t\t\t\terrorCode === \"UNAUTHORIZED\" ||\n\t\t\t\terrorCode === \"FORBIDDEN\" ||\n\t\t\t\terrorCode === \"INVALID_API_KEY\" ||\n\t\t\t\terrorCode === \"API_KEY_EXPIRED\" ||\n\t\t\t\terrorCode === \"API_KEY_MISSING\" ||\n\t\t\t\terrorCode?.toUpperCase().includes(\"AUTH\") ||\n\t\t\t\terrorCode?.toUpperCase().includes(\"API_KEY\");\n\n\t\t\t// Use appropriate error message based on error type\n\t\t\tconst errorMessage = isAuthError\n\t\t\t\t? \"Your Cossistant public API key is invalid, expired, missing or not authorized to access this resource.\"\n\t\t\t\t: serverMessage || `Request failed with status ${statusCode}`;\n\n\t\t\t// Log with appropriate level based on error type\n\t\t\tif (isAuthError) {\n\t\t\t\tlogger.error(errorMessage, {\n\t\t\t\t\tdetails: errorData.details,\n\t\t\t\t\tpath,\n\t\t\t\t\tstatus: statusCode,\n\t\t\t\t\tcode: errorCode,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tlogger.error(\"API request failed\", {\n\t\t\t\t\tmessage: errorMessage,\n\t\t\t\t\tdetails: errorData.details,\n\t\t\t\t\tpath,\n\t\t\t\t\tstatus: statusCode,\n\t\t\t\t\tcode: errorCode,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthrow new CossistantAPIError({\n\t\t\t\tcode: errorCode,\n\t\t\t\tmessage: errorMessage,\n\t\t\t\tdetails: errorData.details,\n\t\t\t});\n\t\t}\n\n\t\treturn response.json();\n\t}\n\n\tasync getWebsite(): Promise<PublicWebsiteResponse> {\n\t\t// Make the request with visitor ID if we have one stored\n\t\tconst headers: Record<string, string> = {};\n\n\t\t// First, check if we already know the website ID and have a visitor ID for it\n\t\tif (this.websiteId) {\n\t\t\tconst storedVisitorId = getVisitorId(this.websiteId);\n\t\t\tif (storedVisitorId) {\n\t\t\t\theaders[\"X-Visitor-Id\"] = storedVisitorId;\n\t\t\t}\n\t\t} else {\n\t\t\t// We don't know the website ID yet, but check if we have any existing visitor\n\t\t\t// This prevents creating duplicate visitors on page refresh\n\t\t\tconst existingVisitor = getExistingVisitorId(this.publicKey);\n\t\t\tif (existingVisitor) {\n\t\t\t\theaders[\"X-Visitor-Id\"] = existingVisitor.visitorId;\n\t\t\t\t// Pre-populate our local state\n\t\t\t\tthis.websiteId = existingVisitor.websiteId;\n\t\t\t\tthis.visitorId = existingVisitor.visitorId;\n\t\t\t}\n\t\t}\n\n\t\tconst response = await this.request<PublicWebsiteResponse>(\"/websites\", {\n\t\t\theaders,\n\t\t});\n\n\t\t// Store the website ID for future requests\n\t\tthis.websiteId = response.id;\n\n\t\t// Store the visitor ID if we got one\n\t\tthis.visitorBlocked = response.visitor?.isBlocked ?? false;\n\n\t\tif (response.visitor?.id) {\n\t\t\tif (this.visitorBlocked) {\n\t\t\t\tthis.visitorId = response.visitor.id;\n\t\t\t\tsetVisitorId(response.id, response.visitor.id);\n\t\t\t\treturn response;\n\t\t\t}\n\n\t\t\tthis.visitorId = response.visitor.id;\n\t\t\tsetVisitorId(response.id, response.visitor.id);\n\t\t\tthis.syncVisitorSnapshot(response.visitor.id);\n\t\t}\n\n\t\treturn response;\n\t}\n\n\t// Manually prime website and visitor context when the caller already has it\n\tsetWebsiteContext(websiteId: string, visitorId?: string): void {\n\t\tthis.websiteId = websiteId;\n\t\tif (visitorId) {\n\t\t\tthis.visitorId = visitorId;\n\t\t\tsetVisitorId(websiteId, visitorId);\n\t\t}\n\t}\n\n\tsetVisitorBlocked(isBlocked: boolean): void {\n\t\tthis.visitorBlocked = isBlocked;\n\t}\n\n\tgetCurrentWebsiteId(): string | null {\n\t\treturn this.websiteId;\n\t}\n\n\tgetCurrentVisitorId(): string | null {\n\t\tif (this.visitorId) {\n\t\t\treturn this.visitorId;\n\t\t}\n\n\t\tif (!this.websiteId) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn getVisitorId(this.websiteId) ?? null;\n\t}\n\n\tasync updateVisitorMetadata(\n\t\tmetadata: VisitorMetadata\n\t): Promise<VisitorResponse> {\n\t\tconst visitorId = this.resolveVisitorId();\n\t\tconst response = await this.request<VisitorResponse>(\n\t\t\t`/visitors/${visitorId}/metadata`,\n\t\t\t{\n\t\t\t\tmethod: \"PATCH\",\n\t\t\t\tbody: JSON.stringify({ metadata }),\n\t\t\t\theaders: {\n\t\t\t\t\t\"X-Visitor-Id\": visitorId,\n\t\t\t\t},\n\t\t\t}\n\t\t);\n\n\t\treturn this.normalizeVisitorResponse(response);\n\t}\n\n\t/**\n\t * Identify a visitor by creating or updating their contact information\n\t * This will link the visitor to a contact record that can be tracked across devices\n\t */\n\tasync identify(params: {\n\t\texternalId?: string;\n\t\temail?: string;\n\t\tname?: string;\n\t\timage?: string;\n\t\tmetadata?: Record<string, unknown>;\n\t\tcontactOrganizationId?: string;\n\t}): Promise<IdentifyContactResponse> {\n\t\tconst visitorId = this.resolveVisitorId();\n\n\t\tconst response = await this.request<IdentifyContactResponse>(\n\t\t\t\"/contacts/identify\",\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tvisitorId,\n\t\t\t\t\t...params,\n\t\t\t\t}),\n\t\t\t\theaders: {\n\t\t\t\t\t\"X-Visitor-Id\": visitorId,\n\t\t\t\t},\n\t\t\t}\n\t\t);\n\n\t\treturn {\n\t\t\tcontact: {\n\t\t\t\t...response.contact,\n\t\t\t\t// Ensure metadata is properly typed\n\t\t\t\tmetadata:\n\t\t\t\t\ttypeof response.contact.metadata === \"string\"\n\t\t\t\t\t\t? JSON.parse(response.contact.metadata)\n\t\t\t\t\t\t: response.contact.metadata,\n\t\t\t\tcreatedAt: response.contact.createdAt,\n\t\t\t\tupdatedAt: response.contact.updatedAt,\n\t\t\t},\n\t\t\tvisitorId: response.visitorId,\n\t\t};\n\t}\n\n\t/**\n\t * Update metadata for the contact associated with the current visitor\n\t * Note: The visitor must be identified first via the identify() method\n\t */\n\tasync updateContactMetadata(\n\t\tmetadata: Record<string, unknown>\n\t): Promise<VisitorResponse> {\n\t\t// This still uses the visitor metadata endpoint for backward compatibility\n\t\t// The endpoint will internally update the contact metadata\n\t\treturn this.updateVisitorMetadata(metadata as VisitorMetadata);\n\t}\n\n\tasync createConversation(\n\t\tparams: Partial<CreateConversationRequestBody> = {}\n\t): Promise<CreateConversationResponseBody> {\n\t\tconst conversationId = params.conversationId || generateConversationId();\n\n\t\t// Get visitor ID from storage if we have the website ID, or use the provided one\n\t\tconst storedVisitorId = this.websiteId\n\t\t\t? getVisitorId(this.websiteId)\n\t\t\t: undefined;\n\t\tconst visitorId = params.visitorId || storedVisitorId;\n\n\t\tif (!visitorId) {\n\t\t\tthrow new Error(\"Visitor ID is required\");\n\t\t}\n\n\t\tconst body: CreateConversationRequestBody = {\n\t\t\tconversationId,\n\t\t\tvisitorId,\n\t\t\tdefaultTimelineItems: params.defaultTimelineItems || [],\n\t\t\tchannel: params.channel || \"widget\",\n\t\t};\n\n\t\t// Add visitor ID header if available\n\t\tconst headers: Record<string, string> = {};\n\t\tif (visitorId) {\n\t\t\theaders[\"X-Visitor-Id\"] = visitorId;\n\t\t}\n\n\t\tconst response = await this.request<CreateConversationResponseBody>(\n\t\t\t\"/conversations\",\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\theaders,\n\t\t\t}\n\t\t);\n\n\t\t// Convert date strings to Date objects\n\t\treturn {\n\t\t\tconversation: {\n\t\t\t\t...response.conversation,\n\t\t\t\tcreatedAt: response.conversation.createdAt,\n\t\t\t\tupdatedAt: response.conversation.updatedAt,\n\t\t\t\tdeletedAt: response.conversation.deletedAt ?? null,\n\t\t\t\tlastTimelineItem: response.conversation.lastTimelineItem,\n\t\t\t},\n\t\t\tinitialTimelineItems: response.initialTimelineItems,\n\t\t};\n\t}\n\n\tasync updateConfiguration(config: Partial<CossistantConfig>): Promise<void> {\n\t\tif (config.publicKey) {\n\t\t\tthis.publicKey = config.publicKey;\n\t\t\tthis.baseHeaders[\"X-Public-Key\"] = config.publicKey;\n\t\t}\n\n\t\tif (config.userId) {\n\t\t\tthis.baseHeaders[\"X-User-ID\"] = config.userId;\n\t\t} else if (config.userId === null) {\n\t\t\tconst { \"X-User-ID\": _, ...rest } = this.baseHeaders;\n\t\t\tthis.baseHeaders = rest;\n\t\t}\n\n\t\tif (config.organizationId) {\n\t\t\tthis.baseHeaders[\"X-Organization-ID\"] = config.organizationId;\n\t\t} else if (config.organizationId === null) {\n\t\t\tconst { \"X-Organization-ID\": _, ...rest } = this.baseHeaders;\n\t\t\tthis.baseHeaders = rest;\n\t\t}\n\n\t\tthis.config = { ...this.config, ...config };\n\t}\n\n\tasync listConversations(\n\t\tparams: Partial<ListConversationsRequest> = {}\n\t): Promise<ListConversationsResponse> {\n\t\t// Get visitor ID from storage if we have the website ID, or use the provided one\n\t\tconst storedVisitorId = this.websiteId\n\t\t\t? getVisitorId(this.websiteId)\n\t\t\t: undefined;\n\t\tconst visitorId = params.visitorId || storedVisitorId;\n\n\t\tif (!visitorId) {\n\t\t\tthrow new Error(\"Visitor ID is required\");\n\t\t}\n\n\t\t// Create query parameters\n\t\tconst queryParams = new URLSearchParams();\n\n\t\tif (visitorId) {\n\t\t\tqueryParams.set(\"visitorId\", visitorId);\n\t\t}\n\n\t\tif (params.page) {\n\t\t\tqueryParams.set(\"page\", params.page.toString());\n\t\t}\n\n\t\tif (params.limit) {\n\t\t\tqueryParams.set(\"limit\", params.limit.toString());\n\t\t}\n\n\t\tif (params.status) {\n\t\t\tqueryParams.set(\"status\", params.status);\n\t\t}\n\n\t\tif (params.orderBy) {\n\t\t\tqueryParams.set(\"orderBy\", params.orderBy);\n\t\t}\n\n\t\tif (params.order) {\n\t\t\tqueryParams.set(\"order\", params.order);\n\t\t}\n\n\t\t// Add visitor ID header if available\n\t\tconst headers: Record<string, string> = {};\n\t\tif (visitorId) {\n\t\t\theaders[\"X-Visitor-Id\"] = visitorId;\n\t\t}\n\n\t\tconst response = await this.request<ListConversationsResponse>(\n\t\t\t`/conversations?${queryParams.toString()}`,\n\t\t\t{\n\t\t\t\theaders,\n\t\t\t}\n\t\t);\n\n\t\t// Convert date strings to Date objects\n\t\treturn {\n\t\t\tconversations: response.conversations.map((conv) => ({\n\t\t\t\t...conv,\n\t\t\t\tcreatedAt: conv.createdAt,\n\t\t\t\tupdatedAt: conv.updatedAt,\n\t\t\t\tdeletedAt: conv.deletedAt ?? null,\n\t\t\t\tlastTimelineItem: conv.lastTimelineItem,\n\t\t\t})),\n\t\t\tpagination: response.pagination,\n\t\t};\n\t}\n\n\tasync getConversation(\n\t\tparams: GetConversationRequest\n\t): Promise<GetConversationResponse> {\n\t\t// Get visitor ID from storage if we have the website ID\n\t\tconst visitorId = this.websiteId ? getVisitorId(this.websiteId) : undefined;\n\n\t\t// Add visitor ID header if available\n\t\tconst headers: Record<string, string> = {};\n\t\tif (visitorId) {\n\t\t\theaders[\"X-Visitor-Id\"] = visitorId;\n\t\t}\n\n\t\tconst response = await this.request<GetConversationResponse>(\n\t\t\t`/conversations/${params.conversationId}`,\n\t\t\t{\n\t\t\t\theaders,\n\t\t\t}\n\t\t);\n\n\t\t// Convert date strings to Date objects\n\t\treturn {\n\t\t\tconversation: {\n\t\t\t\t...response.conversation,\n\t\t\t\tcreatedAt: response.conversation.createdAt,\n\t\t\t\tupdatedAt: response.conversation.updatedAt,\n\t\t\t\tdeletedAt: response.conversation.deletedAt ?? null,\n\t\t\t\tlastTimelineItem: response.conversation.lastTimelineItem,\n\t\t\t},\n\t\t};\n\t}\n\n\tasync markConversationSeen(\n\t\tparams: {\n\t\t\tconversationId: string;\n\t\t} & Partial<MarkConversationSeenRequestBody>\n\t): Promise<MarkConversationSeenResponseBody> {\n\t\tconst storedVisitorId = this.websiteId\n\t\t\t? getVisitorId(this.websiteId)\n\t\t\t: undefined;\n\t\tconst visitorId = params.visitorId || storedVisitorId;\n\n\t\tif (!visitorId) {\n\t\t\tthrow new Error(\"Visitor ID is required to mark a conversation as seen\");\n\t\t}\n\n\t\tconst headers: Record<string, string> = {};\n\t\tif (visitorId) {\n\t\t\theaders[\"X-Visitor-Id\"] = visitorId;\n\t\t}\n\n\t\tconst body: MarkConversationSeenRequestBody = {};\n\t\tif (params.visitorId) {\n\t\t\tbody.visitorId = params.visitorId;\n\t\t}\n\n\t\tconst response = await this.request<MarkConversationSeenResponseBody>(\n\t\t\t`/conversations/${params.conversationId}/seen`,\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\theaders,\n\t\t\t}\n\t\t);\n\n\t\treturn {\n\t\t\tconversationId: response.conversationId,\n\t\t\tlastSeenAt: response.lastSeenAt,\n\t\t};\n\t}\n\n\tasync getConversationSeenData(params: {\n\t\tconversationId: string;\n\t}): Promise<GetConversationSeenDataResponse> {\n\t\tconst response = await this.request<GetConversationSeenDataResponse>(\n\t\t\t`/conversations/${params.conversationId}/seen`,\n\t\t\t{\n\t\t\t\tmethod: \"GET\",\n\t\t\t}\n\t\t);\n\n\t\treturn {\n\t\t\tseenData: response.seenData.map((item) => ({\n\t\t\t\t...item,\n\t\t\t\tlastSeenAt: item.lastSeenAt,\n\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\tupdatedAt: item.updatedAt,\n\t\t\t\tdeletedAt: item.deletedAt ? item.deletedAt : null,\n\t\t\t})),\n\t\t};\n\t}\n\n\tasync setConversationTyping(params: {\n\t\tconversationId: string;\n\t\tisTyping: boolean;\n\t\tvisitorPreview?: string | null;\n\t\tvisitorId?: string;\n\t}): Promise<SetConversationTypingResponseBody> {\n\t\tconst storedVisitorId = this.websiteId\n\t\t\t? getVisitorId(this.websiteId)\n\t\t\t: undefined;\n\t\tconst visitorId = params.visitorId || storedVisitorId;\n\n\t\tif (!visitorId) {\n\t\t\tthrow new Error(\"Visitor ID is required to report typing state\");\n\t\t}\n\n\t\tconst headers: Record<string, string> = {};\n\t\tif (visitorId) {\n\t\t\theaders[\"X-Visitor-Id\"] = visitorId;\n\t\t}\n\n\t\tconst body: SetConversationTypingRequestBody = {\n\t\t\tisTyping: params.isTyping,\n\t\t};\n\n\t\tif (params.visitorId) {\n\t\t\tbody.visitorId = params.visitorId;\n\t\t}\n\n\t\tif (params.visitorPreview && params.isTyping) {\n\t\t\tbody.visitorPreview = params.visitorPreview.slice(0, 2000);\n\t\t}\n\n\t\tconst response = await this.request<SetConversationTypingResponseBody>(\n\t\t\t`/conversations/${params.conversationId}/typing`,\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\theaders,\n\t\t\t}\n\t\t);\n\n\t\treturn {\n\t\t\tconversationId: response.conversationId,\n\t\t\tisTyping: response.isTyping,\n\t\t\tvisitorPreview: response.visitorPreview,\n\t\t\tsentAt: response.sentAt,\n\t\t};\n\t}\n\n\tasync sendMessage(\n\t\tparams: SendTimelineItemRequest\n\t): Promise<SendTimelineItemResponse> {\n\t\t// Get visitor ID from storage if we have the website ID\n\t\tconst visitorId = this.websiteId ? getVisitorId(this.websiteId) : undefined;\n\n\t\t// Add visitor ID header if available\n\t\tconst headers: Record<string, string> = {};\n\t\tif (visitorId) {\n\t\t\theaders[\"X-Visitor-Id\"] = visitorId;\n\t\t}\n\n\t\tconst response = await this.request<SendTimelineItemResponse>(\"/messages\", {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(params),\n\t\t\theaders,\n\t\t});\n\n\t\treturn {\n\t\t\titem: response.item,\n\t\t};\n\t}\n\n\tasync getConversationTimelineItems(\n\t\tparams: GetConversationTimelineItemsRequest & { conversationId: string }\n\t): Promise<GetConversationTimelineItemsResponse> {\n\t\t// Get visitor ID from storage if we have the website ID\n\t\tconst visitorId = this.websiteId ? getVisitorId(this.websiteId) : undefined;\n\n\t\t// Create query parameters\n\t\tconst queryParams = new URLSearchParams();\n\n\t\tif (params.limit) {\n\t\t\tqueryParams.set(\"limit\", params.limit.toString());\n\t\t}\n\n\t\tif (params.cursor) {\n\t\t\tqueryParams.set(\"cursor\", params.cursor);\n\t\t}\n\n\t\t// Add visitor ID header if available\n\t\tconst headers: Record<string, string> = {};\n\t\tif (visitorId) {\n\t\t\theaders[\"X-Visitor-Id\"] = visitorId;\n\t\t}\n\n\t\tconst response = await this.request<GetConversationTimelineItemsResponse>(\n\t\t\t`/conversations/${params.conversationId}/timeline?${queryParams.toString()}`,\n\t\t\t{\n\t\t\t\theaders,\n\t\t\t}\n\t\t);\n\n\t\treturn {\n\t\t\titems: response.items,\n\t\t\tnextCursor: response.nextCursor,\n\t\t\thasNextPage: response.hasNextPage,\n\t\t};\n\t}\n\n\t/**\n\t * Generate a presigned URL for uploading a file to S3.\n\t * The URL can be used to PUT a file directly to S3.\n\t */\n\tasync generateUploadUrl(\n\t\tparams: Omit<GenerateUploadUrlRequest, \"websiteId\" | \"scope\"> & {\n\t\t\tconversationId: string;\n\t\t}\n\t): Promise<GenerateUploadUrlResponse> {\n\t\tif (!this.websiteId) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Website ID is required. Call getWebsite() first to initialize the client.\"\n\t\t\t);\n\t\t}\n\n\t\tconst visitorId = this.resolveVisitorId();\n\n\t\t// Validate file constraints on client side\n\t\tif (!isAllowedMimeType(params.contentType)) {\n\t\t\tthrow new Error(`File type \"${params.contentType}\" is not allowed`);\n\t\t}\n\n\t\tconst headers: Record<string, string> = {};\n\t\tif (visitorId) {\n\t\t\theaders[\"X-Visitor-Id\"] = visitorId;\n\t\t}\n\n\t\t// Get organization ID from website response (stored during getWebsite)\n\t\t// For now, we'll make an additional call to get website info\n\t\tconst websiteResponse = await this.request<{ organizationId: string }>(\n\t\t\t\"/websites\",\n\t\t\t{ headers }\n\t\t);\n\n\t\tconst body: GenerateUploadUrlRequest = {\n\t\t\tcontentType: params.contentType,\n\t\t\twebsiteId: this.websiteId,\n\t\t\tscope: {\n\t\t\t\ttype: \"conversation\",\n\t\t\t\torganizationId: websiteResponse.organizationId,\n\t\t\t\twebsiteId: this.websiteId,\n\t\t\t\tconversationId: params.conversationId,\n\t\t\t},\n\t\t\tfileName: params.fileName,\n\t\t\tfileExtension: params.fileExtension,\n\t\t\tpath: params.path,\n\t\t\tuseCdn: false, // Files should not go to CDN\n\t\t\texpiresInSeconds: params.expiresInSeconds,\n\t\t};\n\n\t\tconst response = await this.request<GenerateUploadUrlResponse>(\n\t\t\t\"/uploads/sign-url\",\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\theaders,\n\t\t\t}\n\t\t);\n\n\t\treturn response;\n\t}\n\n\t/**\n\t * Upload a file to S3 using a presigned URL.\n\t * @returns The public URL of the uploaded file\n\t */\n\tasync uploadFile(\n\t\tfile: File,\n\t\tuploadUrl: string,\n\t\tcontentType: string\n\t): Promise<void> {\n\t\t// Validate file before upload\n\t\tconst validationError = validateFile(file);\n\t\tif (validationError) {\n\t\t\tthrow new Error(validationError);\n\t\t}\n\n\t\tconst response = await fetch(uploadUrl, {\n\t\t\tmethod: \"PUT\",\n\t\t\tbody: file,\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": contentType,\n\t\t\t},\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to upload file: ${response.status} ${response.statusText}`\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Upload multiple files for a conversation message.\n\t * Files are uploaded in parallel and the function returns timeline parts\n\t * that can be included in a message.\n\t */\n\tasync uploadFilesForMessage(\n\t\tfiles: File[],\n\t\tconversationId: string\n\t): Promise<\n\t\tArray<\n\t\t\t| {\n\t\t\t\t\ttype: \"image\";\n\t\t\t\t\turl: string;\n\t\t\t\t\tmediaType: string;\n\t\t\t\t\tfileName?: string;\n\t\t\t\t\tsize?: number;\n\t\t\t }\n\t\t\t| {\n\t\t\t\t\ttype: \"file\";\n\t\t\t\t\turl: string;\n\t\t\t\t\tmediaType: string;\n\t\t\t\t\tfileName?: string;\n\t\t\t\t\tsize?: number;\n\t\t\t }\n\t\t>\n\t> {\n\t\tif (files.length === 0) {\n\t\t\treturn [];\n\t\t}\n\n\t\t// Validate all files first\n\t\tfor (const file of files) {\n\t\t\tconst error = validateFile(file);\n\t\t\tif (error) {\n\t\t\t\tthrow new Error(error);\n\t\t\t}\n\t\t}\n\n\t\t// Upload files in parallel\n\t\tconst uploadPromises = files.map(async (file) => {\n\t\t\t// Generate presigned URL\n\t\t\tconst uploadInfo = await this.generateUploadUrl({\n\t\t\t\tconversationId,\n\t\t\t\tcontentType: file.type,\n\t\t\t\tfileName: file.name,\n\t\t\t});\n\n\t\t\t// Upload file to S3\n\t\t\tawait this.uploadFile(file, uploadInfo.uploadUrl, file.type);\n\n\t\t\t// Return timeline part based on file type\n\t\t\tconst isImage = file.type.startsWith(\"image/\");\n\t\t\treturn {\n\t\t\t\ttype: isImage ? (\"image\" as const) : (\"file\" as const),\n\t\t\t\turl: uploadInfo.publicUrl,\n\t\t\t\tmediaType: file.type,\n\t\t\t\tfileName: file.name,\n\t\t\t\tsize: file.size,\n\t\t\t};\n\t\t});\n\n\t\treturn Promise.all(uploadPromises);\n\t}\n}\n"],"mappings":";;;;;;;;AA8CA,IAAa,uBAAb,MAAkC;CACjC,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ,YAA2B;CACnC,AAAQ,YAA2B;CACnC,AAAQ,iBAAiB;CAEzB,YAAY,QAA0B;AACrC,OAAK,SAAS;AAGd,OAAK,YACJ,OAAO,cACN,OAAO,YAAY,cACjB,QAAQ,IAAI,iCACZ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B,MAAM,QAAQ,aAAa,KAAK;AAChC,OAAI,MACH,OAAM,IAAI,MAAM,MAAM;;EAKxB,MAAM,iBAAiB,MAAM,IAAI,OAAO,SAAS;GAEhD,MAAM,aAAa,MAAM,KAAK,kBAAkB;IAC/C;IACA,aAAa,KAAK;IAClB,UAAU,KAAK;IACf,CAAC;AAGF,SAAM,KAAK,WAAW,MAAM,WAAW,WAAW,KAAK,KAAK;AAI5D,UAAO;IACN,MAFe,KAAK,KAAK,WAAW,SAAS,GAE5B,UAAqB;IACtC,KAAK,WAAW;IAChB,WAAW,KAAK;IAChB,UAAU,KAAK;IACf,MAAM,KAAK;IACX;IACA;AAEF,SAAO,QAAQ,IAAI,eAAe"}
|
package/schemas.d.ts
CHANGED
|
@@ -15,6 +15,7 @@ declare const conversationSchema: z.ZodObject<{
|
|
|
15
15
|
spam: "spam";
|
|
16
16
|
}>>;
|
|
17
17
|
deletedAt: z.ZodDefault<z.ZodNullable<z.ZodString>>;
|
|
18
|
+
visitorLastSeenAt: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
18
19
|
lastTimelineItem: z.ZodOptional<z.ZodObject<{
|
|
19
20
|
id: z.ZodOptional<z.ZodString>;
|
|
20
21
|
conversationId: z.ZodString;
|
package/schemas.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schemas.d.ts","names":[],"sources":["../../types/src/schemas.ts"],"sourcesContent":[],"mappings":";;;;cAkBa,oBAAkB,CAAA,CAAA
|
|
1
|
+
{"version":3,"file":"schemas.d.ts","names":[],"sources":["../../types/src/schemas.ts"],"sourcesContent":[],"mappings":";;;;cAkBa,oBAAkB,CAAA,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAAA,SAAA,eAAA,YAAA,CAAA;IAAA,SAAA,eAAA,YAAA,CAAA;IAmBnB,SAAA,aAAY;IAEX,SAAA,eAUX,cAAA,YAAA,CAAA,CAAA;;;KAZU,YAAA,GAAe,CAAA,CAAE,aAAa;cAE7B,wBAAsB,CAAA,CAAA;;;;;;;;;;;AAAA,KAYvB,gBAAA,GAAmB,CAAA,CAAE,KAZE,CAAA,OAYW,sBAZX,CAAA"}
|
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
import { ListConversationsResponse } from "../conversation.js";
|
|
2
2
|
import { Store } from "./create-store.js";
|
|
3
|
-
import { Conversation } from "@cossistant/types";
|
|
4
3
|
|
|
5
4
|
//#region src/store/conversations-store.d.ts
|
|
6
5
|
type ConversationPagination = ListConversationsResponse["pagination"];
|
|
6
|
+
type ConversationWithSeen = ListConversationsResponse["conversations"][number];
|
|
7
7
|
type ConversationsState = {
|
|
8
8
|
ids: string[];
|
|
9
|
-
byId: Record<string,
|
|
9
|
+
byId: Record<string, ConversationWithSeen>;
|
|
10
10
|
pagination: ConversationPagination | null;
|
|
11
11
|
};
|
|
12
12
|
type ConversationsStore = Store<ConversationsState> & {
|
|
13
13
|
ingestList(response: ListConversationsResponse): void;
|
|
14
|
-
ingestConversation(conversation:
|
|
14
|
+
ingestConversation(conversation: ConversationWithSeen): void;
|
|
15
15
|
};
|
|
16
16
|
declare function createConversationsStore(initialState?: ConversationsState): ConversationsStore;
|
|
17
|
-
declare function getConversations(store: Store<ConversationsState>):
|
|
18
|
-
declare function getConversationById(store: Store<ConversationsState>, conversationId: string):
|
|
17
|
+
declare function getConversations(store: Store<ConversationsState>): ConversationWithSeen[];
|
|
18
|
+
declare function getConversationById(store: Store<ConversationsState>, conversationId: string): ConversationWithSeen | undefined;
|
|
19
19
|
declare function getConversationPagination(store: Store<ConversationsState>): ConversationPagination | null;
|
|
20
20
|
//#endregion
|
|
21
|
-
export { ConversationPagination, ConversationsState, ConversationsStore, createConversationsStore, getConversationById, getConversationPagination, getConversations };
|
|
21
|
+
export { ConversationPagination, ConversationWithSeen, ConversationsState, ConversationsStore, createConversationsStore, getConversationById, getConversationPagination, getConversations };
|
|
22
22
|
//# sourceMappingURL=conversations-store.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conversations-store.d.ts","names":[],"sources":["../../src/store/conversations-store.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"conversations-store.d.ts","names":[],"sources":["../../src/store/conversations-store.ts"],"sourcesContent":[],"mappings":";;;;KAGY,sBAAA,GAAyB;KAGzB,oBAAA,GACX;AAJW,KAMA,kBAAA,GANsB;EAGtB,GAAA,EAAA,MAAA,EAAA;EAGA,IAAA,EAEL,MAFK,CAAA,MAAA,EAEU,oBAFQ,CAAA;EAER,UAAA,EACT,sBADS,GAAA,IAAA;CAAf;AACM,KAkMD,kBAAA,GAAqB,KAlMpB,CAkM0B,kBAlM1B,CAAA,GAAA;EAAsB,UAAA,CAAA,QAAA,EAmMb,yBAnMa,CAAA,EAAA,IAAA;EAkMvB,kBAAA,CAAA,YAAkB,EAEI,oBAFJ,CAAA,EAAA,IAAA;CAAS;AAAN,iBAKjB,wBAAA,CALiB,YAAA,CAAA,EAMlB,kBANkB,CAAA,EAO9B,kBAP8B;AACX,iBAoBN,gBAAA,CApBM,KAAA,EAqBd,KArBc,CAqBR,kBArBQ,CAAA,CAAA,EAsBnB,oBAtBmB,EAAA;AACY,iBA+BlB,mBAAA,CA/BkB,KAAA,EAgC1B,KAhC0B,CAgCpB,kBAhCoB,CAAA,EAAA,cAAA,EAAA,MAAA,CAAA,EAkC/B,oBAlC+B,GAAA,SAAA;AAAoB,iBAsCtC,yBAAA,CAtCsC,KAAA,EAuC9C,KAvC8C,CAuCxC,kBAvCwC,CAAA,CAAA,EAwCnD,sBAxCmD,GAAA,IAAA"}
|
|
@@ -12,7 +12,8 @@ function isSameDate(a, b) {
|
|
|
12
12
|
}
|
|
13
13
|
function isSameConversation(a, b) {
|
|
14
14
|
const deletedAtMatch = !(a.deletedAt || b.deletedAt) || a.deletedAt && b.deletedAt && isSameDate(a.deletedAt, b.deletedAt);
|
|
15
|
-
|
|
15
|
+
const visitorLastSeenAtMatch = !(a.visitorLastSeenAt || b.visitorLastSeenAt) || a.visitorLastSeenAt && b.visitorLastSeenAt && isSameDate(a.visitorLastSeenAt, b.visitorLastSeenAt);
|
|
16
|
+
if (!(a.id === b.id && a.title === b.title && a.status === b.status && a.visitorId === b.visitorId && a.websiteId === b.websiteId && isSameDate(a.createdAt, b.createdAt) && isSameDate(a.updatedAt, b.updatedAt) && deletedAtMatch && visitorLastSeenAtMatch)) return false;
|
|
16
17
|
if (!(a.lastTimelineItem || b.lastTimelineItem)) return true;
|
|
17
18
|
if (!(a.lastTimelineItem && b.lastTimelineItem)) return false;
|
|
18
19
|
return a.lastTimelineItem.id === b.lastTimelineItem.id && a.lastTimelineItem.text === b.lastTimelineItem.text && isSameDate(a.lastTimelineItem.createdAt, b.lastTimelineItem.createdAt);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conversations-store.js","names":["INITIAL_STATE: ConversationsState","next"],"sources":["../../src/store/conversations-store.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"conversations-store.js","names":["INITIAL_STATE: ConversationsState","next"],"sources":["../../src/store/conversations-store.ts"],"sourcesContent":["import type { ListConversationsResponse } from \"@cossistant/types/api/conversation\";\nimport { createStore, type Store } from \"./create-store\";\n\nexport type ConversationPagination = ListConversationsResponse[\"pagination\"];\n\n// Use the conversation type from the list response which includes visitorLastSeenAt\nexport type ConversationWithSeen =\n\tListConversationsResponse[\"conversations\"][number];\n\nexport type ConversationsState = {\n\tids: string[];\n\tbyId: Record<string, ConversationWithSeen>;\n\tpagination: ConversationPagination | null;\n};\n\nconst INITIAL_STATE: ConversationsState = {\n\tids: [],\n\tbyId: {},\n\tpagination: null,\n};\n\nfunction isSameDate(a: Date | string, b: Date | string): boolean {\n\tif (a === b) {\n\t\treturn true;\n\t}\n\n\tconst aTime = typeof a === \"string\" ? new Date(a).getTime() : a.getTime();\n\tconst bTime = typeof b === \"string\" ? new Date(b).getTime() : b.getTime();\n\n\treturn aTime === bTime;\n}\n\nfunction isSameConversation(\n\ta: ConversationWithSeen,\n\tb: ConversationWithSeen\n): boolean {\n\t// Check basic fields\n\tconst deletedAtMatch =\n\t\t!(a.deletedAt || b.deletedAt) ||\n\t\t(a.deletedAt && b.deletedAt && isSameDate(a.deletedAt, b.deletedAt));\n\n\t// Check visitorLastSeenAt\n\tconst visitorLastSeenAtMatch =\n\t\t!(a.visitorLastSeenAt || b.visitorLastSeenAt) ||\n\t\t(a.visitorLastSeenAt &&\n\t\t\tb.visitorLastSeenAt &&\n\t\t\tisSameDate(a.visitorLastSeenAt, b.visitorLastSeenAt));\n\n\tconst basicMatch =\n\t\ta.id === b.id &&\n\t\ta.title === b.title &&\n\t\ta.status === b.status &&\n\t\ta.visitorId === b.visitorId &&\n\t\ta.websiteId === b.websiteId &&\n\t\tisSameDate(a.createdAt, b.createdAt) &&\n\t\tisSameDate(a.updatedAt, b.updatedAt) &&\n\t\tdeletedAtMatch &&\n\t\tvisitorLastSeenAtMatch;\n\n\tif (!basicMatch) {\n\t\treturn false;\n\t}\n\n\t// Check lastTimelineItem - both undefined/null is a match\n\tif (!(a.lastTimelineItem || b.lastTimelineItem)) {\n\t\treturn true;\n\t}\n\n\t// One has timeline item, one doesn't - not a match\n\tif (!(a.lastTimelineItem && b.lastTimelineItem)) {\n\t\treturn false;\n\t}\n\n\t// Both have timeline items - compare them\n\treturn (\n\t\ta.lastTimelineItem.id === b.lastTimelineItem.id &&\n\t\ta.lastTimelineItem.text === b.lastTimelineItem.text &&\n\t\tisSameDate(a.lastTimelineItem.createdAt, b.lastTimelineItem.createdAt)\n\t);\n}\n\nfunction mergeMap(\n\texisting: Record<string, ConversationWithSeen>,\n\tincoming: ConversationWithSeen[]\n): [Record<string, ConversationWithSeen>, boolean] {\n\tlet changed = false;\n\tlet next = existing;\n\n\tfor (const conversation of incoming) {\n\t\tconst previous = next[conversation.id];\n\t\tif (!(previous && isSameConversation(previous, conversation))) {\n\t\t\tif (!changed) {\n\t\t\t\tnext = { ...next };\n\t\t\t\tchanged = true;\n\t\t\t}\n\t\t\tnext[conversation.id] = conversation;\n\t\t}\n\t}\n\n\treturn [next, changed];\n}\n\nfunction mergeOrder(\n\texisting: string[],\n\tincoming: string[],\n\tpage: number\n): [string[], boolean] {\n\tif (incoming.length === 0) {\n\t\treturn [existing, false];\n\t}\n\n\tif (page <= 1) {\n\t\tconst rest = existing.filter((id) => !incoming.includes(id));\n\t\tconst next = [...incoming, ...rest];\n\t\tconst changed =\n\t\t\tnext.length !== existing.length ||\n\t\t\tnext.some((value, index) => value !== existing[index]);\n\t\treturn changed ? [next, true] : [existing, false];\n\t}\n\n\tlet changed = false;\n\tconst seen = new Set(existing);\n\tconst next = [...existing];\n\n\tfor (const id of incoming) {\n\t\tif (seen.has(id)) {\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(id);\n\t\tnext.push(id);\n\t\tchanged = true;\n\t}\n\n\treturn changed ? [next, true] : [existing, false];\n}\n\nfunction isSamePagination(\n\ta: ConversationPagination | null,\n\tb: ConversationPagination | null\n): boolean {\n\tif (a === b) {\n\t\treturn true;\n\t}\n\tif (!(a && b)) {\n\t\treturn !(a || b);\n\t}\n\treturn (\n\t\ta.page === b.page &&\n\t\ta.limit === b.limit &&\n\t\ta.total === b.total &&\n\t\ta.totalPages === b.totalPages &&\n\t\ta.hasMore === b.hasMore\n\t);\n}\n\nfunction applyList(\n\tstate: ConversationsState,\n\tresponse: ListConversationsResponse\n): ConversationsState {\n\tconst [byId, mapChanged] = mergeMap(state.byId, response.conversations);\n\tconst [ids, idsChanged] = mergeOrder(\n\t\tstate.ids,\n\t\tresponse.conversations.map((conversation) => conversation.id),\n\t\tresponse.pagination.page\n\t);\n\tconst paginationChanged = !isSamePagination(\n\t\tstate.pagination,\n\t\tresponse.pagination\n\t);\n\n\tif (!(mapChanged || idsChanged || paginationChanged)) {\n\t\treturn state;\n\t}\n\n\treturn {\n\t\tbyId,\n\t\tids,\n\t\tpagination: paginationChanged ? response.pagination : state.pagination,\n\t};\n}\n\nfunction applyConversation(\n\tstate: ConversationsState,\n\tconversation: ConversationWithSeen\n): ConversationsState {\n\tconst previous = state.byId[conversation.id];\n\tconst sameConversation = previous\n\t\t? isSameConversation(previous, conversation)\n\t\t: false;\n\tconst byId = sameConversation\n\t\t? state.byId\n\t\t: { ...state.byId, [conversation.id]: conversation };\n\tconst hasId = state.ids.includes(conversation.id);\n\tconst ids = hasId ? state.ids : [...state.ids, conversation.id];\n\n\tif (byId === state.byId && ids === state.ids) {\n\t\treturn state;\n\t}\n\n\treturn {\n\t\tbyId,\n\t\tids,\n\t\tpagination: state.pagination,\n\t};\n}\n\nexport type ConversationsStore = Store<ConversationsState> & {\n\tingestList(response: ListConversationsResponse): void;\n\tingestConversation(conversation: ConversationWithSeen): void;\n};\n\nexport function createConversationsStore(\n\tinitialState: ConversationsState = INITIAL_STATE\n): ConversationsStore {\n\tconst store = createStore<ConversationsState>(initialState);\n\n\treturn {\n\t\t...store,\n\t\tingestList(response) {\n\t\t\tstore.setState((state) => applyList(state, response));\n\t\t},\n\t\tingestConversation(conversation) {\n\t\t\tstore.setState((state) => applyConversation(state, conversation));\n\t\t},\n\t};\n}\n\nexport function getConversations(\n\tstore: Store<ConversationsState>\n): ConversationWithSeen[] {\n\tconst state = store.getState();\n\treturn state.ids\n\t\t.map((id) => state.byId[id])\n\t\t.filter(\n\t\t\t(conversation): conversation is ConversationWithSeen =>\n\t\t\t\tconversation !== undefined\n\t\t);\n}\n\nexport function getConversationById(\n\tstore: Store<ConversationsState>,\n\tconversationId: string\n): ConversationWithSeen | undefined {\n\treturn store.getState().byId[conversationId];\n}\n\nexport function getConversationPagination(\n\tstore: Store<ConversationsState>\n): ConversationPagination | null {\n\treturn store.getState().pagination;\n}\n"],"mappings":";;;AAeA,MAAMA,gBAAoC;CACzC,KAAK,EAAE;CACP,MAAM,EAAE;CACR,YAAY;CACZ;AAED,SAAS,WAAW,G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E,OAAA,EAAA,MAAA;AAOhB,CAAA;AAOA,KA7KK,gBAAA,GAAmB,aA6KoB,GAAA;EA8D5B,QAAA,EAAA,OAAA;EA+BA,OAAA,CAAA,EAAA,MAAA,GAAA,IAAA;EACF,KAAA,CAAA,EAAA,MAAA;CAAN;AAEL,KAtOS,WAAA,GAAc,KAsOvB,CAtO6B,WAsO7B,CAAA,GAAA;EAAuB,SAAA,CAAA,OAAA,EArON,gBAqOM,CAAA,EAAA,IAAA;wBApOH;;;iBAIP,iBAAA,gBACD,4BACA,0BACZ;iBA+Ga,cAAA,QACR,sBACE;iBAKM,gBAAA,QACR,sBACE;iBAKM,4BAAA,QACR,oBACA;;;;;;iBA4DQ,2BAAA,QACR,oBACA;iBA6BQ,qBAAA,QACR,MAAM,uCAEX"}
|
package/store/typing-store.js
CHANGED
|
@@ -100,12 +100,12 @@ function applyConversationTypingEvent(store, event, options = {}) {
|
|
|
100
100
|
if (payload.userId) {
|
|
101
101
|
actorType = "user";
|
|
102
102
|
actorId = payload.userId;
|
|
103
|
-
} else if (payload.visitorId) {
|
|
104
|
-
actorType = "visitor";
|
|
105
|
-
actorId = payload.visitorId;
|
|
106
103
|
} else if (payload.aiAgentId) {
|
|
107
104
|
actorType = "ai_agent";
|
|
108
105
|
actorId = payload.aiAgentId;
|
|
106
|
+
} else if (payload.visitorId) {
|
|
107
|
+
actorType = "visitor";
|
|
108
|
+
actorId = payload.visitorId;
|
|
109
109
|
}
|
|
110
110
|
if (!(actorType && actorId)) return;
|
|
111
111
|
if (actorType === "visitor" && payload.visitorId && options.ignoreVisitorId && payload.visitorId === options.ignoreVisitorId || actorType === "user" && payload.userId && options.ignoreUserId && payload.userId === options.ignoreUserId || actorType === "ai_agent" && payload.aiAgentId && options.ignoreAiAgentId && payload.aiAgentId === options.ignoreAiAgentId) return;
|
|
@@ -126,12 +126,12 @@ function clearTypingFromTimelineItem(store, event) {
|
|
|
126
126
|
if (item.userId) {
|
|
127
127
|
actorType = "user";
|
|
128
128
|
actorId = item.userId;
|
|
129
|
-
} else if (item.visitorId) {
|
|
130
|
-
actorType = "visitor";
|
|
131
|
-
actorId = item.visitorId;
|
|
132
129
|
} else if (item.aiAgentId) {
|
|
133
130
|
actorType = "ai_agent";
|
|
134
131
|
actorId = item.aiAgentId;
|
|
132
|
+
} else if (item.visitorId) {
|
|
133
|
+
actorType = "visitor";
|
|
134
|
+
actorId = item.visitorId;
|
|
135
135
|
}
|
|
136
136
|
if (!(actorType && actorId)) return;
|
|
137
137
|
clearTypingState(store, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"typing-store.js","names":["entry: TypingEntry","nextConversation: ConversationTypingState","actorType: TypingActorType | null","actorId: string | null"],"sources":["../../src/store/typing-store.ts"],"sourcesContent":["import type { RealtimeEvent } from \"@cossistant/types/realtime-events\";\nimport { createStore, type Store } from \"./create-store\";\n\nexport type TypingActorType = \"visitor\" | \"user\" | \"ai_agent\";\n\nexport type TypingEntry = {\n\tactorType: TypingActorType;\n\tactorId: string;\n\tpreview: string | null;\n\tupdatedAt: number;\n};\n\nexport type ConversationTypingState = Record<string, TypingEntry>;\n\nexport type TypingState = {\n\tconversations: Record<string, ConversationTypingState>;\n};\n\nconst DEFAULT_TTL_MS = 6000;\n\nexport type TypingStoreDependencies = {\n\tnow?: () => number;\n\tsetTimeout?: (callback: () => void, delay: number) => unknown;\n\tclearTimeout?: (id: unknown) => void;\n\tdefaultTtlMs?: number;\n};\n\ntype TypingOptions = {\n\tconversationId: string;\n\tactorType: TypingActorType;\n\tactorId: string;\n};\n\ntype SetTypingOptions = TypingOptions & {\n\tisTyping: boolean;\n\tpreview?: string | null;\n\tttlMs?: number;\n};\n\nfunction makeKey(\n\tconversationId: string,\n\tactorType: TypingActorType,\n\tactorId: string\n): string {\n\treturn `${conversationId}:${actorType}:${actorId}`;\n}\n\nfunction removeEntry(\n\tstate: TypingState,\n\tconversationId: string,\n\tkey: string\n): TypingState {\n\tconst existingConversation = state.conversations[conversationId];\n\tif (!(existingConversation && key in existingConversation)) {\n\t\treturn state;\n\t}\n\n\tconst { [key]: _removed, ...rest } = existingConversation;\n\tif (Object.keys(rest).length === 0) {\n\t\tconst nextConversations = { ...state.conversations };\n\t\tdelete nextConversations[conversationId];\n\t\treturn { conversations: nextConversations } satisfies TypingState;\n\t}\n\n\treturn {\n\t\tconversations: {\n\t\t\t...state.conversations,\n\t\t\t[conversationId]: rest,\n\t\t},\n\t} satisfies TypingState;\n}\n\nexport type TypingStore = Store<TypingState> & {\n\tsetTyping(options: SetTypingOptions): void;\n\tremoveTyping(options: TypingOptions): void;\n\tclearConversation(conversationId: string): void;\n};\n\nexport function createTypingStore(\n\tinitialState: TypingState = { conversations: {} },\n\tdependencies: TypingStoreDependencies = {}\n): TypingStore {\n\tconst {\n\t\tnow = () => Date.now(),\n\t\tsetTimeout: schedule = (callback, delay) =>\n\t\t\tglobalThis.setTimeout(callback, delay),\n\t\tclearTimeout: clearScheduled = (id) =>\n\t\t\tglobalThis.clearTimeout(id as ReturnType<typeof globalThis.setTimeout>),\n\t\tdefaultTtlMs = DEFAULT_TTL_MS,\n\t} = dependencies;\n\n\tconst timers = new Map<string, unknown>();\n\tconst store = createStore<TypingState>({\n\t\tconversations: { ...initialState.conversations },\n\t});\n\n\tconst clearTimer = (key: string) => {\n\t\tconst handle = timers.get(key);\n\t\tif (!handle) {\n\t\t\treturn;\n\t\t}\n\t\ttimers.delete(key);\n\t\tclearScheduled(handle);\n\t};\n\n\tconst scheduleRemoval = (\n\t\tkey: string,\n\t\toptions: TypingOptions,\n\t\tttl: number\n\t) => {\n\t\tclearTimer(key);\n\t\tconst handle = schedule(() => {\n\t\t\ttimers.delete(key);\n\t\t\tstore.setState((state) =>\n\t\t\t\tremoveEntry(state, options.conversationId, key)\n\t\t\t);\n\t\t}, ttl);\n\t\ttimers.set(key, handle);\n\t};\n\n\treturn {\n\t\t...store,\n\t\tsetTyping({\n\t\t\tconversationId,\n\t\t\tactorType,\n\t\t\tactorId,\n\t\t\tisTyping,\n\t\t\tpreview = null,\n\t\t\tttlMs,\n\t\t}) {\n\t\t\tconst key = makeKey(conversationId, actorType, actorId);\n\n\t\t\tif (!isTyping) {\n\t\t\t\tclearTimer(key);\n\t\t\t\tstore.setState((state) => removeEntry(state, conversationId, key));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst entry: TypingEntry = {\n\t\t\t\tactorType,\n\t\t\t\tactorId,\n\t\t\t\tpreview: preview ?? null,\n\t\t\t\tupdatedAt: now(),\n\t\t\t};\n\n\t\t\tstore.setState((state) => {\n\t\t\t\tconst existingConversation = state.conversations[conversationId];\n\n\t\t\t\tconst nextConversation: ConversationTypingState = {\n\t\t\t\t\t...(existingConversation ? { ...existingConversation } : {}),\n\t\t\t\t\t[key]: entry,\n\t\t\t\t};\n\n\t\t\t\treturn {\n\t\t\t\t\tconversations: {\n\t\t\t\t\t\t...state.conversations,\n\t\t\t\t\t\t[conversationId]: nextConversation,\n\t\t\t\t\t},\n\t\t\t\t} satisfies TypingState;\n\t\t\t});\n\n\t\t\tconst timeoutMs = ttlMs ?? defaultTtlMs;\n\t\t\tscheduleRemoval(key, { conversationId, actorType, actorId }, timeoutMs);\n\t\t},\n\t\tremoveTyping({ conversationId, actorType, actorId }) {\n\t\t\tconst key = makeKey(conversationId, actorType, actorId);\n\t\t\tclearTimer(key);\n\t\t\tstore.setState((state) => removeEntry(state, conversationId, key));\n\t\t},\n\t\tclearConversation(conversationId) {\n\t\t\tconst conversation = store.getState().conversations[conversationId];\n\t\t\tif (!conversation) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfor (const key of Object.keys(conversation)) {\n\t\t\t\tclearTimer(key);\n\t\t\t}\n\n\t\t\tstore.setState((state) => {\n\t\t\t\tif (!(conversationId in state.conversations)) {\n\t\t\t\t\treturn state;\n\t\t\t\t}\n\n\t\t\t\tconst nextConversations = { ...state.conversations };\n\t\t\t\tdelete nextConversations[conversationId];\n\t\t\t\treturn { conversations: nextConversations } satisfies TypingState;\n\t\t\t});\n\t\t},\n\t} satisfies TypingStore;\n}\n\nexport function setTypingState(\n\tstore: TypingStore,\n\toptions: SetTypingOptions\n): void {\n\tstore.setTyping(options);\n}\n\nexport function clearTypingState(\n\tstore: TypingStore,\n\toptions: TypingOptions\n): void {\n\tstore.removeTyping(options);\n}\n\nexport function applyConversationTypingEvent(\n\tstore: TypingStore,\n\tevent: RealtimeEvent<\"conversationTyping\">,\n\toptions: {\n\t\tignoreVisitorId?: string | null;\n\t\tignoreUserId?: string | null;\n\t\tignoreAiAgentId?: string | null;\n\t\tttlMs?: number;\n\t} = {}\n): void {\n\tconst { payload } = event;\n\tlet actorType: TypingActorType | null = null;\n\tlet actorId: string | null = null;\n\n\tif (payload.userId) {\n\t\tactorType = \"user\";\n\t\tactorId = payload.userId;\n\t} else if (payload.visitorId) {\n\t\tactorType = \"visitor\";\n\t\tactorId = payload.visitorId;\n\t} else if (payload.aiAgentId) {\n\t\tactorType = \"ai_agent\";\n\t\tactorId = payload.aiAgentId;\n\t}\n\n\tif (!(actorType && actorId)) {\n\t\treturn;\n\t}\n\n\tif (\n\t\t(actorType === \"visitor\" &&\n\t\t\tpayload.visitorId &&\n\t\t\toptions.ignoreVisitorId &&\n\t\t\tpayload.visitorId === options.ignoreVisitorId) ||\n\t\t(actorType === \"user\" &&\n\t\t\tpayload.userId &&\n\t\t\toptions.ignoreUserId &&\n\t\t\tpayload.userId === options.ignoreUserId) ||\n\t\t(actorType === \"ai_agent\" &&\n\t\t\tpayload.aiAgentId &&\n\t\t\toptions.ignoreAiAgentId &&\n\t\t\tpayload.aiAgentId === options.ignoreAiAgentId)\n\t) {\n\t\treturn;\n\t}\n\n\tconst preview =\n\t\tactorType === \"visitor\" ? (payload.visitorPreview ?? null) : null;\n\n\tsetTypingState(store, {\n\t\tconversationId: payload.conversationId,\n\t\tactorType,\n\t\tactorId,\n\t\tisTyping: payload.isTyping,\n\t\tpreview,\n\t\tttlMs: options.ttlMs,\n\t});\n}\n\nexport function clearTypingFromTimelineItem(\n\tstore: TypingStore,\n\tevent: RealtimeEvent<\"timelineItemCreated\">\n): void {\n\tconst { item } = event.payload;\n\tlet actorType: TypingActorType | null = null;\n\tlet actorId: string | null = null;\n\n\tif (item.userId) {\n\t\tactorType = \"user\";\n\t\tactorId = item.userId;\n\t} else if (item.visitorId) {\n\t\tactorType = \"visitor\";\n\t\tactorId = item.visitorId;\n\t} else if (item.aiAgentId) {\n\t\tactorType = \"ai_agent\";\n\t\tactorId = item.aiAgentId;\n\t}\n\n\tif (!(actorType && actorId)) {\n\t\treturn;\n\t}\n\n\tclearTypingState(store, {\n\t\tconversationId: item.conversationId,\n\t\tactorType,\n\t\tactorId,\n\t});\n}\n\nexport function getConversationTyping(\n\tstore: Store<TypingState>,\n\tconversationId: string\n): ConversationTypingState | undefined {\n\treturn store.getState().conversations[conversationId];\n}\n"],"mappings":";;;AAkBA,MAAM,iBAAiB;AAqBvB,SAAS,QACR,gBACA,WACA,SACS;AACT,QAAO,GAAG,eAAe,GAAG,UAAU,GAAG;;AAG1C,SAAS,YACR,OACA,gBACA,KACc;CACd,MAAM,uBAAuB,MAAM,cAAc;AACjD,KAAI,EAAE,wBAAwB,OAAO,sBACpC,QAAO;CAGR,MAAM,GAAG,MAAM,SAAU,GAAG,SAAS;AACrC,KAAI,OAAO,KAAK,KAAK,CAAC,WAAW,GAAG;EACnC,MAAM,oBAAoB,EAAE,GAAG,MAAM,eAAe;AACpD,SAAO,kBAAkB;AACzB,SAAO,EAAE,eAAe,mBAAmB;;AAG5C,QAAO,EACN,eAAe;EACd,GAAG,MAAM;GACR,iBAAiB;EAClB,EACD;;AASF,SAAgB,kBACf,eAA4B,EAAE,eAAe,EAAE,EAAE,EACjD,eAAwC,EAAE,EAC5B;CACd,MAAM,EACL,YAAY,KAAK,KAAK,EACtB,YAAY,YAAY,UAAU,UACjC,WAAW,WAAW,UAAU,MAAM,EACvC,cAAc,kBAAkB,OAC/B,WAAW,aAAa,GAA+C,E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AAK;YACL,KAAK,WAAW;AAC1B,cAAY;AACZ,YAAU,KAAK;YACL,KAAK,WAAW;AAC1B,cAAY;AACZ,YAAU,KAAK;;AAGhB,KAAI,EAAE,aAAa,SAClB;AAGD,kBAAiB,OAAO;EACvB,gBAAgB,KAAK;EACrB;EACA;EACA,CAAC;;AAGH,SAAgB,sBACf,OACA,gBACsC;AACtC,QAAO,MAAM,UAAU,CAAC,cAAc"}
|
|
1
|
+
{"version":3,"file":"typing-store.js","names":["entry: TypingEntry","nextConversation: ConversationTypingState","actorType: TypingActorType | null","actorId: string | null"],"sources":["../../src/store/typing-store.ts"],"sourcesContent":["import type { RealtimeEvent } from \"@cossistant/types/realtime-events\";\nimport { createStore, type Store } from \"./create-store\";\n\nexport type TypingActorType = \"visitor\" | \"user\" | \"ai_agent\";\n\nexport type TypingEntry = {\n\tactorType: TypingActorType;\n\tactorId: string;\n\tpreview: string | null;\n\tupdatedAt: number;\n};\n\nexport type ConversationTypingState = Record<string, TypingEntry>;\n\nexport type TypingState = {\n\tconversations: Record<string, ConversationTypingState>;\n};\n\nconst DEFAULT_TTL_MS = 6000;\n\nexport type TypingStoreDependencies = {\n\tnow?: () => number;\n\tsetTimeout?: (callback: () => void, delay: number) => unknown;\n\tclearTimeout?: (id: unknown) => void;\n\tdefaultTtlMs?: number;\n};\n\ntype TypingOptions = {\n\tconversationId: string;\n\tactorType: TypingActorType;\n\tactorId: string;\n};\n\ntype SetTypingOptions = TypingOptions & {\n\tisTyping: boolean;\n\tpreview?: string | null;\n\tttlMs?: number;\n};\n\nfunction makeKey(\n\tconversationId: string,\n\tactorType: TypingActorType,\n\tactorId: string\n): string {\n\treturn `${conversationId}:${actorType}:${actorId}`;\n}\n\nfunction removeEntry(\n\tstate: TypingState,\n\tconversationId: string,\n\tkey: string\n): TypingState {\n\tconst existingConversation = state.conversations[conversationId];\n\tif (!(existingConversation && key in existingConversation)) {\n\t\treturn state;\n\t}\n\n\tconst { [key]: _removed, ...rest } = existingConversation;\n\tif (Object.keys(rest).length === 0) {\n\t\tconst nextConversations = { ...state.conversations };\n\t\tdelete nextConversations[conversationId];\n\t\treturn { conversations: nextConversations } satisfies TypingState;\n\t}\n\n\treturn {\n\t\tconversations: {\n\t\t\t...state.conversations,\n\t\t\t[conversationId]: rest,\n\t\t},\n\t} satisfies TypingState;\n}\n\nexport type TypingStore = Store<TypingState> & {\n\tsetTyping(options: SetTypingOptions): void;\n\tremoveTyping(options: TypingOptions): void;\n\tclearConversation(conversationId: string): void;\n};\n\nexport function createTypingStore(\n\tinitialState: TypingState = { conversations: {} },\n\tdependencies: TypingStoreDependencies = {}\n): TypingStore {\n\tconst {\n\t\tnow = () => Date.now(),\n\t\tsetTimeout: schedule = (callback, delay) =>\n\t\t\tglobalThis.setTimeout(callback, delay),\n\t\tclearTimeout: clearScheduled = (id) =>\n\t\t\tglobalThis.clearTimeout(id as ReturnType<typeof globalThis.setTimeout>),\n\t\tdefaultTtlMs = DEFAULT_TTL_MS,\n\t} = dependencies;\n\n\tconst timers = new Map<string, unknown>();\n\tconst store = createStore<TypingState>({\n\t\tconversations: { ...initialState.conversations },\n\t});\n\n\tconst clearTimer = (key: string) => {\n\t\tconst handle = timers.get(key);\n\t\tif (!handle) {\n\t\t\treturn;\n\t\t}\n\t\ttimers.delete(key);\n\t\tclearScheduled(handle);\n\t};\n\n\tconst scheduleRemoval = (\n\t\tkey: string,\n\t\toptions: TypingOptions,\n\t\tttl: number\n\t) => {\n\t\tclearTimer(key);\n\t\tconst handle = schedule(() => {\n\t\t\ttimers.delete(key);\n\t\t\tstore.setState((state) =>\n\t\t\t\tremoveEntry(state, options.conversationId, key)\n\t\t\t);\n\t\t}, ttl);\n\t\ttimers.set(key, handle);\n\t};\n\n\treturn {\n\t\t...store,\n\t\tsetTyping({\n\t\t\tconversationId,\n\t\t\tactorType,\n\t\t\tactorId,\n\t\t\tisTyping,\n\t\t\tpreview = null,\n\t\t\tttlMs,\n\t\t}) {\n\t\t\tconst key = makeKey(conversationId, actorType, actorId);\n\n\t\t\tif (!isTyping) {\n\t\t\t\tclearTimer(key);\n\t\t\t\tstore.setState((state) => removeEntry(state, conversationId, key));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst entry: TypingEntry = {\n\t\t\t\tactorType,\n\t\t\t\tactorId,\n\t\t\t\tpreview: preview ?? null,\n\t\t\t\tupdatedAt: now(),\n\t\t\t};\n\n\t\t\tstore.setState((state) => {\n\t\t\t\tconst existingConversation = state.conversations[conversationId];\n\n\t\t\t\tconst nextConversation: ConversationTypingState = {\n\t\t\t\t\t...(existingConversation ? { ...existingConversation } : {}),\n\t\t\t\t\t[key]: entry,\n\t\t\t\t};\n\n\t\t\t\treturn {\n\t\t\t\t\tconversations: {\n\t\t\t\t\t\t...state.conversations,\n\t\t\t\t\t\t[conversationId]: nextConversation,\n\t\t\t\t\t},\n\t\t\t\t} satisfies TypingState;\n\t\t\t});\n\n\t\t\tconst timeoutMs = ttlMs ?? defaultTtlMs;\n\t\t\tscheduleRemoval(key, { conversationId, actorType, actorId }, timeoutMs);\n\t\t},\n\t\tremoveTyping({ conversationId, actorType, actorId }) {\n\t\t\tconst key = makeKey(conversationId, actorType, actorId);\n\t\t\tclearTimer(key);\n\t\t\tstore.setState((state) => removeEntry(state, conversationId, key));\n\t\t},\n\t\tclearConversation(conversationId) {\n\t\t\tconst conversation = store.getState().conversations[conversationId];\n\t\t\tif (!conversation) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfor (const key of Object.keys(conversation)) {\n\t\t\t\tclearTimer(key);\n\t\t\t}\n\n\t\t\tstore.setState((state) => {\n\t\t\t\tif (!(conversationId in state.conversations)) {\n\t\t\t\t\treturn state;\n\t\t\t\t}\n\n\t\t\t\tconst nextConversations = { ...state.conversations };\n\t\t\t\tdelete nextConversations[conversationId];\n\t\t\t\treturn { conversations: nextConversations } satisfies TypingState;\n\t\t\t});\n\t\t},\n\t} satisfies TypingStore;\n}\n\nexport function setTypingState(\n\tstore: TypingStore,\n\toptions: SetTypingOptions\n): void {\n\tstore.setTyping(options);\n}\n\nexport function clearTypingState(\n\tstore: TypingStore,\n\toptions: TypingOptions\n): void {\n\tstore.removeTyping(options);\n}\n\nexport function applyConversationTypingEvent(\n\tstore: TypingStore,\n\tevent: RealtimeEvent<\"conversationTyping\">,\n\toptions: {\n\t\tignoreVisitorId?: string | null;\n\t\tignoreUserId?: string | null;\n\t\tignoreAiAgentId?: string | null;\n\t\tttlMs?: number;\n\t} = {}\n): void {\n\tconst { payload } = event;\n\tlet actorType: TypingActorType | null = null;\n\tlet actorId: string | null = null;\n\n\t// IMPORTANT: Check aiAgentId BEFORE visitorId because the event payload\n\t// always includes visitorId (for routing purposes), even for AI agent typing.\n\t// The presence of aiAgentId specifically identifies AI agent typing.\n\tif (payload.userId) {\n\t\tactorType = \"user\";\n\t\tactorId = payload.userId;\n\t} else if (payload.aiAgentId) {\n\t\tactorType = \"ai_agent\";\n\t\tactorId = payload.aiAgentId;\n\t} else if (payload.visitorId) {\n\t\tactorType = \"visitor\";\n\t\tactorId = payload.visitorId;\n\t}\n\n\tif (!(actorType && actorId)) {\n\t\treturn;\n\t}\n\n\tif (\n\t\t(actorType === \"visitor\" &&\n\t\t\tpayload.visitorId &&\n\t\t\toptions.ignoreVisitorId &&\n\t\t\tpayload.visitorId === options.ignoreVisitorId) ||\n\t\t(actorType === \"user\" &&\n\t\t\tpayload.userId &&\n\t\t\toptions.ignoreUserId &&\n\t\t\tpayload.userId === options.ignoreUserId) ||\n\t\t(actorType === \"ai_agent\" &&\n\t\t\tpayload.aiAgentId &&\n\t\t\toptions.ignoreAiAgentId &&\n\t\t\tpayload.aiAgentId === options.ignoreAiAgentId)\n\t) {\n\t\treturn;\n\t}\n\n\tconst preview =\n\t\tactorType === \"visitor\" ? (payload.visitorPreview ?? null) : null;\n\n\tsetTypingState(store, {\n\t\tconversationId: payload.conversationId,\n\t\tactorType,\n\t\tactorId,\n\t\tisTyping: payload.isTyping,\n\t\tpreview,\n\t\tttlMs: options.ttlMs,\n\t});\n}\n\nexport function clearTypingFromTimelineItem(\n\tstore: TypingStore,\n\tevent: RealtimeEvent<\"timelineItemCreated\">\n): void {\n\tconst { item } = event.payload;\n\tlet actorType: TypingActorType | null = null;\n\tlet actorId: string | null = null;\n\n\t// Check aiAgentId before visitorId for consistency with applyConversationTypingEvent\n\tif (item.userId) {\n\t\tactorType = \"user\";\n\t\tactorId = item.userId;\n\t} else if (item.aiAgentId) {\n\t\tactorType = \"ai_agent\";\n\t\tactorId = item.aiAgentId;\n\t} else if (item.visitorId) {\n\t\tactorType = \"visitor\";\n\t\tactorId = item.visitorId;\n\t}\n\n\tif (!(actorType && actorId)) {\n\t\treturn;\n\t}\n\n\tclearTypingState(store, {\n\t\tconversationId: item.conversationId,\n\t\tactorType,\n\t\tactorId,\n\t});\n}\n\nexport function getConversationTyping(\n\tstore: Store<TypingState>,\n\tconversationId: string\n): ConversationTypingState | undefined {\n\treturn store.getState().conversations[conversationId];\n}\n"],"mappings":";;;AAkBA,MAAM,iBAAiB;AAqBvB,SAAS,QACR,gBACA,WACA,SACS;AACT,QAAO,GAAG,eAAe,GAAG,UAAU,GAAG;;AAG1C,SAAS,YACR,OACA,gBACA,KACc;CACd,MAAM,uBAAuB,MAAM,cAAc;AACjD,KAAI,EAAE,wBAAwB,OAAO,sBACpC,QAAO;CAGR,MAAM,GAAG,MAAM,SAAU,GAAG,SAAS;AACrC,KAAI,OAAO,KAAK,KAAK,CAAC,WAAW,GAAG;EACnC,MAAM,oBAAoB,EAAE,GAAG,MAAM,eAAe;AACpD,SAAO,kBAAkB;AACzB,SAAO,EAAE,eAAe,mBAAmB;;AAG5C,QAAO,EACN,eAAe;EACd,GAAG,MAAM;GACR,iBAAiB;EAClB,EACD;;AASF,SAAgB,kBACf,eAA4B,EAAE,eAAe,EAAE,EAAE,EACjD,eAAwC,EAAE,EAC5B;CACd,MAAM,EACL,YAAY,KAAK,KAAK,EACtB,YAAY,YAAY,UAAU,UACjC,WAAW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,IAAIC,UAAyB;AAG7B,KAAI,KAAK,QAAQ;AAChB,cAAY;AACZ,YAAU,KAAK;YACL,KAAK,WAAW;AAC1B,cAAY;AACZ,YAAU,KAAK;YACL,KAAK,WAAW;AAC1B,cAAY;AACZ,YAAU,KAAK;;AAGhB,KAAI,EAAE,aAAa,SAClB;AAGD,kBAAiB,OAAO;EACvB,gBAAgB,KAAK;EACrB;EACA;EACA,CAAC;;AAGH,SAAgB,sBACf,OACA,gBACsC;AACtC,QAAO,MAAM,UAAU,CAAC,cAAc"}
|
package/types/src/enums.js
CHANGED
|
@@ -32,7 +32,10 @@ const ConversationEventType = {
|
|
|
32
32
|
REOPENED: "reopened",
|
|
33
33
|
VISITOR_BLOCKED: "visitor_blocked",
|
|
34
34
|
VISITOR_UNBLOCKED: "visitor_unblocked",
|
|
35
|
-
VISITOR_IDENTIFIED: "visitor_identified"
|
|
35
|
+
VISITOR_IDENTIFIED: "visitor_identified",
|
|
36
|
+
AI_ANALYZED: "ai_analyzed",
|
|
37
|
+
TITLE_GENERATED: "title_generated",
|
|
38
|
+
AI_ESCALATED: "ai_escalated"
|
|
36
39
|
};
|
|
37
40
|
|
|
38
41
|
//#endregion
|
package/types/src/enums.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enums.js","names":[],"sources":["../../../../types/src/enums.ts"],"sourcesContent":["export const SenderType = {\n\tVISITOR: \"visitor\",\n\tTEAM_MEMBER: \"team_member\",\n\tAI: \"ai\",\n} as const;\n\nexport type SenderType = (typeof SenderType)[keyof typeof SenderType];\n\nexport const ConversationStatus = {\n\tOPEN: \"open\",\n\tRESOLVED: \"resolved\",\n\tSPAM: \"spam\",\n} as const;\n\nexport type ConversationStatus =\n\t(typeof ConversationStatus)[keyof typeof ConversationStatus];\n\nexport const ConversationPriority = {\n\tLOW: \"low\",\n\tNORMAL: \"normal\",\n\tHIGH: \"high\",\n\tURGENT: \"urgent\",\n} as const;\n\nexport const TimelineItemVisibility = {\n\tPUBLIC: \"public\",\n\tPRIVATE: \"private\",\n} as const;\n\nexport const ConversationTimelineType = {\n\tMESSAGE: \"message\",\n\tEVENT: \"event\",\n\tIDENTIFICATION: \"identification\",\n} as const;\n\nexport type ConversationTimelineType =\n\t(typeof ConversationTimelineType)[keyof typeof ConversationTimelineType];\n\nexport const ConversationEventType = {\n\tASSIGNED: \"assigned\",\n\tUNASSIGNED: \"unassigned\",\n\tPARTICIPANT_REQUESTED: \"participant_requested\",\n\tPARTICIPANT_JOINED: \"participant_joined\",\n\tPARTICIPANT_LEFT: \"participant_left\",\n\tSTATUS_CHANGED: \"status_changed\",\n\tPRIORITY_CHANGED: \"priority_changed\",\n\tTAG_ADDED: \"tag_added\",\n\tTAG_REMOVED: \"tag_removed\",\n\tRESOLVED: \"resolved\",\n\tREOPENED: \"reopened\",\n\tVISITOR_BLOCKED: \"visitor_blocked\",\n\tVISITOR_UNBLOCKED: \"visitor_unblocked\",\n\tVISITOR_IDENTIFIED: \"visitor_identified\",\n} as const;\n\nexport const ConversationParticipationStatus = {\n\tREQUESTED: \"requested\",\n\tACTIVE: \"active\",\n\tLEFT: \"left\",\n\tDECLINED: \"declined\",\n} as const;\n\nexport const ConversationSentiment = {\n\tPOSITIVE: \"positive\",\n\tNEGATIVE: \"negative\",\n\tNEUTRAL: \"neutral\",\n} as const;\n\nexport type ConversationSentiment =\n\t(typeof ConversationSentiment)[keyof typeof ConversationSentiment];\n\nexport type ConversationParticipationStatus =\n\t(typeof ConversationParticipationStatus)[keyof typeof ConversationParticipationStatus];\n\nexport type ConversationEventType =\n\t(typeof ConversationEventType)[keyof typeof ConversationEventType];\n\nexport type TimelineItemVisibility =\n\t(typeof TimelineItemVisibility)[keyof typeof TimelineItemVisibility];\n\nexport type ConversationPriority =\n\t(typeof ConversationPriority)[keyof typeof ConversationPriority];\n\nexport const WebsiteInstallationTarget = {\n\tNEXTJS: \"nextjs\",\n\tREACT: \"react\",\n} as const;\n\nexport const WebsiteStatus = {\n\tACTIVE: \"active\",\n\tINACTIVE: \"inactive\",\n} as const;\n\nexport type WebsiteStatus = (typeof WebsiteStatus)[keyof typeof WebsiteStatus];\n\nexport type WebsiteInstallationTarget =\n\t(typeof WebsiteInstallationTarget)[keyof typeof WebsiteInstallationTarget];\n\nexport const APIKeyType = {\n\tPRIVATE: \"private\",\n\tPUBLIC: \"public\",\n} as const;\n\nexport type APIKeyType = (typeof APIKeyType)[keyof typeof APIKeyType];\n"],"mappings":";AAAA,MAAa,aAAa;CACzB,SAAS;CACT,aAAa;CACb,IAAI;CACJ;AAID,MAAa,qBAAqB;CACjC,MAAM;CACN,UAAU;CACV,MAAM;CACN;AAYD,MAAa,yBAAyB;CACrC,QAAQ;CACR,SAAS;CACT;AAED,MAAa,2BAA2B;CACvC,SAAS;CACT,OAAO;CACP,gBAAgB;CAChB;AAKD,MAAa,wBAAwB;CACpC,UAAU;CACV,YAAY;CACZ,uBAAuB;CACvB,oBAAoB;CACpB,kBAAkB;CAClB,gBAAgB;CAChB,kBAAkB;CAClB,WAAW;CACX,aAAa;CACb,UAAU;CACV,UAAU;CACV,iBAAiB;CACjB,mBAAmB;CACnB,oBAAoB;
|
|
1
|
+
{"version":3,"file":"enums.js","names":[],"sources":["../../../../types/src/enums.ts"],"sourcesContent":["export const SenderType = {\n\tVISITOR: \"visitor\",\n\tTEAM_MEMBER: \"team_member\",\n\tAI: \"ai\",\n} as const;\n\nexport type SenderType = (typeof SenderType)[keyof typeof SenderType];\n\nexport const ConversationStatus = {\n\tOPEN: \"open\",\n\tRESOLVED: \"resolved\",\n\tSPAM: \"spam\",\n} as const;\n\nexport type ConversationStatus =\n\t(typeof ConversationStatus)[keyof typeof ConversationStatus];\n\nexport const ConversationPriority = {\n\tLOW: \"low\",\n\tNORMAL: \"normal\",\n\tHIGH: \"high\",\n\tURGENT: \"urgent\",\n} as const;\n\nexport const TimelineItemVisibility = {\n\tPUBLIC: \"public\",\n\tPRIVATE: \"private\",\n} as const;\n\nexport const ConversationTimelineType = {\n\tMESSAGE: \"message\",\n\tEVENT: \"event\",\n\tIDENTIFICATION: \"identification\",\n} as const;\n\nexport type ConversationTimelineType =\n\t(typeof ConversationTimelineType)[keyof typeof ConversationTimelineType];\n\nexport const ConversationEventType = {\n\tASSIGNED: \"assigned\",\n\tUNASSIGNED: \"unassigned\",\n\tPARTICIPANT_REQUESTED: \"participant_requested\",\n\tPARTICIPANT_JOINED: \"participant_joined\",\n\tPARTICIPANT_LEFT: \"participant_left\",\n\tSTATUS_CHANGED: \"status_changed\",\n\tPRIORITY_CHANGED: \"priority_changed\",\n\tTAG_ADDED: \"tag_added\",\n\tTAG_REMOVED: \"tag_removed\",\n\tRESOLVED: \"resolved\",\n\tREOPENED: \"reopened\",\n\tVISITOR_BLOCKED: \"visitor_blocked\",\n\tVISITOR_UNBLOCKED: \"visitor_unblocked\",\n\tVISITOR_IDENTIFIED: \"visitor_identified\",\n\t// Private AI events (team only, not visible to visitors)\n\tAI_ANALYZED: \"ai_analyzed\",\n\tTITLE_GENERATED: \"title_generated\",\n\tAI_ESCALATED: \"ai_escalated\",\n} as const;\n\nexport const ConversationParticipationStatus = {\n\tREQUESTED: \"requested\",\n\tACTIVE: \"active\",\n\tLEFT: \"left\",\n\tDECLINED: \"declined\",\n} as const;\n\nexport const ConversationSentiment = {\n\tPOSITIVE: \"positive\",\n\tNEGATIVE: \"negative\",\n\tNEUTRAL: \"neutral\",\n} as const;\n\nexport type ConversationSentiment =\n\t(typeof ConversationSentiment)[keyof typeof ConversationSentiment];\n\nexport type ConversationParticipationStatus =\n\t(typeof ConversationParticipationStatus)[keyof typeof ConversationParticipationStatus];\n\nexport type ConversationEventType =\n\t(typeof ConversationEventType)[keyof typeof ConversationEventType];\n\nexport type TimelineItemVisibility =\n\t(typeof TimelineItemVisibility)[keyof typeof TimelineItemVisibility];\n\nexport type ConversationPriority =\n\t(typeof ConversationPriority)[keyof typeof ConversationPriority];\n\nexport const WebsiteInstallationTarget = {\n\tNEXTJS: \"nextjs\",\n\tREACT: \"react\",\n} as const;\n\nexport const WebsiteStatus = {\n\tACTIVE: \"active\",\n\tINACTIVE: \"inactive\",\n} as const;\n\nexport type WebsiteStatus = (typeof WebsiteStatus)[keyof typeof WebsiteStatus];\n\nexport type WebsiteInstallationTarget =\n\t(typeof WebsiteInstallationTarget)[keyof typeof WebsiteInstallationTarget];\n\nexport const APIKeyType = {\n\tPRIVATE: \"private\",\n\tPUBLIC: \"public\",\n} as const;\n\nexport type APIKeyType = (typeof APIKeyType)[keyof typeof APIKeyType];\n"],"mappings":";AAAA,MAAa,aAAa;CACzB,SAAS;CACT,aAAa;CACb,IAAI;CACJ;AAID,MAAa,qBAAqB;CACjC,MAAM;CACN,UAAU;CACV,MAAM;CACN;AAYD,MAAa,yBAAyB;CACrC,QAAQ;CACR,SAAS;CACT;AAED,MAAa,2BAA2B;CACvC,SAAS;CACT,OAAO;CACP,gBAAgB;CAChB;AAKD,MAAa,wBAAwB;CACpC,UAAU;CACV,YAAY;CACZ,uBAAuB;CACvB,oBAAoB;CACpB,kBAAkB;CAClB,gBAAgB;CAChB,kBAAkB;CAClB,WAAW;CACX,aAAa;CACb,UAAU;CACV,UAAU;CACV,iBAAiB;CACjB,mBAAmB;CACnB,oBAAoB;CAEpB,aAAa;CACb,iBAAiB;CACjB,cAAc;CACd"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
//#region src/typing-reporter.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Shared typing reporter logic for throttling and scheduling typing events.
|
|
4
|
+
* This is a framework-agnostic utility used by both React widget and dashboard hooks.
|
|
5
|
+
*/
|
|
6
|
+
/** Minimum interval between typing event sends (ms) */
|
|
7
|
+
declare const TYPING_SEND_INTERVAL_MS = 800;
|
|
8
|
+
/** Keep-alive interval for typing events (ms) */
|
|
9
|
+
declare const TYPING_KEEP_ALIVE_MS = 4000;
|
|
10
|
+
/** Delay before auto-stop typing on inactivity (ms) */
|
|
11
|
+
declare const TYPING_STOP_DELAY_MS = 2000;
|
|
12
|
+
/** Maximum length for typing preview text */
|
|
13
|
+
declare const TYPING_PREVIEW_MAX_LENGTH = 2000;
|
|
14
|
+
type TypingReporterState = {
|
|
15
|
+
isActive: boolean;
|
|
16
|
+
lastSentAt: number;
|
|
17
|
+
latestPreview: string;
|
|
18
|
+
};
|
|
19
|
+
type TypingReporterSendFn = (isTyping: boolean, preview?: string | null) => void | Promise<void>;
|
|
20
|
+
type TypingReporterConfig = {
|
|
21
|
+
/** Function to send the typing event */
|
|
22
|
+
send: TypingReporterSendFn;
|
|
23
|
+
/** Custom send interval (default: 800ms) */
|
|
24
|
+
sendIntervalMs?: number;
|
|
25
|
+
/** Custom keep-alive interval (default: 4000ms) */
|
|
26
|
+
keepAliveMs?: number;
|
|
27
|
+
/** Custom stop delay (default: 2000ms) */
|
|
28
|
+
stopDelayMs?: number;
|
|
29
|
+
/** Maximum preview length (default: 2000) */
|
|
30
|
+
previewMaxLength?: number;
|
|
31
|
+
/** Whether to include preview text (default: true) */
|
|
32
|
+
includePreview?: boolean;
|
|
33
|
+
};
|
|
34
|
+
type TypingReporter = {
|
|
35
|
+
/** Call when input value changes */
|
|
36
|
+
handleInputChange: (value: string) => void;
|
|
37
|
+
/** Call when message is submitted */
|
|
38
|
+
handleSubmit: () => void;
|
|
39
|
+
/** Force stop typing indicator */
|
|
40
|
+
stop: () => void;
|
|
41
|
+
/** Clean up timers (call on unmount) */
|
|
42
|
+
dispose: () => void;
|
|
43
|
+
/** Get current state (for testing) */
|
|
44
|
+
getState: () => TypingReporterState;
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* Creates a typing reporter instance that handles throttling and scheduling
|
|
48
|
+
* of typing events.
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* ```ts
|
|
52
|
+
* const reporter = createTypingReporter({
|
|
53
|
+
* send: async (isTyping, preview) => {
|
|
54
|
+
* await api.sendTypingEvent({ isTyping, preview });
|
|
55
|
+
* },
|
|
56
|
+
* });
|
|
57
|
+
*
|
|
58
|
+
* // On input change
|
|
59
|
+
* reporter.handleInputChange(inputValue);
|
|
60
|
+
*
|
|
61
|
+
* // On submit
|
|
62
|
+
* reporter.handleSubmit();
|
|
63
|
+
*
|
|
64
|
+
* // On unmount
|
|
65
|
+
* reporter.dispose();
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
declare function createTypingReporter(config: TypingReporterConfig): TypingReporter;
|
|
69
|
+
//#endregion
|
|
70
|
+
export { TYPING_KEEP_ALIVE_MS, TYPING_PREVIEW_MAX_LENGTH, TYPING_SEND_INTERVAL_MS, TYPING_STOP_DELAY_MS, TypingReporter, TypingReporterConfig, createTypingReporter };
|
|
71
|
+
//# sourceMappingURL=typing-reporter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"typing-reporter.d.ts","names":[],"sources":["../src/typing-reporter.ts"],"sourcesContent":[],"mappings":";;AAMA;AAGA;AAGA;AAGA;AAEK,cAXQ,uBAAA,GAWW,GAAA;AAAA;AAgBZ,cAxBC,oBAAA,GA0BN,IAAA;AAaP;AAmCgB,cAvEH,oBAAA,GAwEJ,IAAA;;cArEI,yBAAA;KAER,mBAAA;;;;;KAWA,oBAAA,0DAGO;KAEA,oBAAA;;QAEL;;;;;;;;;;;;KAaK,cAAA;;;;;;;;;;kBAUK;;;;;;;;;;;;;;;;;;;;;;;;iBAyBD,oBAAA,SACP,uBACN"}
|