samva 0.29.1 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/AGENTS.md +23 -5
  2. package/README.md +166 -133
  3. package/dist/_virtual/_rolldown/runtime.js +1 -2
  4. package/dist/client/client/client.gen.js +1 -2
  5. package/dist/client/client/utils.gen.js +1 -2
  6. package/dist/client/client.gen.js +1 -2
  7. package/dist/client/core/auth.gen.js +1 -2
  8. package/dist/client/core/bodySerializer.gen.js +1 -2
  9. package/dist/client/core/params.gen.js +1 -2
  10. package/dist/client/core/pathSerializer.gen.js +1 -2
  11. package/dist/client/core/serverSentEvents.gen.js +1 -2
  12. package/dist/client/core/utils.gen.js +1 -2
  13. package/dist/client/sdk.gen.d.ts +216 -191
  14. package/dist/client/sdk.gen.js +2392 -1153
  15. package/dist/client/types.gen.d.ts +766 -376
  16. package/dist/client-attribution.js +1 -2
  17. package/dist/effect/agents.d.ts +33 -11
  18. package/dist/effect/agents.js +1 -2
  19. package/dist/effect/analytics.d.ts +6 -6
  20. package/dist/effect/analytics.js +1 -2
  21. package/dist/effect/api-keys.d.ts +8 -8
  22. package/dist/effect/api-keys.js +1 -2
  23. package/dist/effect/attachments.d.ts +4 -4
  24. package/dist/effect/attachments.js +1 -2
  25. package/dist/effect/brands.d.ts +6 -6
  26. package/dist/effect/brands.js +1 -2
  27. package/dist/effect/campaigns.d.ts +15 -16
  28. package/dist/effect/campaigns.js +1 -2
  29. package/dist/effect/categories.js +1 -2
  30. package/dist/effect/client.js +1 -2
  31. package/dist/effect/contact-groups.d.ts +10 -10
  32. package/dist/effect/contact-groups.js +1 -2
  33. package/dist/effect/contacts.d.ts +23 -24
  34. package/dist/effect/contacts.js +1 -2
  35. package/dist/effect/conversations.d.ts +13 -13
  36. package/dist/effect/conversations.js +1 -2
  37. package/dist/effect/custom-fields.d.ts +4 -4
  38. package/dist/effect/custom-fields.js +1 -2
  39. package/dist/effect/email.d.ts +61 -63
  40. package/dist/effect/email.js +1 -2
  41. package/dist/effect/events.d.ts +2 -4
  42. package/dist/effect/events.js +1 -2
  43. package/dist/effect/extension-installations.d.ts +9 -9
  44. package/dist/effect/extension-installations.js +1 -2
  45. package/dist/effect/extensions.d.ts +5 -5
  46. package/dist/effect/extensions.js +1 -2
  47. package/dist/effect/feedback.d.ts +1 -1
  48. package/dist/effect/feedback.js +1 -2
  49. package/dist/effect/generated/agents.d.ts +264 -22
  50. package/dist/effect/generated/agents.js +2 -3
  51. package/dist/effect/generated/analytics.js +1 -2
  52. package/dist/effect/generated/api-keys.js +1 -2
  53. package/dist/effect/generated/attachments.js +1 -2
  54. package/dist/effect/generated/brands.js +1 -2
  55. package/dist/effect/generated/campaigns.d.ts +160 -155
  56. package/dist/effect/generated/campaigns.js +7 -9
  57. package/dist/effect/generated/contact-events.js +1 -2
  58. package/dist/effect/generated/contact-groups.d.ts +26 -26
  59. package/dist/effect/generated/contact-groups.js +22 -19
  60. package/dist/effect/generated/contacts.d.ts +119 -90
  61. package/dist/effect/generated/contacts.js +32 -32
  62. package/dist/effect/generated/conversations.d.ts +22 -22
  63. package/dist/effect/generated/conversations.js +7 -8
  64. package/dist/effect/generated/custom-fields.d.ts +6 -6
  65. package/dist/effect/generated/custom-fields.js +3 -4
  66. package/dist/effect/generated/email.d.ts +38 -38
  67. package/dist/effect/generated/email.js +13 -14
  68. package/dist/effect/generated/events.d.ts +18 -9
  69. package/dist/effect/generated/events.js +8 -6
  70. package/dist/effect/generated/extension-installations.d.ts +2 -2
  71. package/dist/effect/generated/extension-installations.js +6 -3
  72. package/dist/effect/generated/extensions.js +1 -2
  73. package/dist/effect/generated/feedback.js +1 -2
  74. package/dist/effect/generated/index.d.ts +7 -5
  75. package/dist/effect/generated/journeys.js +1 -2
  76. package/dist/effect/generated/mailboxes.d.ts +44 -44
  77. package/dist/effect/generated/mailboxes.js +17 -18
  78. package/dist/effect/generated/media.js +1 -2
  79. package/dist/effect/generated/messages.d.ts +42 -42
  80. package/dist/effect/generated/messages.js +3 -4
  81. package/dist/effect/generated/namespaces.js +1 -2
  82. package/dist/effect/generated/{publication-domains.d.ts → newsletter-domains.d.ts} +304 -80
  83. package/dist/effect/generated/newsletter-domains.js +218 -0
  84. package/dist/effect/generated/{topic-issues.d.ts → newsletter-issues.d.ts} +330 -288
  85. package/dist/effect/generated/{topic-issues.js → newsletter-issues.js} +255 -246
  86. package/dist/effect/generated/newsletters.d.ts +741 -0
  87. package/dist/effect/generated/newsletters.js +143 -0
  88. package/dist/effect/generated/operations.js +1 -2
  89. package/dist/effect/generated/organizations.d.ts +9 -9
  90. package/dist/effect/generated/organizations.js +4 -5
  91. package/dist/effect/generated/scheduled-messages.d.ts +174 -169
  92. package/dist/effect/generated/scheduled-messages.js +7 -7
  93. package/dist/effect/generated/shared.d.ts +276 -208
  94. package/dist/effect/generated/shared.js +50 -36
  95. package/dist/effect/generated/subscriptions.js +1 -2
  96. package/dist/effect/generated/templates.d.ts +118 -67
  97. package/dist/effect/generated/templates.js +43 -35
  98. package/dist/effect/generated/topic-forms.d.ts +79 -19
  99. package/dist/effect/generated/topic-forms.js +13 -14
  100. package/dist/effect/generated/topics.d.ts +27 -65
  101. package/dist/effect/generated/topics.js +13 -20
  102. package/dist/effect/generated/webhooks.d.ts +9 -9
  103. package/dist/effect/generated/webhooks.js +4 -5
  104. package/dist/effect/generated/whoami.js +1 -2
  105. package/dist/effect/generated-metadata.d.ts +475 -70
  106. package/dist/effect/generated-metadata.js +642 -432
  107. package/dist/effect/index.d.ts +3 -2
  108. package/dist/effect/index.js +4 -3
  109. package/dist/effect/internal/client.d.ts +5 -0
  110. package/dist/effect/internal/client.js +9 -5
  111. package/dist/effect/internal/email-sender.d.ts +1 -1
  112. package/dist/effect/internal/email-sender.js +4 -3
  113. package/dist/effect/internal/mailbox-events.js +1 -2
  114. package/dist/effect/internal/operation.d.ts +4 -15
  115. package/dist/effect/internal/operation.js +21 -33
  116. package/dist/effect/internal/send.js +2 -3
  117. package/dist/effect/journeys.d.ts +14 -14
  118. package/dist/effect/journeys.js +1 -2
  119. package/dist/effect/mailboxes.d.ts +60 -70
  120. package/dist/effect/mailboxes.js +1 -2
  121. package/dist/effect/media.d.ts +5 -5
  122. package/dist/effect/media.js +1 -2
  123. package/dist/effect/messages.d.ts +9 -9
  124. package/dist/effect/messages.js +1 -2
  125. package/dist/effect/namespaces.d.ts +8 -8
  126. package/dist/effect/namespaces.js +1 -2
  127. package/dist/effect/newsletter-domains.d.ts +71 -0
  128. package/dist/effect/newsletter-domains.js +18 -0
  129. package/dist/effect/{topic-issues.d.ts → newsletter-issues.d.ts} +11 -15
  130. package/dist/effect/newsletter-issues.js +32 -0
  131. package/dist/effect/newsletters.d.ts +22 -0
  132. package/dist/effect/newsletters.js +20 -0
  133. package/dist/effect/operations.d.ts +3 -3
  134. package/dist/effect/operations.js +1 -2
  135. package/dist/effect/organizations.d.ts +8 -10
  136. package/dist/effect/organizations.js +1 -2
  137. package/dist/effect/pagination.js +1 -2
  138. package/dist/effect/retry.d.ts +4 -4
  139. package/dist/effect/retry.js +5 -6
  140. package/dist/effect/runtime.js +1 -2
  141. package/dist/effect/scheduled-messages.d.ts +5 -6
  142. package/dist/effect/scheduled-messages.js +1 -2
  143. package/dist/effect/subscriptions.d.ts +1 -1
  144. package/dist/effect/subscriptions.js +1 -2
  145. package/dist/effect/templates.d.ts +34 -43
  146. package/dist/effect/templates.js +1 -2
  147. package/dist/effect/topic-forms.d.ts +5 -5
  148. package/dist/effect/topic-forms.js +1 -2
  149. package/dist/effect/topics.d.ts +9 -13
  150. package/dist/effect/topics.js +1 -2
  151. package/dist/effect/webhooks.d.ts +11 -11
  152. package/dist/effect/webhooks.js +1 -2
  153. package/dist/effect/whoami.d.ts +1 -1
  154. package/dist/effect/whoami.js +1 -2
  155. package/dist/index.js +2 -2
  156. package/dist/inline-attachments.js +1 -2
  157. package/dist/mailbox/dispatch.d.ts +10 -0
  158. package/dist/mailbox/dispatch.js +66 -0
  159. package/dist/mailbox/index.d.ts +17 -0
  160. package/dist/mailbox/index.js +30 -0
  161. package/dist/mailbox/test.d.ts +25 -0
  162. package/dist/mailbox/test.js +174 -0
  163. package/dist/mailbox/types.d.ts +184 -0
  164. package/dist/mailbox/webhook.d.ts +10 -0
  165. package/dist/mailbox/webhook.js +41 -0
  166. package/dist/mailbox-events.js +1 -2
  167. package/dist/normalize.js +1 -2
  168. package/dist/package.js +2 -3
  169. package/dist/promises/client.d.ts +215 -0
  170. package/dist/promises/client.js +324 -0
  171. package/dist/promises/errors.gen.js +1 -2
  172. package/dist/promises/index.d.ts +2 -196
  173. package/dist/promises/index.js +3 -295
  174. package/dist/promises/request.d.ts +15 -0
  175. package/dist/promises/request.js +75 -0
  176. package/dist/promises/types.gen.d.ts +1 -1
  177. package/dist/request-policy.d.ts +3 -0
  178. package/dist/request-policy.js +16 -0
  179. package/dist/service-map.d.ts +78 -47
  180. package/dist/service-map.js +52 -32
  181. package/package.json +34 -18
  182. package/dist/effect/generated/publication-domains.js +0 -163
  183. package/dist/effect/publication-domains.d.ts +0 -14
  184. package/dist/effect/publication-domains.js +0 -17
  185. package/dist/effect/topic-issues.js +0 -33
