memorysync-sdk 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,45 +1,449 @@
1
- // src/index.ts
1
+ // src/errors.ts
2
2
  var MemorySyncError = class extends Error {
3
- constructor(message, opts = {}) {
3
+ constructor(message, options = {}) {
4
4
  super(message);
5
5
  this.name = "MemorySyncError";
6
- this.statusCode = opts.statusCode;
7
- this.response = opts.response;
8
- this.requestId = opts.requestId;
6
+ this.statusCode = options.statusCode;
7
+ this.response = options.response;
8
+ this.requestId = options.requestId;
9
9
  }
10
10
  };
11
11
  var AuthError = class extends MemorySyncError {
12
- constructor(message, opts) {
13
- super(message, opts);
12
+ constructor(message, options) {
13
+ super(message, options);
14
14
  this.name = "AuthError";
15
15
  }
16
16
  };
17
17
  var ValidationError = class extends MemorySyncError {
18
- constructor(message, opts) {
19
- super(message, opts);
18
+ constructor(message, options) {
19
+ super(message, options);
20
20
  this.name = "ValidationError";
21
21
  }
22
22
  };
23
23
  var NotFoundError = class extends MemorySyncError {
24
- constructor(message, opts) {
25
- super(message, opts);
24
+ constructor(message, options) {
25
+ super(message, options);
26
26
  this.name = "NotFoundError";
27
27
  }
28
28
  };
29
29
  var RateLimitError = class extends MemorySyncError {
30
- constructor(message, retryAfterSeconds, opts) {
31
- super(message, opts);
30
+ constructor(message, retryAfterSeconds, options) {
31
+ super(message, options);
32
32
  this.name = "RateLimitError";
33
33
  this.retryAfterSeconds = retryAfterSeconds;
34
34
  }
35
35
  };
36
36
  var ServerError = class extends MemorySyncError {
37
- constructor(message, opts) {
38
- super(message, opts);
37
+ constructor(message, options) {
38
+ super(message, options);
39
39
  this.name = "ServerError";
40
40
  }
41
41
  };
42
- var SDK_VERSION = "1.0.1";
42
+
43
+ // src/control-plane.ts
44
+ var SDK_VERSION = "1.1.0";
45
+ function safeJson(text) {
46
+ try {
47
+ return JSON.parse(text);
48
+ } catch {
49
+ return text;
50
+ }
51
+ }
52
+ function extractDetail(body) {
53
+ if (!body || typeof body !== "object") return void 0;
54
+ const value = body;
55
+ if (typeof value.detail === "string") return value.detail;
56
+ if (value.error && typeof value.error === "object") {
57
+ const error = value.error;
58
+ if (typeof error.message === "string") return error.message;
59
+ }
60
+ if (Array.isArray(value.detail) && value.detail.length > 0) {
61
+ const first = value.detail[0];
62
+ if (first && typeof first === "object" && typeof first.msg === "string") {
63
+ return first.msg;
64
+ }
65
+ }
66
+ return void 0;
67
+ }
68
+ function extractBodyRetryAfter(body) {
69
+ if (!body || typeof body !== "object") return 0;
70
+ const value = body;
71
+ if (typeof value.retry_after === "number") return value.retry_after;
72
+ if (value.error && typeof value.error === "object") {
73
+ const retryAfter = value.error.retry_after;
74
+ if (typeof retryAfter === "number") return retryAfter;
75
+ }
76
+ return 0;
77
+ }
78
+ function parseRetryAfter(value) {
79
+ if (!value) return void 0;
80
+ const seconds = Number(value);
81
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds;
82
+ const date = Date.parse(value);
83
+ if (Number.isNaN(date)) return void 0;
84
+ return Math.max(0, Math.ceil((date - Date.now()) / 1e3));
85
+ }
86
+ function snakeToCamel(key) {
87
+ return key.replace(/_([a-z0-9])/g, (_, character) => character.toUpperCase());
88
+ }
89
+ var OPAQUE_RESPONSE_KEYS = /* @__PURE__ */ new Set(["payload", "metadata", "geo", "configuration"]);
90
+ function normalizeResponse(value) {
91
+ if (Array.isArray(value)) return value.map(normalizeResponse);
92
+ if (!value || typeof value !== "object") return value;
93
+ const normalized = {};
94
+ for (const [key, item] of Object.entries(value)) {
95
+ const camelKey = snakeToCamel(key);
96
+ normalized[camelKey] = OPAQUE_RESPONSE_KEYS.has(camelKey) ? item : normalizeResponse(item);
97
+ }
98
+ return normalized;
99
+ }
100
+ function queryString(values) {
101
+ const params = new URLSearchParams();
102
+ for (const [key, value] of Object.entries(values)) {
103
+ if (value !== void 0 && value !== null) params.set(key, String(value));
104
+ }
105
+ const encoded = params.toString();
106
+ return encoded ? `?${encoded}` : "";
107
+ }
108
+ function positiveId(value, name) {
109
+ if (!Number.isInteger(value) || value <= 0) {
110
+ throw new ValidationError(`${name} must be a positive integer`);
111
+ }
112
+ }
113
+ function nonEmpty(value, name) {
114
+ if (!value.trim()) throw new ValidationError(`${name} must not be empty`);
115
+ }
116
+ function webhookRetryConfig(config) {
117
+ const wire = {};
118
+ if (config.enabled !== void 0) wire.enabled = config.enabled;
119
+ if (config.maxRetries !== void 0) wire.max_retries = config.maxRetries;
120
+ if (config.initialDelaySeconds !== void 0) wire.initial_delay_seconds = config.initialDelaySeconds;
121
+ if (config.maxDelaySeconds !== void 0) wire.max_delay_seconds = config.maxDelaySeconds;
122
+ if (config.backoffMultiplier !== void 0) wire.backoff_multiplier = config.backoffMultiplier;
123
+ if (config.retryStatusCodes !== void 0) wire.retry_status_codes = config.retryStatusCodes;
124
+ return wire;
125
+ }
126
+ function webhookSignatureConfig(config) {
127
+ const wire = {};
128
+ if (config.algorithm !== void 0) wire.algorithm = config.algorithm;
129
+ if (config.headerName !== void 0) wire.header_name = config.headerName;
130
+ if (config.timestampHeader !== void 0) wire.timestamp_header = config.timestampHeader;
131
+ if (config.toleranceSeconds !== void 0) wire.tolerance_seconds = config.toleranceSeconds;
132
+ return wire;
133
+ }
134
+ function validateWebhook(name, url, events) {
135
+ nonEmpty(name, "name");
136
+ if (name.length > 128) throw new ValidationError("name may contain at most 128 characters");
137
+ if (!Array.isArray(events) || events.length === 0 || events.some((event) => !event.trim())) {
138
+ throw new ValidationError("events must contain at least one non-empty event type");
139
+ }
140
+ let parsed;
141
+ try {
142
+ parsed = new URL(url);
143
+ } catch {
144
+ throw new ValidationError("url must be a valid HTTP or HTTPS URL");
145
+ }
146
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
147
+ throw new ValidationError("url must be a valid HTTP or HTTPS URL");
148
+ }
149
+ if (parsed.username || parsed.password) throw new ValidationError("url must not contain credentials");
150
+ }
151
+ var ControlPlaneClient = class {
152
+ constructor(config) {
153
+ if (!config.baseUrl?.trim()) throw new ValidationError("baseUrl is required");
154
+ let parsed;
155
+ try {
156
+ parsed = new URL(config.baseUrl);
157
+ } catch {
158
+ throw new ValidationError("baseUrl must be an absolute HTTP or HTTPS URL");
159
+ }
160
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
161
+ throw new ValidationError("baseUrl must be an absolute HTTP or HTTPS URL");
162
+ }
163
+ if (config.accessToken !== void 0 && !config.accessToken.trim()) {
164
+ throw new ValidationError("accessToken must not be empty when provided");
165
+ }
166
+ if (config.projectId !== void 0 && !config.projectId.trim()) {
167
+ throw new ValidationError("projectId must not be empty when provided");
168
+ }
169
+ if (config.timeoutMs !== void 0 && (!Number.isFinite(config.timeoutMs) || config.timeoutMs <= 0)) {
170
+ throw new ValidationError("timeoutMs must be greater than zero");
171
+ }
172
+ this.baseUrl = config.baseUrl.replace(/\/+$/, "");
173
+ this.accessToken = config.accessToken?.trim();
174
+ this.projectId = config.projectId?.trim();
175
+ this.timeoutMs = config.timeoutMs ?? 3e4;
176
+ const implementation = config.fetch ?? (typeof fetch !== "undefined" ? fetch : void 0);
177
+ if (!implementation) {
178
+ throw new Error("No fetch implementation available. Pass `fetch` in config or use Node 18+.");
179
+ }
180
+ this.fetchImpl = implementation;
181
+ }
182
+ async request(method, path, options = {}) {
183
+ const requiresAuth = options.auth !== false;
184
+ if (requiresAuth && !this.accessToken) {
185
+ throw new AuthError("accessToken is required for this operation");
186
+ }
187
+ if (options.projectId !== void 0 && !options.projectId.trim()) {
188
+ throw new ValidationError("projectId override must not be empty");
189
+ }
190
+ const headers = {
191
+ Accept: "application/json",
192
+ "User-Agent": `memorysync-sdk-js/${SDK_VERSION}`
193
+ };
194
+ if (requiresAuth) headers.Authorization = `Bearer ${this.accessToken}`;
195
+ const selectedProject = options.projectId?.trim() ?? this.projectId;
196
+ if (selectedProject) headers["X-Project-ID"] = selectedProject;
197
+ if (options.body !== void 0) headers["Content-Type"] = "application/json";
198
+ const controller = new AbortController();
199
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
200
+ try {
201
+ const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
202
+ method,
203
+ headers,
204
+ body: options.body === void 0 ? void 0 : JSON.stringify(options.body),
205
+ signal: controller.signal
206
+ });
207
+ const requestId = response.headers.get("X-Request-ID") ?? void 0;
208
+ if (response.status === 204) return void 0;
209
+ const text = await response.text();
210
+ const parsedBody = text ? safeJson(text) : null;
211
+ if (!response.ok) {
212
+ this.throwForStatus(response.status, parsedBody, requestId, response.headers.get("Retry-After"));
213
+ }
214
+ return normalizeResponse(parsedBody);
215
+ } catch (error) {
216
+ if (error instanceof MemorySyncError) throw error;
217
+ if (error instanceof Error && error.name === "AbortError") {
218
+ throw new MemorySyncError(`Request timed out after ${this.timeoutMs}ms`);
219
+ }
220
+ const message = error instanceof Error ? error.message : String(error);
221
+ throw new MemorySyncError(`Network error: ${message}`);
222
+ } finally {
223
+ clearTimeout(timer);
224
+ }
225
+ }
226
+ throwForStatus(status, body, requestId, retryAfterHeader) {
227
+ const detail = extractDetail(body);
228
+ const options = { statusCode: status, response: body, requestId };
229
+ if (status === 401) throw new AuthError(detail || "Unauthenticated", options);
230
+ if (status === 403) throw new AuthError(detail || "Forbidden", options);
231
+ if (status === 404) throw new NotFoundError(detail || "Not found", options);
232
+ if (status === 400 || status === 409 || status === 422) {
233
+ throw new ValidationError(detail || "Validation error", options);
234
+ }
235
+ if (status === 429) {
236
+ const retryAfter = parseRetryAfter(retryAfterHeader) ?? extractBodyRetryAfter(body);
237
+ throw new RateLimitError(detail || "Rate limited", retryAfter, options);
238
+ }
239
+ if (status >= 500) throw new ServerError(detail || `Server error (${status})`, options);
240
+ throw new MemorySyncError(detail || `Unexpected status ${status}`, options);
241
+ }
242
+ async bulkRevokeApiKeys(request, options = {}) {
243
+ if (!Array.isArray(request.keyIds) || request.keyIds.length < 1 || request.keyIds.length > 100) {
244
+ throw new ValidationError("keyIds must contain between 1 and 100 entries");
245
+ }
246
+ request.keyIds.forEach((id) => positiveId(id, "keyIds entry"));
247
+ return this.request("POST", "/org/api-keys/bulk-revoke", {
248
+ ...options,
249
+ body: { key_ids: request.keyIds }
250
+ });
251
+ }
252
+ async testApiKey(keyId, options = {}) {
253
+ positiveId(keyId, "keyId");
254
+ return this.request("POST", `/org/api-keys/${keyId}/test`, options);
255
+ }
256
+ async login(request, options = {}) {
257
+ nonEmpty(request.email, "email");
258
+ nonEmpty(request.password, "password");
259
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(request.email)) {
260
+ throw new ValidationError("email must be a valid email address");
261
+ }
262
+ return this.request("POST", "/auth/login", {
263
+ ...options,
264
+ auth: false,
265
+ body: { email: request.email, password: request.password }
266
+ });
267
+ }
268
+ async getCurrentPlan(options = {}) {
269
+ return this.request("GET", "/org/billing/current-plan", options);
270
+ }
271
+ async listTeamMembers(options = {}) {
272
+ return this.request("GET", "/admin/team/members", options);
273
+ }
274
+ async suspendTeamMember(memberId, options = {}) {
275
+ positiveId(memberId, "memberId");
276
+ return this.request("PATCH", `/admin/team/members/${memberId}`, {
277
+ ...options,
278
+ body: { status: "suspended" }
279
+ });
280
+ }
281
+ async removeTeamMember(memberId, options = {}) {
282
+ positiveId(memberId, "memberId");
283
+ return this.request("DELETE", `/admin/team/members/${memberId}`, options);
284
+ }
285
+ async listSessions(options = {}) {
286
+ return this.request("GET", "/auth/sessions", options);
287
+ }
288
+ async revokeSession(sessionId, options = {}) {
289
+ positiveId(sessionId, "sessionId");
290
+ return this.request("POST", `/auth/sessions/${sessionId}/revoke`, options);
291
+ }
292
+ async listAuditEvents(query = {}, options = {}) {
293
+ if (query.limit !== void 0) positiveId(query.limit, "limit");
294
+ if (query.cursor !== void 0) positiveId(query.cursor, "cursor");
295
+ if (query.skip !== void 0 && (!Number.isInteger(query.skip) || query.skip < 0)) {
296
+ throw new ValidationError("skip must be a non-negative integer");
297
+ }
298
+ const path = "/admin/audit-logs" + queryString({
299
+ limit: query.limit,
300
+ cursor: query.cursor,
301
+ skip: query.skip,
302
+ sort: query.sortDirection,
303
+ tenant_id: query.tenantId,
304
+ actor: query.actor,
305
+ actor_email: query.actorEmail,
306
+ ip: query.ip,
307
+ action: query.action,
308
+ resource_type: query.resourceType,
309
+ resource_id: query.resourceId,
310
+ severity: query.severity,
311
+ category: query.category,
312
+ start: query.start,
313
+ end: query.end,
314
+ success: query.success,
315
+ source: query.source,
316
+ ingest_method: query.ingestMethod,
317
+ search: query.search
318
+ });
319
+ const raw = await this.request("GET", path, options);
320
+ return {
321
+ events: raw.logs ?? [],
322
+ nextCursor: raw.nextCursor ?? null,
323
+ stats: raw.stats ?? null,
324
+ sort: raw.sort ?? query.sortDirection ?? "desc"
325
+ };
326
+ }
327
+ async listIntegrations(query = {}, options = {}) {
328
+ const path = "/api/v1/integrations/catalog" + queryString({ category: query.category });
329
+ return this.request("GET", path, options);
330
+ }
331
+ async createOrganization(request, options = {}) {
332
+ nonEmpty(request.name, "name");
333
+ if (request.domain !== void 0) nonEmpty(request.domain, "domain");
334
+ const body = { name: request.name };
335
+ if (request.domain !== void 0) body.domain = request.domain;
336
+ return this.request("POST", "/organizations", { ...options, body });
337
+ }
338
+ async listOrganizations(options = {}) {
339
+ return this.request("GET", "/organizations", options);
340
+ }
341
+ async listOrganizationMembers(options = {}) {
342
+ return this.listTeamMembers(options);
343
+ }
344
+ async getOrganizationSettings(query = {}, options = {}) {
345
+ if (query.tenantId !== void 0) nonEmpty(query.tenantId, "tenantId");
346
+ const path = "/admin/tenant-settings" + queryString({ tenant_id: query.tenantId });
347
+ return this.request("GET", path, options);
348
+ }
349
+ async listProjects(options = {}) {
350
+ return this.request("GET", "/org/projects", options);
351
+ }
352
+ async createWebhook(request, options = {}) {
353
+ validateWebhook(request.name, request.url, request.events);
354
+ if (request.description !== void 0 && request.description.length > 500) {
355
+ throw new ValidationError("description may contain at most 500 characters");
356
+ }
357
+ if (request.projectId !== void 0) nonEmpty(request.projectId, "projectId");
358
+ const body = { name: request.name, url: request.url, events: request.events };
359
+ if (request.description !== void 0) body.description = request.description;
360
+ if (request.retryConfig !== void 0) body.retry_config = webhookRetryConfig(request.retryConfig);
361
+ if (request.signatureConfig !== void 0) body.signature_config = webhookSignatureConfig(request.signatureConfig);
362
+ if (request.projectId !== void 0) body.project_id = request.projectId;
363
+ return this.request("POST", "/org/webhooks", { ...options, body });
364
+ }
365
+ async listWebhooks(options = {}) {
366
+ return this.request("GET", "/org/webhooks", options);
367
+ }
368
+ async updateWebhook(endpointId, request, options = {}) {
369
+ positiveId(endpointId, "endpointId");
370
+ const body = {};
371
+ if (request.name !== void 0) {
372
+ nonEmpty(request.name, "name");
373
+ if (request.name.length > 128) throw new ValidationError("name may contain at most 128 characters");
374
+ body.name = request.name;
375
+ }
376
+ if (request.url !== void 0) {
377
+ validateWebhook("update", request.url, ["validation"]);
378
+ body.url = request.url;
379
+ }
380
+ if (request.description !== void 0) {
381
+ if (request.description.length > 500) {
382
+ throw new ValidationError("description may contain at most 500 characters");
383
+ }
384
+ body.description = request.description;
385
+ }
386
+ if (request.events !== void 0) {
387
+ if (request.events.length === 0 || request.events.some((event) => !event.trim())) {
388
+ throw new ValidationError("events must contain at least one non-empty event type");
389
+ }
390
+ body.events = request.events;
391
+ }
392
+ if (request.retryConfig !== void 0) body.retry_config = webhookRetryConfig(request.retryConfig);
393
+ if (request.signatureConfig !== void 0) body.signature_config = webhookSignatureConfig(request.signatureConfig);
394
+ if (Object.keys(body).length === 0) {
395
+ throw new ValidationError("updateWebhook requires at least one editable field");
396
+ }
397
+ return this.request("PATCH", `/org/webhooks/${endpointId}`, { ...options, body });
398
+ }
399
+ async deleteWebhook(endpointId, options = {}) {
400
+ positiveId(endpointId, "endpointId");
401
+ return this.request("DELETE", `/org/webhooks/${endpointId}`, options);
402
+ }
403
+ async testWebhook(endpointId, request = {}, options = {}) {
404
+ positiveId(endpointId, "endpointId");
405
+ const body = {};
406
+ if (request.eventType !== void 0) {
407
+ nonEmpty(request.eventType, "eventType");
408
+ body.event_type = request.eventType;
409
+ }
410
+ return this.request("POST", `/org/webhooks/${endpointId}/test`, { ...options, body });
411
+ }
412
+ async replayWebhookDeliveries(endpointId, request = {}, options = {}) {
413
+ positiveId(endpointId, "endpointId");
414
+ if (request.sinceMinutes !== void 0 && (!Number.isInteger(request.sinceMinutes) || request.sinceMinutes < 1 || request.sinceMinutes > 10080)) {
415
+ throw new ValidationError("sinceMinutes must be an integer between 1 and 10080");
416
+ }
417
+ if (request.limit !== void 0 && (!Number.isInteger(request.limit) || request.limit < 1 || request.limit > 1e3)) {
418
+ throw new ValidationError("limit must be an integer between 1 and 1000");
419
+ }
420
+ if (request.statuses !== void 0 && (request.statuses.length === 0 || request.statuses.some((status) => !status.trim()))) {
421
+ throw new ValidationError("statuses must contain at least one non-empty status");
422
+ }
423
+ const body = {};
424
+ if (request.sinceMinutes !== void 0) body.since_minutes = request.sinceMinutes;
425
+ if (request.statuses !== void 0) body.statuses = request.statuses;
426
+ if (request.limit !== void 0) body.limit = request.limit;
427
+ return this.request("POST", `/org/webhooks/${endpointId}/replay`, { ...options, body });
428
+ }
429
+ async listWebhookDeliveries(endpointId, query = {}, options = {}) {
430
+ positiveId(endpointId, "endpointId");
431
+ if (query.page !== void 0) positiveId(query.page, "page");
432
+ if (query.pageSize !== void 0 && (!Number.isInteger(query.pageSize) || query.pageSize < 1 || query.pageSize > 100)) {
433
+ throw new ValidationError("pageSize must be an integer between 1 and 100");
434
+ }
435
+ if (query.status !== void 0) nonEmpty(query.status, "status");
436
+ const path = `/org/webhooks/${endpointId}/deliveries` + queryString({
437
+ page: query.page,
438
+ page_size: query.pageSize,
439
+ status_filter: query.status
440
+ });
441
+ return this.request("GET", path, options);
442
+ }
443
+ };
444
+
445
+ // src/index.ts
446
+ var SDK_VERSION2 = "1.1.0";
43
447
  function camelToSnakeKey(key) {
44
448
  return key.replace(/([A-Z])/g, "_$1").toLowerCase();
45
449
  }
@@ -68,14 +472,14 @@ function snakeToCamelMemory(m) {
68
472
  score: m.score ?? null
69
473
  };
70
474
  }
