@nordhavnhq/beacon 0.5.0 → 0.6.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.d.cts CHANGED
@@ -84,6 +84,22 @@ interface QueryResult<V = unknown> {
84
84
  shape: QueryShape;
85
85
  value: V;
86
86
  }
87
+ /**
88
+ * Response of `POST /files`: one uploaded file, not yet on any record. Hang it
89
+ * on a record by writing `{ uid }` into the file field it was uploaded for;
90
+ * an upload no record takes up within 24 hours is removed.
91
+ */
92
+ interface UploadedFile {
93
+ uid: string;
94
+ /** Absolute URL of the stored file. */
95
+ url: string;
96
+ /** The file name as uploaded. */
97
+ name: string;
98
+ /** Read from the file's content, not from what the upload declared. */
99
+ mimeType: string;
100
+ /** Size in bytes. */
101
+ size: number;
102
+ }
87
103
 
88
104
  /**
89
105
  * Query parameter Nordhavn OS appends when it loads your site in a
@@ -188,6 +204,22 @@ interface ReadOptions {
188
204
  */
189
205
  locale?: string | null | undefined;
190
206
  }
207
+ /** Per-call options for `uploadFile`. */
208
+ interface UploadOptions {
209
+ /**
210
+ * The file name to send, extension included: the studio checks the
211
+ * extension against the field's allowed types. Defaults to the name of a
212
+ * `File`; required for a plain `Blob`.
213
+ */
214
+ filename?: string;
215
+ /**
216
+ * Give up after this many ms, body included. Defaults to the client's
217
+ * `timeout`, but at least 60 s (an upload may be 10 MB); `0` for none. A
218
+ * client created with `timeout: 0` uploads without one too. A negative
219
+ * number or `NaN` counts as not given.
220
+ */
221
+ timeout?: number;
222
+ }
191
223
  /**
192
224
  * Typed client for the Nordhavn OS content API: read and write a project's node
193
225
  * datasets from any website or app. Reads are cached (see the `cache` option);
@@ -322,6 +354,33 @@ declare class HavenClient {
322
354
  * reads of the dataset and of this record.
323
355
  */
324
356
  updateRecord<T = Record<string, unknown>>(nodeSlug: string, datasetSlug: string, recordUid: string, data: Record<string, unknown>): Promise<ContentRecord<T>>;
357
+ /**
358
+ * Upload one file for a `file` field, for a form that sends an attachment.
359
+ * Requires write scope on the dataset. Returns the file; hang it on a record
360
+ * in a second call by writing `{ uid }` into that field:
361
+ *
362
+ * ```ts
363
+ * const attachment = form.get('attachment')
364
+ * if (attachment instanceof File && attachment.size > 0) {
365
+ * const file = await studio.uploadFile('contact', 'requests', 'attachment', attachment)
366
+ * await studio.createRecord('contact', 'requests', { name, attachment: { uid: file.uid } })
367
+ * }
368
+ * ```
369
+ *
370
+ * The field decides what it takes: its `mimes` and `max_size` rules, within
371
+ * what the studio accepts from a key at all (pdf, jpg, png, webp; 10 MB). The
372
+ * studio reads the type from the content, so a renamed file is refused. Only
373
+ * top-level fields. A file of the wrong type or size throws `HavenError` 400
374
+ * with a message fit to show; other refusals (400, 403, 404) are setup
375
+ * errors. More than 10 uploads a minute per key throws 429. From a Node
376
+ * `Buffer`, send `new Blob([buffer])` with a `filename`.
377
+ *
378
+ * Server-side only: the key that uploads can write, and must never reach a
379
+ * browser. Not retried, not cached, and it leaves cached reads alone: until a
380
+ * record takes it up, the file belongs to no content. An upload that failed
381
+ * may still have been stored; an unused one is removed after 24 hours.
382
+ */
383
+ uploadFile(nodeSlug: string, datasetSlug: string, fieldSlug: string, file: Blob, opts?: UploadOptions): Promise<UploadedFile>;
325
384
  /**
326
385
  * Sends a write and settles the cached reads of its dataset with the outcome.
327
386
  *
@@ -477,6 +536,8 @@ declare class DatasetHandle<T = Record<string, unknown>> {
477
536
  get(recordUid: string, opts?: ReadOptions): Promise<ContentRecord<T>>;
478
537
  create(data: Record<string, unknown>): Promise<ContentRecord<T>>;
479
538
  update(recordUid: string, data: Record<string, unknown>): Promise<ContentRecord<T>>;
539
+ /** Upload a file for one of this dataset's file fields; see `HavenClient.uploadFile`. */
540
+ uploadFile(fieldSlug: string, file: Blob, opts?: UploadOptions): Promise<UploadedFile>;
480
541
  /** Clear cached reads for this dataset. */
