@formfeed/sdk 0.1.0 → 0.3.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/index.js CHANGED
@@ -1,4 +1,20 @@
1
1
  // packages/sdk-ts/src/lib/client.ts
2
+ var isOfficeInput = (input) => "file" in input;
3
+ function blobOf(file) {
4
+ const blob = file.data instanceof Blob ? file.data : new Blob([file.data]);
5
+ const own = typeof File !== "undefined" && file.data instanceof File ? file.data.name : void 0;
6
+ return { blob, name: file.name ?? own ?? "document" };
7
+ }
8
+ function multipart(fields, file) {
9
+ const form = new FormData();
10
+ const { blob, name } = blobOf(file);
11
+ form.set("file", blob, name);
12
+ for (const [key, value] of Object.entries(fields)) {
13
+ if (value === void 0) continue;
14
+ form.set(key, typeof value === "string" ? value : typeof value === "object" ? JSON.stringify(value) : String(value));
15
+ }
16
+ return form;
17
+ }
2
18
  var FormfeedError = class extends Error {
3
19
  constructor(code, message, status, problem = null, requestId = null) {
4
20
  super(message);
@@ -25,6 +41,8 @@ function randomKey() {
25
41
  if (c?.randomUUID) return c.randomUUID();
26
42
  return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
27
43
  }
44
+ var withKey = (options) => ({ ...options, idempotencyKey: options.idempotencyKey ?? randomKey() });
45
+ var idOf = (source) => typeof source === "string" ? source : source.id;
28
46
  var Formfeed = class {
29
47
  baseUrl;
30
48
  apiKey;
@@ -88,11 +106,96 @@ var Formfeed = class {
88
106
  },
89
107
  /** Removes the stored files of a render before they expire. Needs the `file:delete` scope. */
90
108
  deleteOutputs: (id, options = {}) => this.request("DELETE", `/renders/${encodeURIComponent(id)}/outputs`, void 0, options),
109
+ /**
110
+ * The stored request of a render, to render it again. Needs `render:input`; throws
111
+ * `render_input_expired` (410) when the workspace keeps no requests or the period ended.
112
+ */
113
+ input: (id, options = {}) => this.request("GET", `/renders/${encodeURIComponent(id)}/input`, void 0, options),
91
114
  batch: (request, options = {}) => this.request("POST", "/renders/batch", request, {
92
115
  ...options,
93
116
  idempotencyKey: options.idempotencyKey ?? randomKey()
94
117
  })
95
118
  };
119
+ /**
120
+ * PDF tools on the outputs of earlier renders (a `Render` or its id) and on PDFs of the file library
121
+ * (a `LibraryFile`, its id or its name). merge, protect and watermark return a new render and cost
122
+ * 0.5 units each on live keys; info is free.
123
+ */
124
+ pdf = {
125
+ merge: (sources, output = {}, options = {}) => this.request("POST", "/pdf/merge", { ...output, sources: sources.map(idOf) }, withKey(options)),
126
+ protect: (source, protect, options = {}) => this.request("POST", "/pdf/protect", { ...protect, source: idOf(source) }, withKey(options)),
127
+ watermark: (source, watermark, options = {}) => this.request("POST", "/pdf/watermark", { ...watermark, source: idOf(source) }, withKey(options)),
128
+ info: (source, options = {}) => this.request("POST", "/pdf/info", { source: idOf(source) }, options),
129
+ /**
130
+ * Converts an office document to a PDF render (Starter plan and above): an uploaded file (Word,
131
+ * Excel, PowerPoint, OpenDocument, RTF or HTML, up to 20 MB, not kept), or the output of a Word or
132
+ * PowerPoint template render. Costs follow the PDF rule. A busy converter answers 503, which is
133
+ * retried like any other.
134
+ */
135
+ convert: (source, convert = {}, options = {}) => {
136
+ if (typeof source === "object" && "file" in source)
137
+ return this.request("POST", "/pdf/convert", multipart({ ...convert }, source.file), withKey(options));
138
+ return this.request("POST", "/pdf/convert", { ...convert, source: idOf(source) }, withKey(options));
139
+ }
140
+ };
141
+ /**
142
+ * The workspace file library (`/files`): images and PDFs a template references by name with
143
+ * `asset('logo.png')`, and the sources of image watermarks and merges. Needs `file:read`,
144
+ * `file:write` or `file:delete`. Files are served without a signature, so keep confidential
145
+ * documents out of it.
146
+ */
147
+ files = {
148
+ /** Uploads a file; the same name replaces the existing file in place and keeps its URL. */
149
+ upload: (file, options = {}) => {
150
+ const blob = file.data instanceof Blob ? file.data : new Blob([file.data], file.contentType ? { type: file.contentType } : {});
151
+ const form = new FormData();
152
+ form.set("file", blob, file.name);
153
+ form.set("name", file.name);
154
+ return this.request("POST", "/files", form, options);
155
+ },
156
+ /** Page of files, newest first. */
157
+ list: (query = {}, options = {}) => {
158
+ const params = new URLSearchParams();
159
+ for (const [k, v] of Object.entries(query)) if (v !== void 0 && v !== null && v !== "") params.set(k, String(v));
160
+ const qs = params.toString();
161
+ return this.request("GET", `/files${qs ? `?${qs}` : ""}`, void 0, options);
162
+ },
163
+ /** Every file matching the query, following the cursor. */
164
+ all: async (query = {}, options = {}) => {
165
+ const out = [];
166
+ let cursor = null;
167
+ do {
168
+ const page = await this.files.list({ ...query, cursor }, options);
169
+ out.push(...page.data);
170
+ cursor = page.next_cursor;
171
+ } while (cursor);
172
+ return out;
173
+ },
174
+ get: (id, options = {}) => this.request("GET", `/files/${encodeURIComponent(id)}`, void 0, options),
175
+ /** Removes the file and its bytes; templates that name it render a missing image afterwards. */
176
+ delete: (file, options = {}) => this.request("DELETE", `/files/${encodeURIComponent(idOf(file))}`, void 0, options)
177
+ };
178
+ /** The organisation's brand kit, read-only through the API (it is edited in the app). Needs `template:read`. */
179
+ brand = {
180
+ get: (options = {}) => this.request("GET", "/brand", void 0, options)
181
+ };
182
+ /**
183
+ * Shared partials of the organisation. Renders use the current source, so a change reaches every
184
+ * template that includes the partial without a new version. Needs `template:read` or `template:write`.
185
+ */
186
+ partials = {
187
+ /** Every shared partial, without its source. */
188
+ list: async (options = {}) => (await this.request("GET", "/partials", void 0, options)).data,
189
+ /** One partial with its source. */
190
+ get: (name, options = {}) => this.request("GET", `/partials/${encodeURIComponent(name)}`, void 0, options),
191
+ /** Creates or replaces a partial; pass `base_version` to fail with 409 when it changed since you read it. */
192
+ put: async (name, input, options = {}) => {
193
+ const { status, body } = await this.send("PUT", `/partials/${encodeURIComponent(name)}`, input, options);
194
+ return { partial: body, created: status === 201 };
195
+ },
196
+ /** Removes a partial; templates that still include it fail to render afterwards. */
197
+ delete: (name, options = {}) => this.request("DELETE", `/partials/${encodeURIComponent(name)}`, void 0, options)
198
+ };
96
199
  jobs = {
97
200
  get: (id, options = {}) => this.request("GET", `/jobs/${encodeURIComponent(id)}`, void 0, options),
98
201
  waitFor: async (id, options = {}) => {
@@ -112,7 +215,20 @@ var Formfeed = class {
112
215
  create: (input, options = {}) => this.request("POST", "/webhooks", input, options),
113
216
  update: (id, patch, options = {}) => this.request("PUT", `/webhooks/${encodeURIComponent(id)}`, patch, options),
114
217
  delete: (id, options = {}) => this.request("DELETE", `/webhooks/${encodeURIComponent(id)}`, void 0, options),
115
- test: (id, options = {}) => this.request("POST", `/webhooks/${encodeURIComponent(id)}/test`, void 0, options)
218
+ test: (id, options = {}) => this.request("POST", `/webhooks/${encodeURIComponent(id)}/test`, void 0, options),
219
+ /**
220
+ * Sends a stored event (`evt_…`) again as a new delivery to a registered endpoint (`webhook:manage`)
221
+ * or a running listen session (`webhook:listen`).
222
+ */
223
+ resend: (eventId, endpointId, options = {}) => this.request("POST", `/webhooks/events/${encodeURIComponent(eventId)}/resend`, { endpoint_id: endpointId }, options),
224
+ /**
225
+ * Listen sessions, what `formfeed listen` uses. Needs `webhook:listen`. Starting a session ends the
226
+ * previous one of the same key; the WebSocket itself is up to the caller.
227
+ */
228
+ listen: {
229
+ start: (input = {}, options = {}) => this.request("POST", "/webhooks/listen", input, options),
230
+ end: (id, options = {}) => this.request("DELETE", `/webhooks/listen/${encodeURIComponent(id)}`, void 0, options)
231
+ }
116
232
  };
117
233
  templates = {
118
234
  list: (query = {}, options = {}) => {
@@ -133,32 +249,127 @@ var Formfeed = class {
133
249
  return out;
134
250
  },
135
251
  get: (idOrSlug, options = {}) => this.request("GET", `/templates/${encodeURIComponent(idOrSlug)}`, void 0, options),
136
- create: (input, options = {}) => this.request("POST", "/templates", input, options),
252
+ /** A Word or PowerPoint template (`kind` `docx` or `pptx`) is created from its `file`, sent as multipart. */
253
+ create: (input, options = {}) => {
254
+ if (isOfficeInput(input) && input.file) {
255
+ const { file, ...fields } = input;
256
+ return this.request("POST", "/templates", multipart(fields, file), options);
257
+ }
258
+ return this.request("POST", "/templates", input, options);
259
+ },
137
260
  update: (idOrSlug, patch, options = {}) => this.request("PUT", `/templates/${encodeURIComponent(idOrSlug)}`, patch, options),
138
261
  archive: (idOrSlug, options = {}) => this.request("DELETE", `/templates/${encodeURIComponent(idOrSlug)}`, void 0, options),
139
262
  versions: {
140
263
  list: async (idOrSlug, options = {}) => (await this.request("GET", `/templates/${encodeURIComponent(idOrSlug)}/versions`, void 0, options)).data,
141
- /** `which`: 'published', 'latest' or a version number. Carries the files. */
142
- get: (idOrSlug, which = "published", options = {}) => this.request("GET", `/templates/${encodeURIComponent(idOrSlug)}/versions/${which}`, void 0, options),
143
- create: (idOrSlug, input, options = {}) => this.request("POST", `/templates/${encodeURIComponent(idOrSlug)}/versions`, input, options),
144
- publish: (idOrSlug, number, options = {}) => this.request("POST", `/templates/${encodeURIComponent(idOrSlug)}/versions/${number}/publish`, void 0, options)
264
+ /** `which`: 'published', 'latest', a version number or a channel name (its main version). Carries the files. */
265
+ get: (idOrSlug, which = "published", options = {}) => this.request("GET", `/templates/${encodeURIComponent(idOrSlug)}/versions/${encodeURIComponent(String(which))}`, void 0, options),
266
+ /** For a Word or PowerPoint template, pass `file` to replace the document; without it the latest file is kept. */
267
+ create: (idOrSlug, input, options = {}) => {
268
+ const path = `/templates/${encodeURIComponent(idOrSlug)}/versions`;
269
+ if (isOfficeInput(input)) {
270
+ const { file, ...fields } = input;
271
+ if (file) return this.request("POST", path, multipart(fields, file), options);
272
+ return this.request("POST", path, fields, options);
273
+ }
274
+ return this.request("POST", path, input, options);
275
+ },
276
+ /** The Word or PowerPoint file of a version (`which` as for `get`); needs `template:read`. */
277
+ file: async (idOrSlug, which = "published", options = {}) => {
278
+ const path = `/templates/${encodeURIComponent(idOrSlug)}/versions/${encodeURIComponent(String(which))}/file`;
279
+ return (await this.send("GET", path, void 0, options, "bytes")).body;
280
+ },
281
+ /**
282
+ * Publishes a version. When both versions store a data schema and the new one breaks callers of the
283
+ * published one, the API refuses with `schema_breaking_change` unless `allowBreaking` is set.
284
+ */
285
+ publish: (idOrSlug, number, options = {}) => {
286
+ const { allowBreaking, ...rest } = options;
287
+ return this.request(
288
+ "POST",
289
+ `/templates/${encodeURIComponent(idOrSlug)}/versions/${number}/publish`,
290
+ allowBreaking ? { allow_breaking: true } : void 0,
291
+ rest
292
+ );
293
+ }
145
294
  },
146
- schema: (idOrSlug, options = {}) => this.request("GET", `/templates/${encodeURIComponent(idOrSlug)}/schema`, void 0, options)
295
+ /**
296
+ * Release channels (`published` and named ones such as `staging`): a render with `version: 'staging'`
297
+ * uses the version the channel points at. Moves reach renders within a minute.
298
+ */
299
+ channels: {
300
+ list: (idOrSlug, options = {}) => this.request("GET", `/templates/${encodeURIComponent(idOrSlug)}/channels`, void 0, options),
301
+ /** Creates or moves a channel; on `published` this publishes. */
302
+ set: (idOrSlug, name, move, options = {}) => {
303
+ const { allowBreaking, ...rest } = options;
304
+ return this.request(
305
+ "PUT",
306
+ `/templates/${encodeURIComponent(idOrSlug)}/channels/${encodeURIComponent(name)}`,
307
+ { ...move, ...allowBreaking ? { allow_breaking: true } : {} },
308
+ rest
309
+ );
310
+ },
311
+ /** The canary becomes the main version. */
312
+ promote: (idOrSlug, name, options = {}) => this.channelAction(idOrSlug, name, "promote", options),
313
+ /** Back to the version before the last move. */
314
+ rollback: (idOrSlug, name, options = {}) => this.channelAction(idOrSlug, name, "rollback", options),
315
+ /** Refused with `channel_in_use` while renders of the last hour used the channel, unless `force`. */
316
+ delete: (idOrSlug, name, options = {}) => {
317
+ const { force, ...rest } = options;
318
+ return this.request(
319
+ "DELETE",
320
+ `/templates/${encodeURIComponent(idOrSlug)}/channels/${encodeURIComponent(name)}${force ? "?force=true" : ""}`,
321
+ void 0,
322
+ rest
323
+ );
324
+ }
325
+ },
326
+ schema: (idOrSlug, options = {}) => this.request("GET", `/templates/${encodeURIComponent(idOrSlug)}/schema`, void 0, options),
327
+ /**
328
+ * Checks a version with data without rendering: syntax, header and footer, missing partials,
329
+ * runtime errors and the data against the stored schema. Free. Without `data`, the version's
330
+ * sample data is checked.
331
+ */
332
+ validate: (idOrSlug, input = {}, options = {}) => this.request("POST", `/templates/${encodeURIComponent(idOrSlug)}/validate`, input, options)
147
333
  };
148
334
  account = {
149
335
  get: (options = {}) => this.request("GET", "/account", void 0, options),
150
336
  /** Units of the current period, or of `YYYY-MM`, with a daily series and a breakdown per template. */
151
337
  usage: (period = "current", options = {}) => this.request("GET", `/usage?period=${encodeURIComponent(period)}`, void 0, options)
152
338
  };
339
+ /** Workspaces of the key's organisation. Needs `workspace:delete`, which no key has by default. */
340
+ workspaces = {
341
+ /**
342
+ * Deletes a workspace: it leaves the app and the API at once, its keys are revoked and its content
343
+ * is removed after 30 days. The organisation's last workspace is refused with `last_workspace`.
344
+ */
345
+ delete: (id, options = {}) => this.request("DELETE", `/workspaces/${encodeURIComponent(id)}`, void 0, options)
346
+ };
347
+ channelAction(idOrSlug, name, action, options) {
348
+ const { allowBreaking, ...rest } = options;
349
+ return this.request(
350
+ "POST",
351
+ `/templates/${encodeURIComponent(idOrSlug)}/channels/${encodeURIComponent(name)}/${action}`,
352
+ allowBreaking ? { allow_breaking: true } : void 0,
353
+ rest
354
+ );
355
+ }
153
356
  /** Raw request with auth, retries and problem mapping; use it for endpoints without a helper. */
154
357
  async request(method, path, body, options = {}) {
358
+ return (await this.send(method, path, body, options)).body;
359
+ }
360
+ /**
361
+ * `request` with the HTTP status, for endpoints whose answer depends on it (201 created, 200 updated).
362
+ * `bytes` returns a successful body as bytes (file downloads); problems are JSON either way.
363
+ */
364
+ async send(method, path, body, options = {}, as = "json") {
155
365
  const url = `${this.baseUrl}${path}`;
156
366
  const headers = {
157
367
  authorization: `Bearer ${this.apiKey}`,
158
- accept: "application/json",
159
- "user-agent": "formfeed-sdk-ts/0.1"
368
+ accept: as === "bytes" ? "*/*" : "application/json",
369
+ "user-agent": "formfeed-sdk-ts/0.3"
160
370
  };
161
- if (body !== void 0) headers["content-type"] = "application/json";
371
+ const isForm = typeof FormData !== "undefined" && body instanceof FormData;
372
+ if (body !== void 0 && !isForm) headers["content-type"] = "application/json";
162
373
  if (options.idempotencyKey) headers["idempotency-key"] = options.idempotencyKey;
163
374
  let attempt = 0;
164
375
  for (; ; ) {
@@ -170,7 +381,7 @@ var Formfeed = class {
170
381
  res = await this.fetchImpl(url, {
171
382
  method,
172
383
  headers,
173
- body: body === void 0 ? void 0 : JSON.stringify(body),
384
+ body: body === void 0 ? void 0 : isForm ? body : JSON.stringify(body),
174
385
  signal: controller.signal
175
386
  });
176
387
  } catch (e) {
@@ -188,9 +399,15 @@ var Formfeed = class {
188
399
  await sleep(this.backoff(attempt, res.headers.get("retry-after")), options.signal);
189
400
  continue;
190
401
  }
191
- if (res.status === 204) return void 0;
402
+ if (res.status === 204) return { status: 204, body: void 0 };
403
+ if (as === "bytes" && res.ok) return { status: res.status, body: new Uint8Array(await res.arrayBuffer()) };
192
404
  const text = await res.text();
193
- const json = text ? JSON.parse(text) : null;
405
+ let json = null;
406
+ try {
407
+ json = text ? JSON.parse(text) : null;
408
+ } catch {
409
+ if (res.ok) throw new FormfeedError("invalid_response", `the API answered HTTP ${res.status} with a body that is not JSON`, res.status);
410
+ }
194
411
  if (!res.ok) {
195
412
  const problem = json ?? {};
196
413
  throw new FormfeedError(
@@ -201,7 +418,7 @@ var Formfeed = class {
201
418
  res.headers.get("x-request-id")
202
419
  );
203
420
  }
204
- return json;
421
+ return { status: res.status, body: json };
205
422
  }
206
423
  }
207
424
  backoff(attempt, retryAfter) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@formfeed/sdk",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Formfeed API client: renders, templates, webhooks. No dependencies, Web APIs only.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/types/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { Formfeed, FormfeedError } from './lib/client.cjs';
2
- export type { Template, TemplateCreate, TemplateFiles, TemplateKind, TemplateListOptions, TemplateVersion, TemplateVersionCreate, VersionStatus, BatchRequest, Engine, FormfeedOptions, Job, OutputFormat, Problem, Region, Render, RenderListOptions, RenderRequest, RenderStatus, RequestOptions, Usage, WaitOptions, WebhookEndpoint, } from './lib/client.cjs';
2
+ export type { Template, TemplateCreate, TemplateFiles, TemplateKind, TemplateListOptions, TemplateValidation, TemplateVersion, TemplateVersionCreate, TemplateFile, OfficeTemplateKind, OfficeTemplateCreate, OfficeVersionCreate, OfficeFileUpload, ConvertOptions, VersionStatus, BatchRequest, Channel, ChannelList, ChannelMove, Brand, SharedPartial, SharedPartialPut, SharedPartialPutResult, Diagnostic, Engine, FileListOptions, FileUpload, FormfeedOptions, FormfeedTemplates, Job, LibraryFile, OutputFormat, PdfInfo, PdfOutputOptions, PdfPermission, PostProcessing, Problem, ProtectOptions, Region, Render, RenderListOptions, RenderRequest, RenderStatus, TemplateData, TypedRenderRequest, RequestOptions, SchemaChange, SchemaCheck, SchemaGuardOptions, Usage, WaitOptions, WatermarkOptions, WebhookEndpoint, WebhookEndpointCreate, WebhookEndpointUpdate, WebhookEnvironment, WebhookResend, ListenSession, ListenSessionOptions, RenderInput, } from './lib/client.cjs';
3
3
  export { parseWebhookEvent, verifyWebhookSignature } from './lib/webhooks.cjs';
4
4
  export type { VerifyOptions } from './lib/webhooks.cjs';
package/types/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { Formfeed, FormfeedError } from './lib/client.js';
2
- export type { Template, TemplateCreate, TemplateFiles, TemplateKind, TemplateListOptions, TemplateVersion, TemplateVersionCreate, VersionStatus, BatchRequest, Engine, FormfeedOptions, Job, OutputFormat, Problem, Region, Render, RenderListOptions, RenderRequest, RenderStatus, RequestOptions, Usage, WaitOptions, WebhookEndpoint, } from './lib/client.js';
2
+ export type { Template, TemplateCreate, TemplateFiles, TemplateKind, TemplateListOptions, TemplateValidation, TemplateVersion, TemplateVersionCreate, TemplateFile, OfficeTemplateKind, OfficeTemplateCreate, OfficeVersionCreate, OfficeFileUpload, ConvertOptions, VersionStatus, BatchRequest, Channel, ChannelList, ChannelMove, Brand, SharedPartial, SharedPartialPut, SharedPartialPutResult, Diagnostic, Engine, FileListOptions, FileUpload, FormfeedOptions, FormfeedTemplates, Job, LibraryFile, OutputFormat, PdfInfo, PdfOutputOptions, PdfPermission, PostProcessing, Problem, ProtectOptions, Region, Render, RenderListOptions, RenderRequest, RenderStatus, TemplateData, TypedRenderRequest, RequestOptions, SchemaChange, SchemaCheck, SchemaGuardOptions, Usage, WaitOptions, WatermarkOptions, WebhookEndpoint, WebhookEndpointCreate, WebhookEndpointUpdate, WebhookEnvironment, WebhookResend, ListenSession, ListenSessionOptions, RenderInput, } from './lib/client.js';
3
3
  export { parseWebhookEvent, verifyWebhookSignature } from './lib/webhooks.js';
4
4
  export type { VerifyOptions } from './lib/webhooks.js';