@@ -1,199 +1,5 @@
1
- /**
2
- * Samva SDK - TypeScript client for the Samva API.
3
- *
4
- * Ergonomic methods resolve with decoded success values and throw generated
5
- * plain-JavaScript error classes. The bound Hey API result surface remains
6
- * available under `client.raw` for transport-level access.
7
- *
8
- * @example
9
- * ```typescript
10
- * import { createClient, RateLimitedError } from "samva";
11
- *
12
- * const samva = createClient({ apiKey: "<samva-api-key>" });
13
- *
14
- * try {
15
- * const { contact } = await samva.contacts.findOrCreate({
16
- * create: { name: "Ada Lovelace" },
17
- * lookup: { type: "email", value: "ada@example.com" },
18
- * });
19
- * await samva.email.send({
20
- * to: contact,
21
- * subject: "Hello",
22
- * html: "<p>Hi there!</p>",
23
- * });
24
- * } catch (error) {
25
- * if (error instanceof RateLimitedError) console.log(error.retryAfterSeconds);
26
- * }
27
- * ```
28
- */
29
- import { type Client, type Config } from "../client/client";
30
- import { Agents as agents, Analytics as analytics, ApiKeys as apiKeys, Attachments as attachments, Brands as brands, Campaigns as campaigns, ContactGroups as contactGroups, ContactEvents as contactEvents, Contacts as contacts, Conversations as conversations, CustomFields as customFields, Email as email, ExtensionInstallations as extensionInstallations, Extensions as extensions, Events as events, Feedback as feedback, Journeys as journeys, Mailboxes as mailboxes, Media as media, Messages as messages, Namespaces as namespaces, Operations as operations, Organizations as organizations, ScheduledMessages as scheduledMessages, Subscriptions as subscriptions, Templates as templates, Topics as topics, TopicForms as topicForms, TopicIssues as topicIssues, TopicPublicationDomains as topicPublicationDomains, Webhooks as webhooks, Whoami as whoami } from "../client/sdk.gen";
31
- import type { MessagesSendData } from "../client/types.gen";
32
- import { MailboxEventStream, type MailboxEventStreamOptions } from "../mailbox-events";
1
+ export { createClient, type SamvaClient, type SamvaClientConfig, type SamvaRawClient, type PromiseMailboxesService, type Client, type Config, } from "./client";
33
2
  export * from "./errors.gen";