481
542
  clearCache(): void;
482
543
  }
@@ -708,4 +769,4 @@ interface ForecastSeries {
708
769
  declare function createClient(options: HavenClientOptions): HavenClient;
709
770
 
710
771
  export { CHART_FENCE_LANG, CHART_FENCE_LIMITS, CacheOptions, ChartData, DEFAULT_BASE_URL, DatasetHandle, HavenClient, HavenError, HavenClient as JustmadeClient, HavenError as JustmadeError, PREVIEW_PARAM, chartFenceHeight, createClient, isChartFence, isPreviewRequest, parseChartFence };
711
- export type { ChartFence, ChartFenceResult, ContentLocale, ContentRecord, ContentSchema, FieldKind, FieldType, ForecastSeries, HavenClientOptions, HavenClientOptions as JustmadeClientOptions, PreviewInput, QueryResult, QueryShape, ReadOptions, RoadmapData, RoadmapEvent, RoadmapHappening, RoadmapLane, RoadmapMilestone, RoadmapPhase, RoadmapPhaseState, RoadmapRepeat, RoadmapTask, RoadmapTip, RoadmapTone, RoadmapWaiting, RoadmapWorkState, SchemaDataset, SchemaField, SchemaNode, StudioFailure };
772
+ export type { ChartFence, ChartFenceResult, ContentLocale, ContentRecord, ContentSchema, FieldKind, FieldType, ForecastSeries, HavenClientOptions, HavenClientOptions as JustmadeClientOptions, PreviewInput, QueryResult, QueryShape, ReadOptions, RoadmapData, RoadmapEvent, RoadmapHappening, RoadmapLane, RoadmapMilestone, RoadmapPhase, RoadmapPhaseState, RoadmapRepeat, RoadmapTask, RoadmapTip, RoadmapTone, RoadmapWaiting, RoadmapWorkState, SchemaDataset, SchemaField, SchemaNode, StudioFailure, UploadOptions, UploadedFile };
package/dist/index.d.ts CHANGED
@@ -84,6 +84,22 @@ interface QueryResult<V = unknown> {
84
84
  shape: QueryShape;
85
85
  value: V;
86
86
  }
87
+ /**
88
+ * Response of `POST /files`: one uploaded file, not yet on any record. Hang it
89
+ * on a record by writing `{ uid }` into the file field it was uploaded for;
90
+ * an upload no record takes up within 24 hours is removed.
91
+ */
92
+ interface UploadedFile {
93
+ uid: string;
94
+ /** Absolute URL of the stored file. */
95
+ url: string;
96
+ /** The file name as uploaded. */
97
+ name: string;
98
+ /** Read from the file's content, not from what the upload declared. */
99
+ mimeType: string;
100
+ /** Size in bytes. */
101
+ size: number;
102
+ }
87
103
 
88
104
  /**
89
105
  * Query parameter Nordhavn OS appends when it loads your site in a
@@ -188,6 +204,22 @@ interface ReadOptions {
188
204
  */
189
205
  locale?: string | null | undefined;
190
206
  }
207
+ /** Per-call options for `uploadFile`. */
208
+ interface UploadOptions {
209
+ /**
210
+ * The file name to send, extension included: the studio checks the
211
+ * extension against the field's allowed types. Defaults to the name of a
212
+ * `File`; required for a plain `Blob`.
213
+ */
214
+ filename?: string;
215
+ /**
216
+ * Give up after this many ms, body included. Defaults to the client's
217
+ * `timeout`, but at least 60 s (an upload may be 10 MB); `0` for none. A
218
+ * client created with `timeout: 0` uploads without one too. A negative
219
+ * number or `NaN` counts as not given.
220
+ */
221
+ timeout?: number;
222
+ }
191
223
  /**
192
224
  * Typed client for the Nordhavn OS content API: read and write a project's node
193
225
  * datasets from any website or app. Reads are cached (see the `cache` option);
@@ -322,6 +354,33 @@ declare class HavenClient {
322
354
  * reads of the dataset and of this record.
323
355
  */
324
356
  updateRecord<T = Record<string, unknown>>(nodeSlug: string, datasetSlug: string, recordUid: string, data: Record<string, unknown>): Promise<ContentRecord<T>>;
