@replicer/sdk 0.0.0-stage → 0.1.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.js ADDED
@@ -0,0 +1,269 @@
1
+ // src/errors.ts
2
+ var ReplicerError = class extends Error {
3
+ /** HTTP status code (0 when the request never produced a response). */
4
+ status;
5
+ /** `body.code` when the API sent one, else `network_error`, `invalid_response` or `http_<status>`. */
6
+ code;
7
+ /** Parsed JSON error body, or the raw response text when it was not JSON. */
8
+ body;
9
+ /** Request path (without the base URL or query string). */
10
+ path;
11
+ /** `x-request-id` response header, when present. */
12
+ requestId;
13
+ /** Seconds to wait before retrying (from `Retry-After` on a 429), when provided. */
14
+ retryAfter;
15
+ constructor(init) {
16
+ super(init.message, init.cause === void 0 ? void 0 : { cause: init.cause });
17
+ this.name = "ReplicerError";
18
+ this.status = init.status;
19
+ this.code = init.code;
20
+ this.body = init.body;
21
+ this.path = init.path ?? "";
22
+ this.requestId = init.requestId;
23
+ this.retryAfter = init.retryAfter;
24
+ }
25
+ /** Best human-readable message: the API's `error` string, else the raw text body, else `message`. */
26
+ get errorMessage() {
27
+ if (this.body && typeof this.body === "object" && typeof this.body.error === "string") {
28
+ return this.body.error;
29
+ }
30
+ if (typeof this.body === "string" && this.body !== "") return this.body;
31
+ return this.message;
32
+ }
33
+ };
34
+
35
+ // src/routes.ts
36
+ var ROUTES = [
37
+ { method: "POST", path: "/v1/create-phone-call", sdk: "call.createPhoneCall" },
38
+ { method: "POST", path: "/v1/cancel-call", sdk: "call.cancel" },
39
+ { method: "POST", path: "/v1/cancel-campaign-pending", sdk: "call.cancelCampaignPending" },
40
+ { method: "GET", path: "/v1/list-calls", sdk: "call.list" },
41
+ { method: "GET", path: "/v1/get-call/:id", sdk: "call.get" },
42
+ { method: "POST", path: "/v1/campaigns", sdk: "campaign.create" },
43
+ { method: "GET", path: "/v1/campaigns/:id", sdk: "campaign.get" },
44
+ { method: "GET", path: "/v1/list-campaigns", sdk: "campaign.list" },
45
+ { method: "POST", path: "/v1/start-campaign/:id", sdk: "campaign.start" },
46
+ { method: "GET", path: "/v1/list-phone-numbers", sdk: "phoneNumber.list" },
47
+ { method: "POST", path: "/v1/phone-numbers/inbound", sdk: "phoneNumber.provisionInbound" },
48
+ { method: "DELETE", path: "/v1/phone-numbers/inbound/:id", sdk: "phoneNumber.deprovisionInbound" },
49
+ { method: "POST", path: "/v1/create-knowledge-base", sdk: "knowledgeBase.create" },
50
+ { method: "GET", path: "/v1/get-knowledge-base/:id", sdk: "knowledgeBase.retrieve" },
51
+ { method: "GET", path: "/v1/list-knowledge-bases", sdk: "knowledgeBase.list" },
52
+ { method: "DELETE", path: "/v1/delete-knowledge-base/:id", sdk: "knowledgeBase.delete" },
53
+ { method: "POST", path: "/v1/add-knowledge-base-sources/:id", sdk: "knowledgeBase.addSources" },
54
+ { method: "DELETE", path: "/v1/delete-knowledge-base-source/:source_id", sdk: "knowledgeBase.deleteSource" },
55
+ { method: "PATCH", path: "/v1/update-knowledge-base/:id", sdk: "knowledgeBase.update" },
56
+ { method: "POST", path: "/v1/presign-knowledge-base-file/:id", sdk: "knowledgeBase.presignFile" },
57
+ { method: "POST", path: "/v1/complete-knowledge-base-file/:id/:source_id", sdk: "knowledgeBase.completeFile" },
58
+ { method: "POST", path: "/v1/fail-knowledge-base-file/:id/:source_id", sdk: "knowledgeBase.failFile" },
59
+ { method: "PUT", path: "/v1/reindex-knowledge-base/:id", sdk: "knowledgeBase.reindex" },
60
+ { method: "PATCH", path: "/v1/update-knowledge-base-source/:id/:source_id", sdk: "knowledgeBase.updateSource" },
61
+ { method: "PATCH", path: "/v1/update-knowledge-base-chunk/:id/:chunk_id", sdk: "knowledgeBase.updateChunk" },
62
+ { method: "GET", path: "/v1/get-knowledge-base-source/:id/:source_id", sdk: "knowledgeBase.getSource" },
63
+ { method: "GET", path: "/v1/presign-knowledge-base-file-download/:id/:source_id", sdk: "knowledgeBase.presignFileDownload" },
64
+ { method: "GET", path: "/v1/list-contacts", sdk: "contact.list" },
65
+ { method: "POST", path: "/v1/create-contact", sdk: "contact.create" },
66
+ { method: "GET", path: "/v1/list-agents", sdk: "agent.list" },
67
+ { method: "GET", path: "/v1/list-calendar-events", sdk: "calendar.listEvents" },
68
+ { method: "POST", path: "/v1/create-calendar-event", sdk: "calendar.createEvent" },
69
+ { method: "GET", path: "/v1/list-messages", sdk: "message.list" },
70
+ { method: "POST", path: "/v1/send-sms", sdk: "message.sendSms" },
71
+ { method: "POST", path: "/v1/send-whatsapp", sdk: "message.sendWhatsapp" },
72
+ { method: "POST", path: "/v1/send-email", sdk: "message.sendEmail" },
73
+ { method: "POST", path: "/v1/create-tts", sdk: "tts.create" },
74
+ { method: "GET", path: "/v1/list-tts", sdk: "tts.list" },
75
+ { method: "GET", path: "/v1/get-tts/:id", sdk: "tts.get" }
76
+ ];
77
+
78
+ // src/client.ts
79
+ var DEFAULT_BASE_URL = "https://api.replicer.ai";
80
+ var ROUTE_BY_SDK = new Map(ROUTES.map((r) => [r.sdk, r]));
81
+ var Replicer = class {
82
+ apiKey;
83
+ baseURL;
84
+ fetchImpl;
85
+ constructor(options) {
86
+ if (!options || typeof options.apiKey !== "string" || options.apiKey.trim() === "") {
87
+ throw new TypeError("Replicer: `apiKey` is required");
88
+ }
89
+ const impl = options.fetch ?? globalThis.fetch;
90
+ if (typeof impl !== "function") {
91
+ throw new TypeError("Replicer: no global `fetch` found; pass one via the `fetch` option");
92
+ }
93
+ this.apiKey = options.apiKey;
94
+ this.baseURL = (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
95
+ this.fetchImpl = impl.bind(globalThis);
96
+ }
97
+ call = {
98
+ createPhoneCall: (input) => this.request("call.createPhoneCall", { body: input }),
99
+ cancel: (call_id) => this.request("call.cancel", { body: { call_id } }),
100
+ cancelCampaignPending: (campaign_id) => this.request("call.cancelCampaignPending", { body: { campaign_id } }),
101
+ list: (params) => this.request("call.list", { query: params }),
102
+ get: (id) => this.request("call.get", { params: { id } })
103
+ };
104
+ campaign = {
105
+ create: (input) => this.request("campaign.create", { body: input }),
106
+ /** Includes up to 1,000 contacts (`contacts_truncated` tells whether there are more). */
107
+ get: (id) => this.request("campaign.get", { params: { id } }),
108
+ list: (params) => this.request("campaign.list", { query: params }),
109
+ /** Starts a campaign, or resumes one paused by `call.cancelCampaignPending`. */
110
+ start: (id) => this.request("campaign.start", { params: { id } })
111
+ };
112
+ phoneNumber = {
113
+ /** Your organization's phone numbers; `id` is the `from_number_id` for `call.createPhoneCall`. */
114
+ list: (params) => this.request("phoneNumber.list", { query: params }),
115
+ provisionInbound: (input) => this.request("phoneNumber.provisionInbound", { body: input }),
116
+ deprovisionInbound: (id, trunk_id, rule_id) => this.request("phoneNumber.deprovisionInbound", { params: { id }, query: { trunk_id, rule_id } })
117
+ };
118
+ knowledgeBase = {
119
+ create: (input) => this.request("knowledgeBase.create", { body: input }),
120
+ retrieve: (knowledgeBaseId) => this.request("knowledgeBase.retrieve", { params: { id: knowledgeBaseId } }),
121
+ list: () => this.request("knowledgeBase.list"),
122
+ delete: (knowledgeBaseId) => this.request("knowledgeBase.delete", { params: { id: knowledgeBaseId } }),
123
+ addSources: (knowledgeBaseId, input) => this.request("knowledgeBase.addSources", { params: { id: knowledgeBaseId }, body: input }),
124
+ deleteSource: (sourceId, knowledgeBaseId) => this.request("knowledgeBase.deleteSource", {
125
+ params: { source_id: sourceId },
126
+ query: { knowledge_base_id: knowledgeBaseId }
127
+ }),
128
+ update: (knowledgeBaseId, input) => this.request("knowledgeBase.update", { params: { id: knowledgeBaseId }, body: input }),
129
+ presignFile: (knowledgeBaseId, input) => this.request("knowledgeBase.presignFile", { params: { id: knowledgeBaseId }, body: input }),
130
+ completeFile: (knowledgeBaseId, sourceId) => this.request("knowledgeBase.completeFile", {
131
+ params: { id: knowledgeBaseId, source_id: sourceId },
132
+ body: {}
133
+ }),
134
+ failFile: (knowledgeBaseId, sourceId, input) => this.request("knowledgeBase.failFile", {
135
+ params: { id: knowledgeBaseId, source_id: sourceId },
136
+ body: input ?? {}
137
+ }),
138
+ reindex: (knowledgeBaseId) => this.request("knowledgeBase.reindex", { params: { id: knowledgeBaseId }, body: {} }),
139
+ updateSource: (knowledgeBaseId, sourceId, input) => this.request("knowledgeBase.updateSource", {
140
+ params: { id: knowledgeBaseId, source_id: sourceId },
141
+ body: input
142
+ }),
143
+ updateChunk: (knowledgeBaseId, chunkId, input) => this.request("knowledgeBase.updateChunk", {
144
+ params: { id: knowledgeBaseId, chunk_id: chunkId },
145
+ body: input
146
+ }),
147
+ getSource: (knowledgeBaseId, sourceId) => this.request("knowledgeBase.getSource", {
148
+ params: { id: knowledgeBaseId, source_id: sourceId }
149
+ }),
150
+ presignFileDownload: (knowledgeBaseId, sourceId) => this.request("knowledgeBase.presignFileDownload", {
151
+ params: { id: knowledgeBaseId, source_id: sourceId }
152
+ })
153
+ };
154
+ contact = {
155
+ list: (params) => this.request("contact.list", { query: params }),
156
+ create: (input) => this.request("contact.create", { body: input })
157
+ };
158
+ agent = {
159
+ list: (params) => this.request("agent.list", { query: params })
160
+ };
161
+ calendar = {
162
+ listEvents: (params) => this.request("calendar.listEvents", { query: params }),
163
+ createEvent: (input) => this.request("calendar.createEvent", { body: input })
164
+ };
165
+ message = {
166
+ list: (params) => this.request("message.list", { query: params }),
167
+ sendSms: (input) => this.request("message.sendSms", { body: input }),
168
+ sendWhatsapp: (input) => this.request("message.sendWhatsapp", { body: input }),
169
+ sendEmail: (input) => this.request("message.sendEmail", { body: input })
170
+ };
171
+ tts = {
172
+ create: (input) => this.request("tts.create", { body: input }),
173
+ list: (params) => this.request("tts.list", { query: params }),
174
+ get: (id) => this.request("tts.get", { params: { id } })
175
+ };
176
+ async request(sdk, opts = {}) {
177
+ const route = ROUTE_BY_SDK.get(sdk);
178
+ if (!route) throw new Error(`Replicer: unknown route ${sdk}`);
179
+ const params = opts.params ?? {};
180
+ const path = route.path.replace(/:([A-Za-z_]+)/g, (_m, name) => {
181
+ const value = params[name];
182
+ if (typeof value !== "string" || value === "" || value === "." || value === "..") {
183
+ throw new ReplicerError({
184
+ status: 0,
185
+ code: "validation_error",
186
+ message: `Replicer: invalid \`${name}\` path parameter`,
187
+ path: route.path
188
+ });
189
+ }
190
+ return encodeURIComponent(value);
191
+ });
192
+ const qs = buildQuery(opts.query);
193
+ const url = `${this.baseURL}${path}${qs ? `?${qs}` : ""}`;
194
+ const headers = {
195
+ authorization: `Bearer ${this.apiKey}`,
196
+ accept: "application/json"
197
+ };
198
+ let body;
199
+ if (opts.body !== void 0) {
200
+ headers["content-type"] = "application/json";
201
+ body = JSON.stringify(opts.body);
202
+ }
203
+ let res;
204
+ try {
205
+ res = await this.fetchImpl(url, { method: route.method, headers, body });
206
+ } catch (cause) {
207
+ throw new ReplicerError({
208
+ status: 0,
209
+ code: "network_error",
210
+ message: `Request to ${route.method} ${path} failed: ${cause instanceof Error ? cause.message : String(cause)}`,
211
+ path,
212
+ cause
213
+ });
214
+ }
215
+ const requestId = res.headers.get("x-request-id") ?? void 0;
216
+ const text = await res.text();
217
+ let parsed;
218
+ let isJson = false;
219
+ if (text) {
220
+ try {
221
+ parsed = JSON.parse(text);
222
+ isJson = true;
223
+ } catch {
224
+ isJson = false;
225
+ }
226
+ }
227
+ if (!res.ok) {
228
+ const errBody = isJson && parsed && typeof parsed === "object" ? parsed : void 0;
229
+ const retryAfterRaw = res.headers.get("retry-after");
230
+ const retryAfter = retryAfterRaw !== null && retryAfterRaw.trim() !== "" && Number.isFinite(Number(retryAfterRaw)) ? Number(retryAfterRaw) : void 0;
231
+ throw new ReplicerError({
232
+ status: res.status,
233
+ code: typeof errBody?.code === "string" && errBody.code ? errBody.code : `http_${res.status}`,
234
+ message: typeof errBody?.error === "string" && errBody.error ? errBody.error : text || res.statusText || `HTTP ${res.status}`,
235
+ body: isJson ? parsed : text,
236
+ path,
237
+ requestId,
238
+ retryAfter
239
+ });
240
+ }
241
+ if (res.status === 204) return void 0;
242
+ if (!isJson) {
243
+ throw new ReplicerError({
244
+ status: res.status,
245
+ code: "invalid_response",
246
+ message: `Expected a JSON response from ${route.method} ${path}`,
247
+ body: text,
248
+ path,
249
+ requestId
250
+ });
251
+ }
252
+ return parsed;
253
+ }
254
+ };
255
+ function buildQuery(query) {
256
+ if (!query) return "";
257
+ const params = new URLSearchParams();
258
+ for (const [key, value] of Object.entries(query)) {
259
+ if (value === void 0 || value === null) continue;
260
+ params.set(key, String(value));
261
+ }
262
+ return params.toString();
263
+ }
264
+ export {
265
+ DEFAULT_BASE_URL,
266
+ ROUTES,
267
+ Replicer,
268
+ ReplicerError
269
+ };
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/webhooks.ts
21
+ var webhooks_exports = {};
22
+ __export(webhooks_exports, {
23
+ verifyWebhookSignature: () => verifyWebhookSignature
24
+ });
25
+ module.exports = __toCommonJS(webhooks_exports);
26
+ var import_node_crypto = require("crypto");
27
+ var SIGNATURE_PREFIX = "sha256=";
28
+ var HEX_SHA256 = /^[0-9a-f]{64}$/;
29
+ function verifyWebhookSignature({ payload, signature, secret }) {
30
+ if (typeof signature !== "string" || !secret) return false;
31
+ let hex = signature.trim();
32
+ if (hex.slice(0, SIGNATURE_PREFIX.length).toLowerCase() === SIGNATURE_PREFIX) {
33
+ hex = hex.slice(SIGNATURE_PREFIX.length);
34
+ }
35
+ hex = hex.toLowerCase();
36
+ if (!HEX_SHA256.test(hex)) return false;
37
+ const expected = (0, import_node_crypto.createHmac)("sha256", secret).update(payload).digest();
38
+ const received = Buffer.from(hex, "hex");
39
+ if (received.length !== expected.length) return false;
40
+ return (0, import_node_crypto.timingSafeEqual)(expected, received);
41
+ }
42
+ // Annotate the CommonJS export names for ESM import in node:
43
+ 0 && (module.exports = {
44
+ verifyWebhookSignature
45
+ });
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Server-only webhook helpers. Import from `@replicer/sdk/webhooks`; the main entry stays free of
3
+ * `node:` imports so it bundles for edge runtimes and browsers.
4
+ */
5
+ interface VerifyWebhookSignatureInput {
6
+ /** The exact request body as received (do not re-serialize parsed JSON). */
7
+ payload: string | Uint8Array;
8
+ /** Value of the `X-Replicer-Signature` header: `sha256=<hex>` (a bare hex digest is also accepted). */
9
+ signature: string | null | undefined;
10
+ /** The endpoint signing secret. */
11
+ secret: string;
12
+ }
13
+ /**
14
+ * Verify the `X-Replicer-Signature` header of a webhook delivery (HMAC-SHA256 over the raw body,
15
+ * compared in constant time). Returns `false`, never throws, for a missing, malformed or
16
+ * wrong-length signature.
17
+ *
18
+ * The `X-Replicer-Timestamp` header is NOT covered by the signature: for replay protection,
19
+ * de-duplicate on `X-Replicer-Delivery-Id` / the event id instead of relying on the timestamp.
20
+ */
21
+ declare function verifyWebhookSignature({ payload, signature, secret }: VerifyWebhookSignatureInput): boolean;
22
+
23
+ export { type VerifyWebhookSignatureInput, verifyWebhookSignature };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Server-only webhook helpers. Import from `@replicer/sdk/webhooks`; the main entry stays free of
3
+ * `node:` imports so it bundles for edge runtimes and browsers.
4
+ */
5
+ interface VerifyWebhookSignatureInput {
6
+ /** The exact request body as received (do not re-serialize parsed JSON). */
7
+ payload: string | Uint8Array;
8
+ /** Value of the `X-Replicer-Signature` header: `sha256=<hex>` (a bare hex digest is also accepted). */
9
+ signature: string | null | undefined;
10
+ /** The endpoint signing secret. */
11
+ secret: string;
12
+ }
13
+ /**
14
+ * Verify the `X-Replicer-Signature` header of a webhook delivery (HMAC-SHA256 over the raw body,
15
+ * compared in constant time). Returns `false`, never throws, for a missing, malformed or
16
+ * wrong-length signature.
17
+ *
18
+ * The `X-Replicer-Timestamp` header is NOT covered by the signature: for replay protection,
19
+ * de-duplicate on `X-Replicer-Delivery-Id` / the event id instead of relying on the timestamp.
20
+ */
21
+ declare function verifyWebhookSignature({ payload, signature, secret }: VerifyWebhookSignatureInput): boolean;
22
+
23
+ export { type VerifyWebhookSignatureInput, verifyWebhookSignature };
@@ -0,0 +1,20 @@
1
+ // src/webhooks.ts
2
+ import { createHmac, timingSafeEqual } from "crypto";
3
+ var SIGNATURE_PREFIX = "sha256=";
4
+ var HEX_SHA256 = /^[0-9a-f]{64}$/;
5
+ function verifyWebhookSignature({ payload, signature, secret }) {
6
+ if (typeof signature !== "string" || !secret) return false;
7
+ let hex = signature.trim();
8
+ if (hex.slice(0, SIGNATURE_PREFIX.length).toLowerCase() === SIGNATURE_PREFIX) {
9
+ hex = hex.slice(SIGNATURE_PREFIX.length);
10
+ }
11
+ hex = hex.toLowerCase();
12
+ if (!HEX_SHA256.test(hex)) return false;
13
+ const expected = createHmac("sha256", secret).update(payload).digest();
14
+ const received = Buffer.from(hex, "hex");
15
+ if (received.length !== expected.length) return false;
16
+ return timingSafeEqual(expected, received);
17
+ }
18
+ export {
19
+ verifyWebhookSignature
20
+ };
package/package.json CHANGED
@@ -1,6 +1,74 @@
1
1
  {
2
2
  "name": "@replicer/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Typed JavaScript/TypeScript client for the Replicer API: calls, campaigns, knowledge bases, contacts, calendar, messages and TTS.",
5
+ "keywords": [
6
+ "replicer",
7
+ "sdk",
8
+ "voice",
9
+ "ai",
10
+ "calls",
11
+ "campaigns",
12
+ "knowledge-base",
13
+ "api"
14
+ ],
15
+ "license": "MIT",
16
+ "homepage": "https://docs.replicer.ai",
17
+ "type": "module",
18
+ "sideEffects": false,
19
+ "main": "./dist/index.cjs",
20
+ "module": "./dist/index.js",
21
+ "types": "./dist/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "import": {
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
27
+ },
28
+ "require": {
29
+ "types": "./dist/index.d.cts",
30
+ "default": "./dist/index.cjs"
31
+ }
32
+ },
33
+ "./webhooks": {
34
+ "import": {
35
+ "types": "./dist/webhooks.d.ts",
36
+ "default": "./dist/webhooks.js"
37
+ },
38
+ "require": {
39
+ "types": "./dist/webhooks.d.cts",
40
+ "default": "./dist/webhooks.cjs"
41
+ }
42
+ },
43
+ "./package.json": "./package.json"
44
+ },
45
+ "typesVersions": {
46
+ "*": {
47
+ "webhooks": [
48
+ "./dist/webhooks.d.ts"
49
+ ]
50
+ }
51
+ },
52
+ "files": [
53
+ "dist",
54
+ "README.md",
55
+ "LICENSE"
56
+ ],
57
+ "engines": {
58
+ "node": ">=18"
59
+ },
60
+ "publishConfig": {
61
+ "access": "public"
62
+ },
63
+ "devDependencies": {
64
+ "@types/node": "^22.10.0",
65
+ "tsup": "^8.3.5",
66
+ "typescript": "^5.7.0",
67
+ "vitest": "^4.0.18"
68
+ },
69
+ "scripts": {
70
+ "build": "tsup",
71
+ "typecheck": "tsc -p tsconfig.json --noEmit",
72
+ "test": "vitest run"
73
+ }
6
74
  }