34
- export { MediaUploadError } from "../inline-attachments";
35
3
  export type * from "./types.gen";
4
+ export { MediaUploadError } from "../inline-attachments";
36
5
  export { MailboxEventStream, MailboxEventStreamError, type MailboxEvent, type MailboxEventStreamErrorFields, type MailboxEventStreamErrorReason, type MailboxEventStreamErrorTag, type MailboxEventStreamFailure, type MailboxEventStreamOptions, type MailboxEventStreamReconnect, type MailboxEventStreamWebSocket, type MailboxEventType, } from "../mailbox-events";
37
- interface SamvaClientConfigBase extends Omit<Config, "baseUrl" | "responseStyle" | "throwOnError"> {
38
- /** Base URL for the API (defaults to https://api.samva.dev). */
39
- baseUrl?: string;
40
- }
41
- export type SamvaClientConfig = (SamvaClientConfigBase & {
42
- /** Your Samva API key. The organization is derived from the key. */
43
- apiKey: string;
44
- authToken?: never;
45
- }) | (SamvaClientConfigBase & {
46
- /** OAuth bearer token, such as one obtained by `samva login`. */
47
- authToken: string;
48
- apiKey?: never;
49
- });
50
- type MessageSendBody = MessagesSendData["body"];
51
- type MessageRecipient = MessageSendBody["to"][number];
52
- type MessageSendRequestOptions<ThrowOnError extends boolean = false> = Omit<NonNullable<Parameters<typeof messages.send<ThrowOnError>>[1]>, "client">;
53
- type MessageSendOptions<ThrowOnError extends boolean = false> = MessageSendRequestOptions<ThrowOnError> & {
54
- /** Sent as the `idempotency-key` header; defaults to a fresh UUID per call. */
55
- readonly idempotencyKey?: string | undefined;
56
- };
57
- type MessageSendResponse<ThrowOnError extends boolean = false> = ReturnType<typeof messages.send<ThrowOnError>>;
58
- type ContactObjectRecipient = {
59
- readonly id: string;
60
- };
61
- type ErgonomicMessageRecipient = MessageRecipient | ContactObjectRecipient | string;
62
- type EmailMessageSendBody = Extract<MessageSendBody, {
63
- readonly channel: "email";
64
- }>;
65
- type ErgonomicReplyTo = string | ReadonlyArray<string>;
66
- type ErgonomicEmailList = string | ReadonlyArray<string>;
67
- type ErgonomicEmailContent = Omit<EmailMessageSendBody["email"], "replyTo"> & {
68
- readonly replyTo?: ErgonomicReplyTo | null | undefined;
69
- };
70
- type EmailAddSenderWireInput = NonNullable<Parameters<typeof email.addSender>[0]>;
71
- type EmailAddSenderRequestOptions<ThrowOnError extends boolean = false> = Parameters<typeof email.addSender<ThrowOnError>>[1];
72
- type ErgonomicEmailAddSenderInput = Omit<EmailAddSenderWireInput, "idempotency-key" | "replyToEmails"> & {
73
- readonly replyToEmails?: ErgonomicEmailList | null | undefined;
74
- };
75
- type EmailAddSenderOptions<ThrowOnError extends boolean = false> = EmailAddSenderRequestOptions<ThrowOnError> & {
76
- readonly idempotencyKey?: string | undefined;
77
- };
78
- type ErgonomicEmailMessageSendBody = Omit<EmailMessageSendBody, "to" | "cc" | "bcc" | "email"> & {
79
- readonly to: ErgonomicMessageRecipient | ReadonlyArray<ErgonomicMessageRecipient>;
80
- readonly cc?: ErgonomicMessageRecipient | ReadonlyArray<ErgonomicMessageRecipient> | null;
81
- readonly bcc?: ErgonomicMessageRecipient | ReadonlyArray<ErgonomicMessageRecipient> | null;
82
- readonly email: ErgonomicEmailContent;
83
- };
84
- type ErgonomicMessageSendInput = ErgonomicEmailMessageSendBody;
85
- type PromiseMessagesTransport = {
86
- readonly list: typeof messages.list;
87
- readonly remove: typeof messages.remove;
88
- readonly get: typeof messages.get;
89
- readonly getEmail: typeof messages.getEmail;
90
- readonly getStatus: typeof messages.getStatus;
91
- readonly getEvents: typeof messages.getEvents;
92
- readonly listDeliveries: typeof messages.listDeliveries;
93
- readonly getContent: typeof messages.getContent;
94
- readonly validateEmail: typeof messages.validateEmail;
95
- readonly send: <ThrowOnError extends boolean = false>(input: ErgonomicMessageSendInput, options?: MessageSendOptions<ThrowOnError>) => MessageSendResponse<ThrowOnError>;
96
- };
97
- type ErgonomicEmailSendBody = Omit<EmailMessageSendBody, "channel" | "email" | "to" | "cc" | "bcc"> & ErgonomicEmailContent & {
98
- readonly to: ErgonomicMessageRecipient | ReadonlyArray<ErgonomicMessageRecipient>;
99
- readonly cc?: ErgonomicMessageRecipient | ReadonlyArray<ErgonomicMessageRecipient>;
100
- readonly bcc?: ErgonomicMessageRecipient | ReadonlyArray<ErgonomicMessageRecipient>;
101
- };
102
- type PromiseEmailTransport = Omit<typeof email, "send"> & {
103
- readonly send: <ThrowOnError extends boolean = false>(input: ErgonomicEmailSendBody, options?: MessageSendOptions<ThrowOnError>) => MessageSendResponse<ThrowOnError>;
104
- readonly addSender: <ThrowOnError extends boolean = false>(input: ErgonomicEmailAddSenderInput, options?: EmailAddSenderOptions<ThrowOnError>) => ReturnType<typeof email.addSender<ThrowOnError>>;
105
- };
106
- type PromiseTemplatesTransport = typeof templates;
107
- type RawMethod = (...arguments_: Array<never>) => PromiseLike<unknown>;
108
- type SuccessValue<Method extends RawMethod> = Exclude<Awaited<ReturnType<Method>> extends infer Result ? Result extends {
109
- readonly data: infer Data;
110
- } ? Data : never : never, undefined>;
111
- type ErgonomicOptions<Options> = Options extends object ? Omit<Options, "client" | "responseStyle" | "throwOnError"> : Options;
112
- type DirectArguments<Method extends RawMethod> = {
113
- [Key in keyof Parameters<Method>]: Key extends 1 | "1" ? ErgonomicOptions<Parameters<Method>[Key]> : Parameters<Method>[Key];
114
- };
115
- type DirectMethod<Method extends RawMethod> = (...arguments_: DirectArguments<Method>) => Promise<SuccessValue<Method>>;
116
- type DirectService<Service extends object> = {
117
- readonly [Key in keyof Service]: Service[Key] extends RawMethod ? DirectMethod<Service[Key]> : Service[Key] extends object ? DirectService<Service[Key]> : Service[Key];
118
- };
119
- export interface SamvaRawClient {
120
- /** The underlying generated HTTP client. */
121
- readonly client: Client;
122
- readonly messages: typeof messages;
123
- readonly scheduledMessages: typeof scheduledMessages;
124
- readonly brands: typeof brands;
125
- readonly campaigns: typeof campaigns;
126
- readonly email: typeof email;
127
- readonly media: typeof media;
128
- readonly templates: PromiseTemplatesTransport;
129
- readonly contacts: typeof contacts & typeof contactEvents;
130
- readonly events: typeof events;
131
- readonly conversations: typeof conversations;
132
- readonly webhooks: typeof webhooks;
133
- readonly operations: typeof operations;
134
- readonly apiKeys: typeof apiKeys;
135
- readonly organizations: typeof organizations;
136
- readonly attachments: typeof attachments;
137
- readonly contactGroups: typeof contactGroups;
138
- readonly customFields: typeof customFields;
139
- readonly subscriptions: typeof subscriptions;
140
- readonly topics: typeof topics;
141
- readonly topicForms: typeof topicForms;
142
- readonly topicIssues: typeof topicIssues;
143
- readonly topicPublicationDomains: typeof topicPublicationDomains;
144
- readonly agents: typeof agents;
145
- readonly analytics: typeof analytics;
146
- readonly feedback: typeof feedback;
147
- readonly whoami: typeof whoami;
148
- readonly journeys: typeof journeys;
149
- readonly mailboxes: typeof mailboxes;
150
- readonly namespaces: typeof namespaces;
151
- readonly extensions: typeof extensions;
152
- readonly extensionInstallations: typeof extensionInstallations;
153
- }
154
- /** The mailbox operations, plus the mailbox event stream. */
155
- export type PromiseMailboxesService = DirectService<typeof mailboxes> & {
156
- /**
157
- * The organization's mailbox events over a WebSocket, as an async iterable that resumes from
158
- * the last handled event. See {@link MailboxEventStream}.
159
- */
160
- readonly events: (options?: MailboxEventStreamOptions) => MailboxEventStream;
161
- };
162
- export interface SamvaClient {
163
- /** Bound, unmodified Hey API methods and their original result envelopes. */
164
- readonly raw: SamvaRawClient;
165
- readonly messages: DirectService<PromiseMessagesTransport>;
166
- readonly scheduledMessages: DirectService<typeof scheduledMessages>;
167
- readonly brands: DirectService<typeof brands>;
168
- readonly campaigns: DirectService<typeof campaigns>;
169
- readonly email: DirectService<PromiseEmailTransport>;
170
- readonly media: DirectService<typeof media>;
171
- readonly templates: DirectService<PromiseTemplatesTransport>;
172
- readonly contacts: DirectService<typeof contacts & typeof contactEvents>;
173
- readonly events: DirectService<typeof events>;
174
- readonly conversations: DirectService<typeof conversations>;
175
- readonly webhooks: DirectService<typeof webhooks>;
176
- readonly operations: DirectService<typeof operations>;
177
- readonly apiKeys: DirectService<typeof apiKeys>;
178
- readonly organizations: DirectService<typeof organizations>;
179
- readonly attachments: DirectService<typeof attachments>;
180
- readonly contactGroups: DirectService<typeof contactGroups>;
181
- readonly customFields: DirectService<typeof customFields>;
182
- readonly subscriptions: DirectService<typeof subscriptions>;
183
- readonly topics: DirectService<typeof topics>;
184
- readonly topicForms: DirectService<typeof topicForms>;
185
- readonly topicIssues: DirectService<typeof topicIssues>;
186
- readonly topicPublicationDomains: DirectService<typeof topicPublicationDomains>;
187
- readonly agents: DirectService<typeof agents>;
188
- readonly analytics: DirectService<typeof analytics>;
189
- readonly feedback: DirectService<typeof feedback>;
190
- readonly whoami: DirectService<typeof whoami>;
191
- readonly journeys: DirectService<typeof journeys>;
192
- readonly mailboxes: PromiseMailboxesService;
193
- readonly namespaces: DirectService<typeof namespaces>;
194
- readonly extensions: DirectService<typeof extensions>;
195
- readonly extensionInstallations: DirectService<typeof extensionInstallations>;
196
- }
197
- /** Create a configured Promise client. */
198
- export declare function createClient(config: SamvaClientConfig): SamvaClient;
199
- export type { Client, Config } from "../client/client";
@@ -1,297 +1,5 @@
1
- import { CLIENT_ATTRIBUTION_HEADER, clientAttribution } from "../client-attribution.js";
2
- import { mergeHeaders } from "../client/client/utils.gen.js";
3
- import { createClient as createClient$1 } from "../client/client/client.gen.js";
4
- import { Agents, Analytics, ApiKeys, Attachments, Brands, Campaigns, ContactEvents, ContactGroups, Contacts, Conversations, CustomFields, Email, Events, ExtensionInstallations, Extensions, Feedback, Journeys, Mailboxes, Media, Messages, Namespaces, Operations, Organizations, ScheduledMessages, Subscriptions, Templates, TopicForms, TopicIssues, TopicPublicationDomains, Topics, Webhooks, Whoami } from "../client/sdk.gen.js";
5
- import { MediaUploadError, mediaCreateBody, planInlineUploads, withUploadedAttachments } from "../inline-attachments.js";
6
- import { MailboxEventStream, MailboxEventStreamError } from "../mailbox-events.js";
7
- import { buildEmailSendPayload, buildMessagesSendPayload, replyToEmailsPayload } from "../normalize.js";
8
1
  import { AnalyticsQueryError, BillingProviderError, BrandAddressRequiredError, CampaignFooterRequiredError, ConflictError, DeliveryUnavailableError, EmailChannelError, ExternalServiceError, FlagDisabledError, ForbiddenError, FromAddressRequiredError, GatewayTimeoutError, InternalError, MailboxSendConflictError, MailboxSendRefusedError, OnboardingReviewRequiredError, PaymentRequiredError, RateLimitedError, ResourceNotFoundError, SamvaApiError, SamvaTransportError, SenderNotReadyError, TemplateSourceError, UnauthorizedError, ValidationError, fromApiError } from "./errors.gen.js";