357
+ /**
358
+ * Upload one file for a `file` field, for a form that sends an attachment.
359
+ * Requires write scope on the dataset. Returns the file; hang it on a record
360
+ * in a second call by writing `{ uid }` into that field:
361
+ *
362
+ * ```ts
363
+ * const attachment = form.get('attachment')
364
+ * if (attachment instanceof File && attachment.size > 0) {
365
+ * const file = await studio.uploadFile('contact', 'requests', 'attachment', attachment)
366
+ * await studio.createRecord('contact', 'requests', { name, attachment: { uid: file.uid } })
367
+ * }
368
+ * ```
369
+ *
370
+ * The field decides what it takes: its `mimes` and `max_size` rules, within
371
+ * what the studio accepts from a key at all (pdf, jpg, png, webp; 10 MB). The
372
+ * studio reads the type from the content, so a renamed file is refused. Only
373
+ * top-level fields. A file of the wrong type or size throws `HavenError` 400
374
+ * with a message fit to show; other refusals (400, 403, 404) are setup
375
+ * errors. More than 10 uploads a minute per key throws 429. From a Node
376
+ * `Buffer`, send `new Blob([buffer])` with a `filename`.
377
+ *
378
+ * Server-side only: the key that uploads can write, and must never reach a
379
+ * browser. Not retried, not cached, and it leaves cached reads alone: until a
380
+ * record takes it up, the file belongs to no content. An upload that failed
381
+ * may still have been stored; an unused one is removed after 24 hours.
382
+ */
383
+ uploadFile(nodeSlug: string, datasetSlug: string, fieldSlug: string, file: Blob, opts?: UploadOptions): Promise<UploadedFile>;
325
384
  /**
326
385
  * Sends a write and settles the cached reads of its dataset with the outcome.
327
386
  *
@@ -477,6 +536,8 @@ declare class DatasetHandle<T = Record<string, unknown>> {
477
536
  get(recordUid: string, opts?: ReadOptions): Promise<ContentRecord<T>>;
478
537
  create(data: Record<string, unknown>): Promise<ContentRecord<T>>;
479
538
  update(recordUid: string, data: Record<string, unknown>): Promise<ContentRecord<T>>;
539
+ /** Upload a file for one of this dataset's file fields; see `HavenClient.uploadFile`. */
540
+ uploadFile(fieldSlug: string, file: Blob, opts?: UploadOptions): Promise<UploadedFile>;
480
541
  /** Clear cached reads for this dataset. */
481
542
  clearCache(): void;
482
543
  }
