chat 4.4.0 → 4.4.1

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/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { C as CardElement, a as CardJSXElement, M as ModalElement, b as CardChild, A as Actions$1, B as Button$1, c as Card$1, T as Text$1, D as Divider$1, F as Field$1, d as Fields$1, f as fromReactElement$1, I as Image$1, i as isCardElement$1, e as isJSX$1, S as Section$1, t as toCardElement$1, g as toModalElement$1, h as fromReactModalElement$1, j as isModalElement$1, k as Modal$1, l as Select$1, m as SelectOption$1, n as TextInput$1 } from './jsx-runtime-CFK57xOl.js';
2
2
  export { x as ActionsElement, y as ButtonElement, z as ButtonOptions, o as ButtonProps, E as ButtonStyle, p as CardJSXProps, G as CardOptions, q as CardProps, r as ContainerProps, H as DividerElement, s as DividerProps, J as FieldElement, u as FieldProps, K as FieldsElement, L as ImageElement, v as ImageProps, Q as ModalChild, R as ModalOptions, N as SectionElement, U as SelectElement, V as SelectOptionElement, W as SelectOptions, O as TextElement, X as TextInputElement, Y as TextInputOptions, w as TextProps, P as TextStyle } from './jsx-runtime-CFK57xOl.js';
3
+ import { WORKFLOW_SERIALIZE, WORKFLOW_DESERIALIZE } from '@workflow/serde';
3
4
  import { Root, Content, Blockquote, Code, Emphasis, InlineCode, Delete, Link, ListItem, List, Paragraph, Strong, Text } from 'mdast';
4
5
  export { Blockquote, Code, Content, Delete, Emphasis, InlineCode, Link, List, ListItem, Paragraph, Root, Strong, Text } from 'mdast';
5
6
 
