@foxnose/sdk 0.4.0 → 0.5.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/README.md CHANGED
@@ -52,6 +52,15 @@ const client = new ManagementClient({
52
52
  const collections = await client.listCollections();
53
53
  console.log(collections.results);
54
54
 
55
+ // Create a public API
56
+ const api = await client.createApi({
57
+ name: 'Storefront',
58
+ prefix: 'shop',
59
+ is_auth_required: false,
60
+ cors_origins: ['*'], // browser CORS for public APIs (reads only)
61
+ });
62
+ console.log(api.key);
63
+
55
64
  // Create a resource
56
65
  const resource = await client.createResource('my-collection-key', {
57
66
  data: { title: 'Hello World' },
@@ -153,6 +162,11 @@ console.log(router.routes.length);
153
162
  const schema = await client.getSchema('articles');
154
163
  console.log(schema.searchable_fields);
155
164
 
165
+ // Writes require a write-capable key. Create publishes immediately; `key` is an
166
+ // optional external id used to deduplicate. updateResource is a full replace.
167
+ const created = await client.createResource('articles', { title: 'Hello' }, { key: 'my-id' });
168
+ await client.updateResource('articles', created.resource_key, { title: 'Hello (edited)' });
169
+
156
170
  client.close();
157
171
  ```
158
172
 
@@ -343,6 +357,37 @@ try {
343
357
  }
344
358
  ```
345
359
 
360
+ ### Write errors
361
+
362
+ Resource writes (`createResource` / `updateResource`) can throw these typed
363
+ subclasses of `FoxnoseAPIError`:
364
+
365
+ ```typescript
366
+ import {
367
+ CollectionNotWritableError,
368
+ ExternalIdConflictError,
369
+ ContentValidationFailedError,
370
+ UpstreamError,
371
+ } from '@foxnose/sdk';
372
+
373
+ try {
374
+ await client.createResource('articles', { title: 'Hi' }, { key: 'ext-1' });
375
+ } catch (err) {
376
+ if (err instanceof ExternalIdConflictError) {
377
+ // HTTP 409 — a resource with that key already exists
378
+ } else if (err instanceof ContentValidationFailedError) {
379
+ // HTTP 422 — err.errors[] each carry a json_path; err.errorsTruncated
380
+ console.error(err.errors, err.errorsTruncated);
381
+ } else if (err instanceof CollectionNotWritableError) {
382
+ // HTTP 403 — this key cannot write to that collection
383
+ } else if (err instanceof UpstreamError) {
384
+ // HTTP 502 — outcome unknown; re-read with a GET before retrying
385
+ }
386
+ }
387
+ ```
388
+
389
+ Writes are never retried automatically (they are not idempotent).
390
+
346
391
  ## Batch Operations
347
392
 
348
393
  Efficiently upsert multiple resources with concurrency control:
package/dist/index.cjs CHANGED
@@ -21,8 +21,11 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  AnonymousAuth: () => AnonymousAuth,
24
+ CollectionNotWritableError: () => CollectionNotWritableError,
25
+ ContentValidationFailedError: () => ContentValidationFailedError,
24
26
  DEFAULT_RETRY_CONFIG: () => DEFAULT_RETRY_CONFIG,
25
27
  DEFAULT_USER_AGENT: () => DEFAULT_USER_AGENT,
28
+ ExternalIdConflictError: () => ExternalIdConflictError,
26
29
  FluxClient: () => FluxClient,
27
30
  FoxnoseAPIError: () => FoxnoseAPIError,
28
31
  FoxnoseAuthError: () => FoxnoseAuthError,
@@ -40,6 +43,7 @@ __export(index_exports, {
40
43
  SimpleKeyAuth: () => SimpleKeyAuth,
41
44
  SpendCapExceededError: () => SpendCapExceededError,
42
45
  StaticTokenProvider: () => StaticTokenProvider,
46
+ UpstreamError: () => UpstreamError,
43
47
  VERSION: () => SDK_VERSION,
44
48
  buildSearchBody: () => buildSearchBody,
45
49
  createConfig: () => createConfig,
@@ -170,6 +174,36 @@ var RateLimitExceededError = class extends FoxnoseAPIError {
170
174
  this.retryAfter = options.retryAfter;
171
175
  }
172
176
  };
177
+ var CollectionNotWritableError = class extends FoxnoseAPIError {
178
+ constructor(options) {
179
+ super(options);
180
+ this.name = "CollectionNotWritableError";
181
+ }
182
+ };
183
+ var ExternalIdConflictError = class extends FoxnoseAPIError {
184
+ constructor(options) {
185
+ super(options);
186
+ this.name = "ExternalIdConflictError";
187
+ }
188
+ };
189
+ var ContentValidationFailedError = class extends FoxnoseAPIError {
190
+ /** Individual validation problems; each includes a `json_path`. */
191
+ errors;
192
+ /** True when the server capped a very large error list. */
193
+ errorsTruncated;
194
+ constructor(options) {
195
+ super(options);
196
+ this.name = "ContentValidationFailedError";
197
+ this.errors = options.errors ?? [];
198
+ this.errorsTruncated = options.errorsTruncated ?? false;
199
+ }
200
+ };
201
+ var UpstreamError = class extends FoxnoseAPIError {
202
+ constructor(options) {
203
+ super(options);
204
+ this.name = "UpstreamError";
205
+ }
206
+ };
173
207
  function isPlainObject(value) {
174
208
  return typeof value === "object" && value !== null && !Array.isArray(value);
175
209
  }
@@ -224,6 +258,24 @@ function buildAPIError(options) {
224
258
  retryAfter: Number.isNaN(parsed) ? void 0 : parsed
225
259
  });
226
260
  }
261
+ if (statusCode === 403 && errorCode === "collection_not_writable") {
262
+ return new CollectionNotWritableError(options);
263
+ }
264
+ if (statusCode === 409 && errorCode === "external_id_conflict") {
265
+ return new ExternalIdConflictError(options);
266
+ }
267
+ if (statusCode === 422 && errorCode === "content_validation_failed") {
268
+ const d = isPlainObject(detail) ? detail : {};
269
+ const errors = Array.isArray(d.errors) ? d.errors : typeof d.json_path === "string" ? [d] : [];
270
+ return new ContentValidationFailedError({
271
+ ...options,
272
+ errors,
273
+ errorsTruncated: d.errors_truncated === true
274
+ });
275
+ }
276
+ if (statusCode === 502 && errorCode === "upstream_error") {
277
+ return new UpstreamError(options);
278
+ }
227
279
  return new FoxnoseAPIError(options);
228
280
  }
229
281
  var FoxnoseAuthError = class extends FoxnoseError {
@@ -310,7 +362,7 @@ var DEFAULT_RETRY_CONFIG = {
310
362
  statusCodes: [408, 425, 429, 500, 502, 503, 504],
311
363
  methods: ["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]
312
364
  };
313
- var SDK_VERSION = "0.4.0";
365
+ var SDK_VERSION = "0.5.1";
314
366
  var DEFAULT_USER_AGENT = `foxnose-sdk-js/${SDK_VERSION}`;
315
367
  function createConfig(options) {
316
368
  if (!options.baseUrl) {
@@ -439,6 +491,7 @@ var HttpTransport = class {
439
491
  }
440
492
  }
441
493
  async sendWithRetries(method, path, options) {
494
+ const allowRetries = options?.allowRetries !== false;
442
495
  for (let attempt = 1; attempt <= this.retry.attempts; attempt++) {
443
496
  const { url, init } = this.buildRequest(method, path, options);
444
497
  const controller = new AbortController();
@@ -449,7 +502,7 @@ var HttpTransport = class {
449
502
  response = await fetch(url, init);
450
503
  } catch (err) {
451
504
  clearTimeout(timeoutId);
452
- const delay = this.handleTransportError(err, method, attempt);
505
+ const delay = this.handleTransportError(err, method, attempt, !allowRetries);
453
506
  if (delay > 0) {
454
507
  await this.sleep(delay);
455
508
  }
@@ -458,7 +511,7 @@ var HttpTransport = class {
458
511
  clearTimeout(timeoutId);
459
512
  }
460
513
  if (response.status >= 400) {
461
- if (this.shouldRetry(method, response.status) && attempt < this.retry.attempts) {
514
+ if (allowRetries && this.shouldRetry(method, response.status) && attempt < this.retry.attempts) {
462
515
  const delay = this.computeDelay(attempt, response.headers.get("Retry-After"));
463
516
  if (delay > 0) {
464
517
  await this.sleep(delay);
@@ -471,8 +524,8 @@ var HttpTransport = class {
471
524
  }
472
525
  throw new FoxnoseTransportError("All retry attempts exhausted");
473
526
  }
474
- handleTransportError(err, method, attempt) {
475
- const canRetry = this.retry.methods.includes(method.toUpperCase()) && attempt < this.retry.attempts;
527
+ handleTransportError(err, method, attempt, forbidRetry = false) {
528
+ const canRetry = !forbidRetry && this.retry.methods.includes(method.toUpperCase()) && attempt < this.retry.attempts;
476
529
  if (!canRetry) {
477
530
  const message = err instanceof Error ? err.message : String(err);
478
531
  throw new FoxnoseTransportError(message);
@@ -2057,6 +2110,46 @@ var FluxClient = class {
2057
2110
  const path = this.buildPath(folderPath, "/_search");
2058
2111
  return this.transport.request("POST", path, { jsonBody: body });
2059
2112
  }
2113
+ /**
2114
+ * Create a resource in a collection and publish it immediately.
2115
+ *
2116
+ * `folderPath` is the collection path (e.g. `articles` or a nested path such
2117
+ * as `users/usr_1/memories`). `options.key` is an optional external
2118
+ * identifier for deduplication — reusing an existing key raises
2119
+ * {@link ExternalIdConflictError}. The response carries `resource_key`,
2120
+ * `revision_key`, `write_units`, and `published`.
2121
+ *
2122
+ * Writes require an authenticated key with write access: an anonymous caller
2123
+ * gets 401, a key without the `create` grant gets a generic 403
2124
+ * (`access_denied`), and a collection whose connection does not allow writes
2125
+ * raises {@link CollectionNotWritableError}.
2126
+ *
2127
+ * Writes are never retried automatically: a failed write's outcome is
2128
+ * unknown, so re-read with a GET before retrying.
2129
+ */
2130
+ async createResource(folderPath, data, options) {
2131
+ const path = this.buildPath(folderPath, "/");
2132
+ const body = { data };
2133
+ if (options?.key !== void 0) {
2134
+ body.key = options.key;
2135
+ }
2136
+ return this.transport.request("POST", path, { jsonBody: body, allowRetries: false });
2137
+ }
2138
+ /**
2139
+ * Replace a resource's document and publish a new revision. This is a
2140
+ * full-document replace, not a partial merge: fields absent from `data` are
2141
+ * removed.
2142
+ *
2143
+ * Writes require an authenticated key with write access: an anonymous caller
2144
+ * gets 401, a key without the `update` grant gets a generic 403
2145
+ * (`access_denied`), and a collection whose connection does not allow writes
2146
+ * raises {@link CollectionNotWritableError}. Like {@link createResource}, it
2147
+ * is never retried automatically.
2148
+ */
2149
+ async updateResource(folderPath, resourceKey, data) {
2150
+ const path = this.buildPath(folderPath, `/${resourceKey}/`);
2151
+ return this.transport.request("PUT", path, { jsonBody: { data }, allowRetries: false });
2152
+ }
2060
2153
  /** Semantic search using auto-generated embeddings. */
2061
2154
  async vectorSearch(folderPath, options) {
2062
2155
  const { query, fields, top_k = 10, similarity_threshold, limit, offset, ...rest } = options;
@@ -2189,8 +2282,11 @@ var FluxClient = class {
2189
2282
  // Annotate the CommonJS export names for ESM import in node:
2190
2283
  0 && (module.exports = {
2191
2284
  AnonymousAuth,
2285
+ CollectionNotWritableError,
2286
+ ContentValidationFailedError,
2192
2287
  DEFAULT_RETRY_CONFIG,
2193
2288
  DEFAULT_USER_AGENT,
2289
+ ExternalIdConflictError,
2194
2290
  FluxClient,
2195
2291
  FoxnoseAPIError,
2196
2292
  FoxnoseAuthError,
@@ -2208,6 +2304,7 @@ var FluxClient = class {
2208
2304
  SimpleKeyAuth,
2209
2305
  SpendCapExceededError,
2210
2306
  StaticTokenProvider,
2307
+ UpstreamError,
2211
2308
  VERSION,
2212
2309
  buildSearchBody,
2213
2310
  createConfig,