71
- function safeJson(text) {
475
+ function safeJson2(text) {
72
476
  try {
73
477
  return JSON.parse(text);
74
478
  } catch {
75
479
  return text;
76
480
  }
77
481
  }
78
- function extractDetail(body) {
482
+ function extractDetail2(body) {
79
483
  if (!body || typeof body !== "object") return void 0;
80
484
  const b = body;
81
485
  if (typeof b.detail === "string") return b.detail;
@@ -119,7 +523,7 @@ var MemorySyncClient = class {
119
523
  "X-API-Key": this.apiKey,
120
524
  "Content-Type": "application/json",
121
525
  "Accept": "application/json",
122
- "User-Agent": `memorysync-sdk-js/${SDK_VERSION}`,
526
+ "User-Agent": `memorysync-sdk-js/${SDK_VERSION2}`,
123
527
  ...extra
124
528
  };
125
529
  if (this.projectId) h["X-Project-ID"] = this.projectId;
@@ -143,7 +547,7 @@ var MemorySyncClient = class {
143
547
  const requestId = res.headers.get("X-Request-ID") ?? void 0;
144
548
  if (res.status === 204) return void 0;
145
549
  const text = await res.text();
146
- const parsed = text ? safeJson(text) : null;
550
+ const parsed = text ? safeJson2(text) : null;
147
551
  if (!res.ok) this.throwForStatus(res.status, parsed, requestId);
148
552
  return parsed;
149
553
  } catch (e) {
@@ -157,7 +561,7 @@ var MemorySyncClient = class {
157
561
  }
158
562
  }
159
563
  throwForStatus(status, body, requestId) {
160
- const detail = extractDetail(body);
564
+ const detail = extractDetail2(body);
161
565
  const opts = { statusCode: status, response: body, requestId };
162
566
  if (status === 401) throw new AuthError(detail || "Unauthenticated", opts);
163
567
  if (status === 403) throw new AuthError(detail || "Forbidden", opts);
@@ -332,6 +736,7 @@ var MemorySyncClient = class {
332
736
  };
333
737
  export {
334
738
  AuthError,
739
+ ControlPlaneClient,
335
740
  MemorySyncClient,
336
741
  MemorySyncError,
337
742
  NotFoundError,