9
- //#region src/promises/index.ts
10
- /**
11
- * Samva SDK - TypeScript client for the Samva API.
12
- *
13
- * Ergonomic methods resolve with decoded success values and throw generated
14
- * plain-JavaScript error classes. The bound Hey API result surface remains
15
- * available under `client.raw` for transport-level access.
16
- *
17
- * @example
18
- * ```typescript
19
- * import { createClient, RateLimitedError } from "samva";
20
- *
21
- * const samva = createClient({ apiKey: "<samva-api-key>" });
22
- *
23
- * try {
24
- * const { contact } = await samva.contacts.findOrCreate({
25
- * create: { name: "Ada Lovelace" },
26
- * lookup: { type: "email", value: "ada@example.com" },
27
- * });
28
- * await samva.email.send({
29
- * to: contact,
30
- * subject: "Hello",
31
- * html: "<p>Hi there!</p>",
32
- * });
33
- * } catch (error) {
34
- * if (error instanceof RateLimitedError) console.log(error.retryAfterSeconds);
35
- * }
36
- * ```
37
- */
38
- const isObject = (value) => typeof value === "object" && value !== null;
39
- /**
40
- * The key a retry-safe call sends as `idempotency-key`: the `idempotencyKey`
41
- * option, else one the caller set in `headers`, else a fresh UUID. The
42
- * generated header parameter is applied after request headers, so it must carry
43
- * a caller-set header value rather than overwrite it.
44
- */
45
- function resolveIdempotencyKey(options) {
46
- const { idempotencyKey, ...requestOptions } = options ?? {};
47
- return {
48
- idempotencyKey: idempotencyKey ?? mergeHeaders(requestOptions.headers).get("idempotency-key") ?? crypto.randomUUID(),
49
- requestOptions
50
- };
51
- }
52
- /**
53
- * Inline attachment content over the API's request cap travels as media instead: the largest
54
- * attachments are uploaded (create, put to the presigned URL, complete) and replaced by their
55
- * `mediaId`. The returned payload is the one request every send attempt reuses, so nothing is
56
- * uploaded twice.
57
- */
58
- async function uploadOversizedAttachments(clientInstance, payload, requestOptions) {
59
- const plan = planInlineUploads(payload);
60
- if (plan.length === 0) return payload;
61
- const uploaded = /* @__PURE__ */ new Map();
62
- const directMedia = createDirectService(createBoundService(Media, clientInstance));
63
- for (const upload of plan) {
64
- const created = await directMedia.create(mediaCreateBody(upload), requestOptions);
65
- await putUpload(clientInstance, upload, created, requestOptions.signal ?? void 0);
66
- await directMedia.complete({ id: created.id }, requestOptions);
67
- uploaded.set(upload.index, {
68
- mediaId: created.id,
69
- upload
70
- });
71
- }
72
- return withUploadedAttachments(payload, uploaded);
73
- }
74
- /**
75
- * Send with oversized inline attachments uploaded first. Within the cap this is the send call
76
- * itself, one request and no extra await, so its result is returned unchanged.
77
- */
78
- function sendWithUploads(clientInstance, payload, requestOptions, send) {
79
- if (planInlineUploads(payload).length === 0) return send(payload);
80
- return uploadOversizedAttachments(clientInstance, payload, requestOptions).then(send);
81
- }
82
- async function putUpload(clientInstance, upload, created, signal) {
83
- const fail = (status, cause) => new MediaUploadError({
84
- filename: upload.filename,
85
- mediaId: created.id,
86
- status,
87
- cause
88
- });
89
- let response;
90
- try {
91
- response = await (clientInstance.getConfig().fetch ?? globalThis.fetch)(new Request(created.upload.url, {
92
- method: created.upload.method,
93
- headers: created.upload.headers,
94
- body: upload.bytes,
95
- signal: signal ?? null
96
- }));
97
- } catch (error) {
98
- throw fail(void 0, error);
99
- }
100
- if (!response.ok) throw fail(response.status);
101
- }
102
- function createPromiseMessagesTransport(clientInstance) {
103
- const boundMessages = createBoundService(Messages, clientInstance);
104
- return {
105
- list: boundMessages.list,
106
- remove: boundMessages.remove,
107
- get: boundMessages.get,
108
- getEmail: boundMessages.getEmail,
109
- getStatus: boundMessages.getStatus,
110
- getEvents: boundMessages.getEvents,
111
- listDeliveries: boundMessages.listDeliveries,
112
- getContent: boundMessages.getContent,
113
- validateEmail: boundMessages.validateEmail,
114
- send: (input, options) => {
115
- const { idempotencyKey, requestOptions } = resolveIdempotencyKey(options);
116
- return sendWithUploads(clientInstance, buildMessagesSendPayload(input), requestOptions, (payload) => Messages.send({
117
- "idempotency-key": idempotencyKey,
118
- ...payload
119
- }, {
120
- ...requestOptions,
121
- client: clientInstance
122
- }));
123
- }
124
- };
125
- }
126
- function createPromiseEmailTransport(clientInstance) {
127
- const boundEmail = createBoundService(Email, clientInstance);
128
- return Object.assign(boundEmail, {
129
- addSender: (input, options) => {
130
- const { replyToEmails, ...sender } = input;
131
- const { idempotencyKey, requestOptions } = resolveIdempotencyKey(options);
132
- return Email.addSender({
133
- "idempotency-key": idempotencyKey,
134
- ...sender,
135
- ...replyToEmailsPayload(replyToEmails)
136
- }, {
137
- ...requestOptions,
138
- client: clientInstance
139
- });
140
- },
141
- send: (input, options) => {
142
- const { idempotencyKey, requestOptions } = resolveIdempotencyKey(options);
143
- return sendWithUploads(clientInstance, buildEmailSendPayload(input), requestOptions, (payload) => Messages.send({
144
- "idempotency-key": idempotencyKey,
145
- ...payload
146
- }, {
147
- ...requestOptions,
148
- client: clientInstance
149
- }));
150
- }
151
- });
152
- }
153
- function createPromiseTemplatesTransport(clientInstance) {
154
- return createBoundService(Templates, clientInstance);
155
- }
156
- function createBoundService(service, clientInstance) {
157
- const bound = {};
158
- for (const key of Object.getOwnPropertyNames(service)) {
159
- if (key === "length" || key === "name" || key === "prototype") continue;
160
- const value = service[key];
161
- if (typeof value === "function") bound[key] = value.length >= 2 ? (parameters, options) => value(parameters ?? {}, {
162
- ...options,
163
- client: clientInstance
164
- }) : (options) => value({
165
- ...options,
166
- client: clientInstance
167
- });
168
- else if (isObject(value)) bound[key] = createBoundService(value, clientInstance);
169
- else bound[key] = value;
170
- }
171
- return bound;
172
- }
173
- const directOptions = (options) => ({
174
- ...isObject(options) ? options : {},
175
- responseStyle: "fields",
176
- throwOnError: false
177
- });
178
- async function unwrap(method, arguments_) {
179
- let result;
180
- try {
181
- result = await method(...arguments_);
182
- } catch (error) {
183
- if (error instanceof MediaUploadError) throw error;
184
- throw fromApiError(error);
185
- }
186
- if (!isObject(result)) throw new SamvaTransportError(result);
187
- const raw = result;
188
- const context = {
189
- request: raw.request,
190
- response: raw.response
191
- };
192
- if (raw.error !== void 0) throw fromApiError(raw.error, context);
193
- if ("data" in raw) return raw.data;
194
- throw new SamvaTransportError(result, context);
195
- }
196
- function createDirectService(service) {
197
- const direct = {};
198
- for (const [key, value] of Object.entries(service)) if (typeof value === "function") direct[key] = value.length >= 2 ? (parameters = {}, options = {}) => unwrap(value, [parameters, directOptions(options)]) : (options = {}) => unwrap(value, [directOptions(options)]);
199
- else if (isObject(value)) direct[key] = createDirectService(value);
200
- else direct[key] = value;
201
- return direct;
202
- }
203
- /** Create a configured Promise client. */
204
- function createClient(config) {
205
- const authHeaders = config.authToken !== void 0 ? { Authorization: `Bearer ${config.authToken}` } : { "X-API-Key": config.apiKey };
206
- const clientInstance = createClient$1({
207
- ...config,
208
- baseUrl: config.baseUrl ?? "https://api.samva.dev",
209
- headers: mergeHeaders({ [CLIENT_ATTRIBUTION_HEADER]: clientAttribution("typescript-promise") }, config.headers, authHeaders),
210
- responseStyle: "fields",
211
- throwOnError: false
212
- });
213
- clientInstance.interceptors.request.use((request) => {
214
- const headers = new Headers(request.headers);
215
- for (const [name, value] of Object.entries(authHeaders)) headers.set(name, value);
216
- return new Request(request, { headers });
217
- });
218
- const raw = {
219
- client: clientInstance,
220
- messages: createBoundService(Messages, clientInstance),
221
- scheduledMessages: createBoundService(ScheduledMessages, clientInstance),
222
- brands: createBoundService(Brands, clientInstance),
223
- campaigns: createBoundService(Campaigns, clientInstance),
224
- email: createBoundService(Email, clientInstance),
225
- media: createBoundService(Media, clientInstance),
226
- templates: createPromiseTemplatesTransport(clientInstance),
227
- contacts: Object.assign(createBoundService(Contacts, clientInstance), createBoundService(ContactEvents, clientInstance)),
228
- events: createBoundService(Events, clientInstance),
229
- conversations: createBoundService(Conversations, clientInstance),
230
- webhooks: createBoundService(Webhooks, clientInstance),
231
- operations: createBoundService(Operations, clientInstance),
232
- apiKeys: createBoundService(ApiKeys, clientInstance),
233
- organizations: createBoundService(Organizations, clientInstance),
234
- attachments: createBoundService(Attachments, clientInstance),
235
- contactGroups: createBoundService(ContactGroups, clientInstance),
236
- customFields: createBoundService(CustomFields, clientInstance),
237
- subscriptions: createBoundService(Subscriptions, clientInstance),
238
- topics: createBoundService(Topics, clientInstance),
239
- topicForms: createBoundService(TopicForms, clientInstance),
240
- topicIssues: createBoundService(TopicIssues, clientInstance),
241
- topicPublicationDomains: createBoundService(TopicPublicationDomains, clientInstance),
242
- agents: createBoundService(Agents, clientInstance),
243
- analytics: createBoundService(Analytics, clientInstance),
244
- feedback: createBoundService(Feedback, clientInstance),
245
- whoami: createBoundService(Whoami, clientInstance),
246
- journeys: createBoundService(Journeys, clientInstance),
247
- mailboxes: createBoundService(Mailboxes, clientInstance),
248
- namespaces: createBoundService(Namespaces, clientInstance),
249
- extensions: createBoundService(Extensions, clientInstance),
250
- extensionInstallations: createBoundService(ExtensionInstallations, clientInstance)
251
- };
252
- const streamConnection = {
253
- baseUrl: config.baseUrl ?? "https://api.samva.dev",
254
- headers: async () => Object.fromEntries(mergeHeaders({ [CLIENT_ATTRIBUTION_HEADER]: clientAttribution("typescript-promise") }, config.headers, authHeaders).entries()),
255
- fetch: config.fetch
256
- };
257
- const promiseMessages = createPromiseMessagesTransport(clientInstance);
258
- const promiseEmail = createPromiseEmailTransport(clientInstance);
259
- return {
260
- raw,
261
- messages: createDirectService(promiseMessages),
262
- scheduledMessages: createDirectService(raw.scheduledMessages),
263
- brands: createDirectService(raw.brands),
264
- campaigns: createDirectService(raw.campaigns),
265
- email: createDirectService(promiseEmail),
266
- media: createDirectService(raw.media),
267
- templates: createDirectService(raw.templates),
268
- contacts: createDirectService(raw.contacts),
269
- events: createDirectService(raw.events),
270
- conversations: createDirectService(raw.conversations),
271
- webhooks: createDirectService(raw.webhooks),
272
- operations: createDirectService(raw.operations),
273
- apiKeys: createDirectService(raw.apiKeys),
274
- organizations: createDirectService(raw.organizations),
275
- attachments: createDirectService(raw.attachments),
276
- contactGroups: createDirectService(raw.contactGroups),
277
- customFields: createDirectService(raw.customFields),
278
- subscriptions: createDirectService(raw.subscriptions),
279
- topics: createDirectService(raw.topics),
280
- topicForms: createDirectService(raw.topicForms),
281
- topicIssues: createDirectService(raw.topicIssues),
282
- topicPublicationDomains: createDirectService(raw.topicPublicationDomains),
283
- agents: createDirectService(raw.agents),
284
- analytics: createDirectService(raw.analytics),
285
- feedback: createDirectService(raw.feedback),
286
- whoami: createDirectService(raw.whoami),
287
- journeys: createDirectService(raw.journeys),
288
- mailboxes: Object.assign(createDirectService(raw.mailboxes), { events: (options) => new MailboxEventStream(streamConnection, options) }),
289
- namespaces: createDirectService(raw.namespaces),
290
- extensions: createDirectService(raw.extensions),
291
- extensionInstallations: createDirectService(raw.extensionInstallations)
292
- };
293
- }
294
- //#endregion
2
+ import { MediaUploadError } from "../inline-attachments.js";
3
+ import { MailboxEventStream, MailboxEventStreamError } from "../mailbox-events.js";
4
+ import { createClient } from "./client.js";
295
5
  export { AnalyticsQueryError, BillingProviderError, BrandAddressRequiredError, CampaignFooterRequiredError, ConflictError, DeliveryUnavailableError, EmailChannelError, ExternalServiceError, FlagDisabledError, ForbiddenError, FromAddressRequiredError, GatewayTimeoutError, InternalError, MailboxEventStream, MailboxEventStreamError, MailboxSendConflictError, MailboxSendRefusedError, MediaUploadError, OnboardingReviewRequiredError, PaymentRequiredError, RateLimitedError, ResourceNotFoundError, SamvaApiError, SamvaTransportError, SenderNotReadyError, TemplateSourceError, UnauthorizedError, ValidationError, createClient, fromApiError };