@@ -708,4 +769,4 @@ interface ForecastSeries {
708
769
  declare function createClient(options: HavenClientOptions): HavenClient;
709
770
 
710
771
  export { CHART_FENCE_LANG, CHART_FENCE_LIMITS, CacheOptions, ChartData, DEFAULT_BASE_URL, DatasetHandle, HavenClient, HavenError, HavenClient as JustmadeClient, HavenError as JustmadeError, PREVIEW_PARAM, chartFenceHeight, createClient, isChartFence, isPreviewRequest, parseChartFence };
711
- export type { ChartFence, ChartFenceResult, ContentLocale, ContentRecord, ContentSchema, FieldKind, FieldType, ForecastSeries, HavenClientOptions, HavenClientOptions as JustmadeClientOptions, PreviewInput, QueryResult, QueryShape, ReadOptions, RoadmapData, RoadmapEvent, RoadmapHappening, RoadmapLane, RoadmapMilestone, RoadmapPhase, RoadmapPhaseState, RoadmapRepeat, RoadmapTask, RoadmapTip, RoadmapTone, RoadmapWaiting, RoadmapWorkState, SchemaDataset, SchemaField, SchemaNode, StudioFailure };
772
+ export type { ChartFence, ChartFenceResult, ContentLocale, ContentRecord, ContentSchema, FieldKind, FieldType, ForecastSeries, HavenClientOptions, HavenClientOptions as JustmadeClientOptions, PreviewInput, QueryResult, QueryShape, ReadOptions, RoadmapData, RoadmapEvent, RoadmapHappening, RoadmapLane, RoadmapMilestone, RoadmapPhase, RoadmapPhaseState, RoadmapRepeat, RoadmapTask, RoadmapTip, RoadmapTone, RoadmapWaiting, RoadmapWorkState, SchemaDataset, SchemaField, SchemaNode, StudioFailure, UploadOptions, UploadedFile };
package/dist/index.js CHANGED
@@ -209,6 +209,7 @@ var VersionTracker = class {
209
209
  var PREVIEW_PARAM = "sl-preview";
210
210
  var DEFAULT_BASE_URL = "https://beacon.nordhavn.ai";
211
211
  var DEFAULT_TIMEOUT = 1e4;
212
+ var MIN_UPLOAD_TIMEOUT = 6e4;
212
213
  var VERSION_TIMEOUT = 3e3;
213
214
  var DEFAULT_WAIT_FOR_FRESH = 1e3;
214
215
  var MAX_TIMER = 2147483647;
@@ -460,6 +461,58 @@ var HavenClient = class {
460
461
  );
461
462
  return res.record;
462
463
  }
464
+ /**
465
+ * Upload one file for a `file` field, for a form that sends an attachment.
466
+ * Requires write scope on the dataset. Returns the file; hang it on a record
467
+ * in a second call by writing `{ uid }` into that field:
468
+ *
469
+ * ```ts
470
+ * const attachment = form.get('attachment')
471
+ * if (attachment instanceof File && attachment.size > 0) {
472
+ * const file = await studio.uploadFile('contact', 'requests', 'attachment', attachment)
473
+ * await studio.createRecord('contact', 'requests', { name, attachment: { uid: file.uid } })
474
+ * }
475
+ * ```
476
+ *
477
+ * The field decides what it takes: its `mimes` and `max_size` rules, within
478
+ * what the studio accepts from a key at all (pdf, jpg, png, webp; 10 MB). The
479
+ * studio reads the type from the content, so a renamed file is refused. Only
480
+ * top-level fields. A file of the wrong type or size throws `HavenError` 400
481
+ * with a message fit to show; other refusals (400, 403, 404) are setup
482
+ * errors. More than 10 uploads a minute per key throws 429. From a Node
483
+ * `Buffer`, send `new Blob([buffer])` with a `filename`.
484
+ *
485
+ * Server-side only: the key that uploads can write, and must never reach a
486
+ * browser. Not retried, not cached, and it leaves cached reads alone: until a
487
+ * record takes it up, the file belongs to no content. An upload that failed
488
+ * may still have been stored; an unused one is removed after 24 hours.
489
+ */
490
+ async uploadFile(nodeSlug, datasetSlug, fieldSlug, file, opts) {
491
+ const filename = opts?.filename ?? file.name;
492
+ if (!filename) {
493
+ throw new Error("HavenClient.uploadFile: the file has no name; pass `filename` (with its extension)");
494
+ }
495
+ const form = new FormData();
496
+ form.set("file", file, filename);
497
+ form.set("nodeSlug", nodeSlug);
498
+ form.set("datasetSlug", datasetSlug);
499
+ form.set("fieldSlug", fieldSlug);
500
+ const url = `${this.baseUrl}/api/content/files`;
501
+ const timeout = uploadTimeout(this.timeout, opts?.timeout);
502
+ return withTimeout(url, timeout, async (signal) => {
503
+ const res = await this.fetchImpl(url, {
504
+ method: "POST",
505
+ // No Content-Type: fetch sets the multipart one, with its boundary.
506
+ headers: { Authorization: `Bearer ${this.apiKey}`, ...withoutContentType(this.headers) },
507
+ body: form,
508
+ signal
509
+ });
510
+ if (!res.ok) throw await this.toError(res);
511
+ const value = await res.json().catch(() => void 0);
512
+ if (!has("uid", (uid) => typeof uid === "string" && uid !== "")(value)) throw unexpectedBody(url);
513
+ return value;
514
+ });
515
+ }
463
516
  /**
464
517
  * Sends a write and settles the cached reads of its dataset with the outcome.
465
518
  *
@@ -853,6 +906,10 @@ var DatasetHandle = class {
853
906
  update(recordUid, data) {
854
907
  return this.client.updateRecord(this.nodeSlug, this.datasetSlug, recordUid, data);
855
908
  }
909
+ /** Upload a file for one of this dataset's file fields; see `HavenClient.uploadFile`. */
910
+ uploadFile(fieldSlug, file, opts) {
911
+ return this.client.uploadFile(this.nodeSlug, this.datasetSlug, fieldSlug, file, opts);
912
+ }
856
913
  /** Clear cached reads for this dataset. */
857
914
  clearCache() {
858
915
  this.client.clearCache({ node: this.nodeSlug, dataset: this.datasetSlug });
@@ -893,6 +950,13 @@ function normalizeTimeout(value) {
893
950
  if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_TIMEOUT;
894
951
  return value > MAX_TIMER ? 0 : value;
895
952
  }
953
+ function uploadTimeout(clientTimeout, perCall) {
954
+ if (typeof perCall === "number" && perCall >= 0) return normalizeTimeout(perCall);
955
+ return clientTimeout === 0 ? 0 : Math.max(clientTimeout, MIN_UPLOAD_TIMEOUT);
956
+ }
957
+ function withoutContentType(headers) {
958
+ return Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== "content-type"));
959
+ }
896
960
  function normalizeGatewayRetry(value) {
897
961
  if (value === false) return void 0;
898
962
  if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_GATEWAY_RETRY;