@@ -524,45 +525,6 @@ interface FetchResult<TRawMessage = unknown> {
524
525
  * This is the canonical representation of message formatting.
525
526
  */
526
527
  type FormattedContent = Root;
527
- interface Message<TRawMessage = unknown> {
528
- /** Unique message ID */
529
- readonly id: string;
530
- /** Thread this message belongs to */
531
- readonly threadId: string;
532
- /** Plain text content (all formatting stripped) */
533
- text: string;
534
- /**
535
- * Structured formatting as an AST (mdast Root).
536
- * This is the canonical representation - use this for processing.
537
- * Use `stringifyMarkdown(message.formatted)` to get markdown string.
538
- */
539
- formatted: FormattedContent;
540
- /** Platform-specific raw payload (escape hatch) */
541
- raw: TRawMessage;
542
- /** Message author */
543
- author: Author;
544
- /** Message metadata */
545
- metadata: MessageMetadata;
546
- /** Attachments */
547
- attachments: Attachment[];
548
- /**
549
- * Whether the bot is @-mentioned in this message.
550
- *
551
- * This is set by the Chat SDK before passing the message to handlers.
552
- * It checks for `@username` in the message text using the adapter's
553
- * configured `userName` and optional `botUserId`.
554
- *
555
- * @example
556
- * ```typescript
557
- * chat.onSubscribedMessage(async (thread, message) => {
558
- * if (message.isMention) {
559
- * await thread.post("You mentioned me!");
560
- * }
561
- * });
562
- * ```
563
- */
564
- isMention?: boolean;
565
- }
566
528
  /** Raw message returned from adapter (before wrapping as SentMessage) */
567
529
  interface RawMessage<TRawMessage = unknown> {
568
530
  id: string;
@@ -934,6 +896,7 @@ interface ModalSubmitEvent {
934
896
  interface ModalCloseEvent {
935
897
  callbackId: string;
936
898
  viewId: string;
899
+ privateMetadata?: string;
937
900
  user: Author;
938
901
  adapter: Adapter;
939
902
  raw: unknown;
@@ -957,6 +920,153 @@ type ModalResponse = ModalCloseResponse | ModalErrorsResponse | ModalUpdateRespo
957
920
  type ModalSubmitHandler = (event: ModalSubmitEvent) => Promise<ModalResponse | undefined>;
958
921
  type ModalCloseHandler = (event: ModalCloseEvent) => Promise<void>;
959
922
 
923
+ /**
924
+ * Message class with serialization support for workflow engines.
925
+ */
926
+
927
+ /**
928
+ * Input data for creating a Message instance.
929
+ * Use this interface when constructing Message objects.
930
+ */
931
+ interface MessageData<TRawMessage = unknown> {
932
+ /** Unique message ID */
933
+ id: string;
934
+ /** Thread this message belongs to */
935
+ threadId: string;
936
+ /** Plain text content (all formatting stripped) */
937
+ text: string;
938
+ /** Structured formatting as an AST (mdast Root) */
939
+ formatted: FormattedContent;
940
+ /** Platform-specific raw payload (escape hatch) */
941
+ raw: TRawMessage;
942
+ /** Message author */
943
+ author: Author;
944
+ /** Message metadata */
945
+ metadata: MessageMetadata;
946
+ /** Attachments */
947
+ attachments: Attachment[];
948
+ /** Whether the bot is @-mentioned in this message */
949
+ isMention?: boolean;
950
+ }
951
+ /**
952
+ * Serialized message data for passing to external systems (e.g., workflow engines).
953
+ * Dates are converted to ISO strings, and non-serializable fields are omitted.
954
+ */
955
+ interface SerializedMessage {
956
+ _type: "chat:Message";
957
+ id: string;
958
+ threadId: string;
959
+ text: string;
960
+ formatted: Root;
961
+ raw: unknown;
962
+ author: {
963
+ userId: string;
964
+ userName: string;
965
+ fullName: string;
966
+ isBot: boolean | "unknown";
967
+ isMe: boolean;
968
+ };
969
+ metadata: {
970
+ dateSent: string;
971
+ edited: boolean;
972
+ editedAt?: string;
973
+ };
974
+ attachments: Array<{
975
+ type: "image" | "file" | "video" | "audio";
976
+ url?: string;
977
+ name?: string;
978
+ mimeType?: string;
979
+ size?: number;
980
+ width?: number;
981
+ height?: number;
982
+ }>;
983
+ isMention?: boolean;
984
+ }
985
+ /**
986
+ * A chat message with serialization support for workflow engines.
987
+ *
988
+ * @example
989
+ * ```typescript
990
+ * // Create a message
991
+ * const message = new Message({
992
+ * id: "msg-1",
993
+ * threadId: "slack:C123:1234.5678",
994
+ * text: "Hello world",
995
+ * formatted: parseMarkdown("Hello world"),
996
+ * raw: {},
997
+ * author: { userId: "U123", userName: "user", fullName: "User", isBot: false, isMe: false },
998
+ * metadata: { dateSent: new Date(), edited: false },
999
+ * attachments: [],
1000
+ * });
1001
+ *
1002
+ * // Serialize for workflow
1003
+ * const serialized = message.toJSON();
1004
+ * ```
1005
+ */
1006
+ declare class Message<TRawMessage = unknown> {
1007
+ /** Unique message ID */
1008
+ readonly id: string;
1009
+ /** Thread this message belongs to */
1010
+ readonly threadId: string;
1011
+ /** Plain text content (all formatting stripped) */
1012
+ text: string;
1013
+ /**
1014
+ * Structured formatting as an AST (mdast Root).
1015
+ * This is the canonical representation - use this for processing.
1016
+ * Use `stringifyMarkdown(message.formatted)` to get markdown string.
1017
+ */
1018
+ formatted: FormattedContent;
1019
+ /** Platform-specific raw payload (escape hatch) */
1020
+ raw: TRawMessage;
1021
+ /** Message author */
1022
+ author: Author;
1023
+ /** Message metadata */
1024
+ metadata: MessageMetadata;
1025
+ /** Attachments */
1026
+ attachments: Attachment[];
1027
+ /**
1028
+ * Whether the bot is @-mentioned in this message.
1029
+ *
1030
+ * This is set by the Chat SDK before passing the message to handlers.
1031
+ * It checks for `@username` in the message text using the adapter's
1032
+ * configured `userName` and optional `botUserId`.
1033
+ *
1034
+ * @example
1035
+ * ```typescript
1036
+ * chat.onSubscribedMessage(async (thread, message) => {
1037
+ * if (message.isMention) {
1038
+ * await thread.post("You mentioned me!");
1039
+ * }
1040
+ * });
1041
+ * ```
1042
+ */
1043
+ isMention?: boolean;
1044
+ constructor(data: MessageData<TRawMessage>);
1045
+ /**
1046
+ * Serialize the message to a plain JSON object.
1047
+ * Use this to pass message data to external systems like workflow engines.
1048
+ *
1049
+ * Note: Attachment `data` (Buffer) and `fetchData` (function) are omitted
1050
+ * as they're not serializable.
1051
+ */
1052
+ toJSON(): SerializedMessage;
1053
+ /**
1054
+ * Reconstruct a Message from serialized JSON data.
1055
+ * Converts ISO date strings back to Date objects.
1056
+ */
1057
+ static fromJSON<TRawMessage = unknown>(json: SerializedMessage): Message<TRawMessage>;
1058
+ /**
1059
+ * Serialize a Message instance for @workflow/serde.
1060
+ * This static method is automatically called by workflow serialization.
1061
+ */
1062
+ static [WORKFLOW_SERIALIZE](instance: Message): SerializedMessage;
1063
+ /**
1064
+ * Deserialize a Message from @workflow/serde.
1065
+ * This static method is automatically called by workflow deserialization.
1066
+ */
1067
+ static [WORKFLOW_DESERIALIZE](data: SerializedMessage): Message;
1068
+ }
1069
+
960
1070
  /** Filter can be EmojiValue objects, emoji names, or raw emoji formats */
961
1071
  type EmojiFilter = EmojiValue | string;
962
1072
  /**
@@ -998,6 +1108,29 @@ type Webhooks<TAdapters extends Record<string, Adapter>> = {
998
1108
  * });
999
1109
  */
1000
1110
  declare class Chat<TAdapters extends Record<string, Adapter> = Record<string, Adapter>, TState = Record<string, unknown>> implements ChatInstance {
1111
+ /**
1112
+ * Register this Chat instance as the global singleton.
1113
+ * Required for Thread deserialization via @workflow/serde.
1114
+ *
1115
+ * @example
1116
+ * ```typescript
1117
+ * const chat = new Chat({ ... });
1118
+ * chat.registerSingleton();
1119
+ *
1120
+ * // Now threads can be deserialized without passing chat explicitly
1121
+ * const thread = ThreadImpl.fromJSON(serializedThread);
1122
+ * ```
1123
+ */
1124
+ registerSingleton(): this;
1125
+ /**
1126
+ * Get the registered singleton Chat instance.
1127
+ * Throws if no singleton has been registered.
1128
+ */
1129
+ static getSingleton(): Chat;
1130
+ /**
1131
+ * Check if a singleton has been registered.
1132
+ */
1133
+ static hasSingleton(): boolean;
1001
1134
  private adapters;
1002
1135
  private _stateAdapter;
1003
1136
  private userName;
@@ -1171,6 +1304,26 @@ declare class Chat<TAdapters extends Record<string, Adapter> = Record<string, Ad
1171
1304
  * Get an adapter by name with type safety.
1172
1305
  */
1173
1306
  getAdapter<K extends keyof TAdapters>(name: K): TAdapters[K];
1307
+ /**
1308
+ * Get a JSON.parse reviver function that automatically deserializes
1309
+ * chat:Thread and chat:Message objects.
1310
+ *
1311
+ * Use this when parsing JSON that contains serialized Thread or Message objects
1312
+ * (e.g., from workflow engine payloads).
1313
+ *
1314
+ * @returns A reviver function for JSON.parse
1315
+ *
1316
+ * @example
1317
+ * ```typescript
1318
+ * // Parse workflow payload with automatic deserialization
1319
+ * const data = JSON.parse(payload, chat.reviver());
1320
+ *
1321
+ * // data.thread is now a ThreadImpl instance
1322
+ * // data.message is now a Message object with Date fields restored
1323
+ * await data.thread.post("Hello from workflow!");
1324
+ * ```
1325
+ */
1326
+ reviver(): (key: string, value: unknown) => unknown;
1174
1327
  /**
1175
1328
  * Process an incoming message from an adapter.
1176
1329
  * Handles waitUntil registration and error catching internally.
@@ -1257,27 +1410,55 @@ declare class Chat<TAdapters extends Record<string, Adapter> = Record<string, Ad
1257
1410
  private runHandlers;
1258
1411
  }
1259
1412
 
1260
- interface ThreadImplConfig {
1413
+ /**
1414
+ * Serialized thread data for passing to external systems (e.g., workflow engines).
1415
+ */
1416
+ interface SerializedThread {
1417
+ _type: "chat:Thread";
1418
+ id: string;
1419
+ channelId: string;
1420
+ isDM: boolean;
1421
+ adapterName: string;
1422
+ }
1423
+ /**
1424
+ * Config for creating a ThreadImpl with explicit adapter/state instances.
1425
+ */
1426
+ interface ThreadImplConfigWithAdapter {
1261
1427
  id: string;
1262
1428
  adapter: Adapter;
1263
1429
  channelId: string;
1264
1430
  stateAdapter: StateAdapter;
1265
1431
  initialMessage?: Message;
1266
- /** If true, thread is known to be subscribed (for short-circuit optimization) */
1267
1432
  isSubscribedContext?: boolean;
1268
- /** Whether this is a direct message conversation */
1269
1433
  isDM?: boolean;
1270
- /** Current message context for streaming (provides userId/teamId) */
1271
1434
  currentMessage?: Message;
1272
- /** Update interval for fallback streaming in milliseconds. Defaults to 500ms. */
1273
1435
  streamingUpdateIntervalMs?: number;
1274
1436
  }
1437
+ /**
1438
+ * Config for creating a ThreadImpl with lazy adapter resolution.
1439
+ * The adapter will be looked up from the Chat singleton on first access.
1440
+ */
1441
+ interface ThreadImplConfigLazy {
1442
+ id: string;
1443
+ adapterName: string;
1444
+ channelId: string;
1445
+ initialMessage?: Message;
1446
+ isSubscribedContext?: boolean;
1447
+ isDM?: boolean;
1448
+ currentMessage?: Message;
1449
+ streamingUpdateIntervalMs?: number;
1450
+ }
1451
+ type ThreadImplConfig = ThreadImplConfigWithAdapter | ThreadImplConfigLazy;
1275
1452
  declare class ThreadImpl<TState = Record<string, unknown>> implements Thread<TState> {
1276
1453
  readonly id: string;
1277
- readonly adapter: Adapter;
1278
1454
  readonly channelId: string;
1279
1455
  readonly isDM: boolean;
1280
- private _stateAdapter;
1456
+ /** Direct adapter instance (if provided) */
1457
+ private _adapter?;
1458
+ /** Adapter name for lazy resolution */
1459
+ private _adapterName?;
1460
+ /** Direct state adapter instance (if provided) */
1461
+ private _stateAdapterInstance?;
1281
1462
  private _recentMessages;
1282
1463
  private _isSubscribedContext;
1283
1464
  /** Current message context for streaming - provides userId/teamId */
@@ -1285,6 +1466,16 @@ declare class ThreadImpl<TState = Record<string, unknown>> implements Thread<TSt
1285
1466
  /** Update interval for fallback streaming */
1286
1467
  private _streamingUpdateIntervalMs;
1287
1468
  constructor(config: ThreadImplConfig);
1469
+ /**
1470
+ * Get the adapter for this thread.
1471
+ * If created with lazy config, resolves from Chat singleton on first access.
1472
+ */
1473
+ get adapter(): Adapter;
1474
+ /**
1475
+ * Get the state adapter for this thread.
1476
+ * If created with lazy config, resolves from Chat singleton on first access.
1477
+ */
1478
+ private get _stateAdapter();
1288
1479
  get recentMessages(): Message[];
1289
1480
  set recentMessages(messages: Message[]);
1290
1481
  /**
@@ -1319,6 +1510,46 @@ declare class ThreadImpl<TState = Record<string, unknown>> implements Thread<TSt
1319
1510
  private fallbackStream;
1320
1511
  refresh(): Promise<void>;
1321
1512
  mentionUser(userId: string): string;
1513
+ /**
1514
+ * Serialize the thread to a plain JSON object.
1515
+ * Use this to pass thread data to external systems like workflow engines.
1516
+ *
1517
+ * @example
1518
+ * ```typescript
1519
+ * // Pass to a workflow
1520
+ * await workflow.start("my-workflow", {
1521
+ * thread: thread.toJSON(),
1522
+ * message: serializeMessage(message),
1523
+ * });
1524
+ * ```
1525
+ */
1526
+ toJSON(): SerializedThread;
1527
+ /**
1528
+ * Reconstruct a Thread from serialized JSON data.
1529
+ *
1530
+ * Reconstructs a ThreadImpl from serialized data.
1531
+ * Uses lazy resolution from Chat.getSingleton() for adapter and state.
1532
+ *
1533
+ * @param json - Serialized thread data
1534
+ * @requires Call `chat.registerSingleton()` before deserializing threads
1535
+ *
1536
+ * @example
1537
+ * ```typescript
1538
+ * const thread = ThreadImpl.fromJSON(serializedThread);
1539
+ * ```
1540
+ */
1541
+ static fromJSON<TState = Record<string, unknown>>(json: SerializedThread): ThreadImpl<TState>;
1542
+ /**
1543
+ * Serialize a ThreadImpl instance for @workflow/serde.
1544
+ * This static method is automatically called by workflow serialization.
1545
+ */
1546
+ static [WORKFLOW_SERIALIZE](instance: ThreadImpl): SerializedThread;
1547
+ /**
1548
+ * Deserialize a ThreadImpl from @workflow/serde.
1549
+ * Uses lazy adapter resolution from Chat.getSingleton().
1550
+ * Requires chat.registerSingleton() to have been called.
1551
+ */
1552
+ static [WORKFLOW_DESERIALIZE](data: SerializedThread): ThreadImpl;
1322
1553
  private createSentMessage;
1323
1554
  }
1324
1555
 
@@ -1713,4 +1944,4 @@ declare const Select: typeof Select$1;
1713
1944
  declare const SelectOption: typeof SelectOption$1;
1714
1945
  declare const TextInput: typeof TextInput$1;
1715
1946
 
1716
- export { type ActionEvent, type ActionHandler, Actions, type Adapter, type AdapterPostableMessage, type Attachment, type Author, BaseFormatConverter, Button, Card, CardChild, CardElement, CardJSXElement, CardText, Chat, type ChatConfig, ChatError, type ChatInstance, ConsoleLogger, type CustomEmojiMap, DEFAULT_EMOJI_MAP, Divider, type Emoji, type EmojiFormats, type EmojiMapConfig, EmojiResolver, type EmojiValue, type FetchDirection, type FetchOptions, type FetchResult, Field, Fields, type FileUpload, type FormatConverter, type FormattedContent, Image, type Lock, LockError, type LogLevel, type Logger, type MarkdownConverter, type MentionHandler, type Message, type MessageHandler, type MessageMetadata, Modal, type ModalCloseEvent, type ModalCloseHandler, type ModalCloseResponse, ModalElement, type ModalErrorsResponse, type ModalPushResponse, type ModalResponse, type ModalSubmitEvent, type ModalSubmitHandler, type ModalUpdateResponse, NotImplementedError, type PostableAst, type PostableCard, type PostableMarkdown, type PostableMessage, type PostableRaw, RateLimitError, type RawMessage, type ReactionEvent, type ReactionHandler, Section, Select, SelectOption, type SentMessage, type StateAdapter, type StreamOptions, type SubscribedMessageHandler, THREAD_STATE_TTL_MS, TextInput, type Thread, ThreadImpl, type ThreadInfo, type WebhookOptions, type WellKnownEmoji, blockquote, codeBlock, convertEmojiPlaceholders, createEmoji, defaultEmojiResolver, emoji, emphasis, fromReactElement, fromReactModalElement, getEmoji, getNodeChildren, getNodeValue, inlineCode, isBlockquoteNode, isCardElement, isCodeNode, isDeleteNode, isEmphasisNode, isInlineCodeNode, isJSX, isLinkNode, isListItemNode, isListNode, isModalElement, isParagraphNode, isStrongNode, isTextNode, link, markdownToPlainText, paragraph, parseMarkdown, root, strikethrough, stringifyMarkdown, strong, text, toCardElement, toModalElement, toPlainText, walkAst };
1947
+ export { type ActionEvent, type ActionHandler, Actions, type Adapter, type AdapterPostableMessage, type Attachment, type Author, BaseFormatConverter, Button, Card, CardChild, CardElement, CardJSXElement, CardText, Chat, type ChatConfig, ChatError, type ChatInstance, ConsoleLogger, type CustomEmojiMap, DEFAULT_EMOJI_MAP, Divider, type Emoji, type EmojiFormats, type EmojiMapConfig, EmojiResolver, type EmojiValue, type FetchDirection, type FetchOptions, type FetchResult, Field, Fields, type FileUpload, type FormatConverter, type FormattedContent, Image, type Lock, LockError, type LogLevel, type Logger, type MarkdownConverter, type MentionHandler, Message, type MessageData, type MessageHandler, type MessageMetadata, Modal, type ModalCloseEvent, type ModalCloseHandler, type ModalCloseResponse, ModalElement, type ModalErrorsResponse, type ModalPushResponse, type ModalResponse, type ModalSubmitEvent, type ModalSubmitHandler, type ModalUpdateResponse, NotImplementedError, type PostableAst, type PostableCard, type PostableMarkdown, type PostableMessage, type PostableRaw, RateLimitError, type RawMessage, type ReactionEvent, type ReactionHandler, Section, Select, SelectOption, type SentMessage, type SerializedMessage, type SerializedThread, type StateAdapter, type StreamOptions, type SubscribedMessageHandler, THREAD_STATE_TTL_MS, TextInput, type Thread, ThreadImpl, type ThreadInfo, type WebhookOptions, type WellKnownEmoji, blockquote, codeBlock, convertEmojiPlaceholders, createEmoji, defaultEmojiResolver, emoji, emphasis, fromReactElement, fromReactModalElement, getEmoji, getNodeChildren, getNodeValue, inlineCode, isBlockquoteNode, isCardElement, isCodeNode, isDeleteNode, isEmphasisNode, isInlineCodeNode, isJSX, isLinkNode, isListItemNode, isListNode, isModalElement, isParagraphNode, isStrongNode, isTextNode, link, markdownToPlainText, paragraph, parseMarkdown, root, strikethrough, stringifyMarkdown, strong, text, toCardElement, toModalElement, toPlainText, walkAst };