296
-
297
- //# sourceMappingURL=index.js.map
@@ -0,0 +1,15 @@
1
+ import { type Client, mergeHeaders } from "../client/client";
2
+ import { SamvaOperations } from "../effect/generated-metadata";
3
+ export interface RequestPolicy {
4
+ readonly maxRetries?: number | undefined;
5
+ readonly idempotency?: ((operation: string) => string) | undefined;
6
+ }
7
+ export interface CallOptions {
8
+ readonly idempotencyKey?: string | undefined;
9
+ readonly maxRetries?: number | undefined;
10
+ readonly headers?: Parameters<typeof mergeHeaders>[0];
11
+ readonly signal?: AbortSignal | null | undefined;
12
+ }
13
+ export declare const configureRequests: (client: Client, policy: RequestPolicy) => void;
14
+ /** The key belongs to a logical call, so all attempts share it and each invocation gets a fresh one. */
15
+ export declare function requestWithPolicy<Result>(client: Client, operation: keyof typeof SamvaOperations, options: CallOptions | undefined, send: (headers: Record<string, string | null | undefined>) => Promise<Result>, input?: unknown): Promise<Result>;
@@ -0,0 +1,75 @@
1
+ import { mergeHeaders } from "../client/client/utils.gen.js";
2
+ import { SamvaErrorMetadata, SamvaOperations } from "../effect/generated-metadata.js";
3
+ import { isRetrySafe } from "../request-policy.js";
4
+ import { SamvaTransportError, fromApiError } from "./errors.gen.js";
5
+ // src/promises/request.ts
6
+ const policies = /* @__PURE__ */ new WeakMap();
7
+ const configureRequests = (client, policy) => {
8
+ if (policy.maxRetries !== void 0) validateRetries(policy.maxRetries);
9
+ policies.set(client, policy);
10
+ };
11
+ const validateRetries = (value) => {
12
+ if (!Number.isInteger(value) || value < 0) throw new RangeError("maxRetries must be a nonnegative integer");
13
+ return value;
14
+ };
15
+ const object = (value) => typeof value === "object" && value !== null;
16
+ const retryable = (error) => {
17
+ if (error instanceof SamvaTransportError) return error.response === void 0 && error.cause instanceof TypeError;
18
+ if (!object(error) || typeof error._tag !== "string") return false;
19
+ if (error._tag === "EmailChannelError") return error.reason === "transport" || error.reason === "rate_limited";
20
+ return SamvaErrorMetadata[error._tag]?.retryable === true;
21
+ };
22
+ const delay = (error, retry) => {
23
+ if (object(error) && error._tag === "RateLimitedError" && typeof error.retryAfterSeconds === "number" && Number.isFinite(error.retryAfterSeconds) && error.retryAfterSeconds >= 0) return Math.min(error.retryAfterSeconds, 60) * 1e3;
24
+ return 200 * 2 ** retry * (.8 + Math.random() * .4);
25
+ };
26
+ const pause = (milliseconds, signal) => new Promise((resolve, reject) => {
27
+ signal?.throwIfAborted();
28
+ const abort = () => {
29
+ clearTimeout(timer);
30
+ reject(signal?.reason);
31
+ };
32
+ const timer = setTimeout(() => {
33
+ signal?.removeEventListener("abort", abort);
34
+ resolve();
35
+ }, milliseconds);
36
+ signal?.addEventListener("abort", abort, { once: true });
37
+ });
38
+ /** The key belongs to a logical call, so all attempts share it and each invocation gets a fresh one. */
39
+ async function requestWithPolicy(client, operation, options, send, input) {
40
+ const metadata = SamvaOperations[operation];
41
+ const policy = policies.get(client);
42
+ const signal = options?.signal ?? client.getConfig().signal;
43
+ const headers = Object.fromEntries(mergeHeaders(client.getConfig().headers, options?.headers));
44
+ if (options?.headers !== void 0 && !(options.headers instanceof Headers) && !Array.isArray(options.headers)) {
45
+ for (const [name, value] of Object.entries(options.headers)) if (value === null) headers[name] = null;
46
+ }
47
+ if (metadata.idempotent) {
48
+ for (const name of Object.keys(headers)) if (name.toLowerCase() === "idempotency-key") delete headers[name];
49
+ headers["idempotency-key"] = options?.idempotencyKey ?? policy?.idempotency?.(operation) ?? crypto.randomUUID();
50
+ }
51
+ const maxRetries = validateRetries(options?.maxRetries ?? policy?.maxRetries ?? 3);
52
+ const safe = isRetrySafe(operation, input);
53
+ for (let retry = 0;; retry++) {
54
+ let failure;
55
+ let result;
56
+ try {
57
+ result = await send(headers);
58
+ if (!object(result) || result.error === void 0) return result;
59
+ failure = fromApiError(result.error, {
60
+ request: result.request instanceof Request ? result.request : void 0,
61
+ response: result.response instanceof Response ? result.response : void 0
62
+ });
63
+ } catch (error) {
64
+ failure = fromApiError(error);
65
+ if (!safe || retry >= maxRetries || !retryable(failure) || signal?.aborted) throw error;
66
+ await pause(delay(failure, retry), signal);
67
+ continue;
68
+ }
69
+ if (!safe || retry >= maxRetries || !retryable(failure) || signal?.aborted) return result;
70
+ await pause(delay(failure, retry), signal);
71
+ }
72
+ }
73
+ export { configureRequests, requestWithPolicy };
74
+
75
+ //# sourceMappingURL=request.js.map