@vocalstack/payload 0.9.1 → 0.10.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/README.md CHANGED
@@ -176,7 +176,7 @@ The translation is saved on the document, and where VocalStack can read the lang
176
176
 
177
177
  When VocalStack does not answer (an outage, an upgrade), the endpoints say *VocalStack is unavailable, try again shortly.* instead of waiting.
178
178
 
179
- **How the audio reaches VocalStack.** If the file has a public address, VocalStack fetches it (`POST /v1/transcriptions { url }`). Otherwise (localhost, a private network) the plugin uploads the bytes. Either way the job runs on VocalStack, and the admin polls every 3 s. The connected workspace is billed per second, with a 5-minute minimum per transcription.
179
+ **How the audio reaches VocalStack.** If the file has a public address, VocalStack fetches it (`POST /v1/transcriptions { url }`). Otherwise (localhost, a private network) the plugin uploads the bytes. If VocalStack's fetch of a public address fails because of the link (its server refuses VocalStack, as addresses signed for one viewer, IP address or region do; it answers with nothing; or it cannot be reached or found from VocalStack: job `errorCode` `link_refused`, `link_empty`, `link_unreachable` or `link_not_found`), the plugin reads the file itself and uploads the bytes in a new job, once. The job's own reason is shown only when that fails too. Either way the job runs on VocalStack, and the admin polls every 3 s. The connected workspace is billed per second, with a 5-minute minimum per transcription.
180
180
 
181
181
  ## The workspace
182
182
 
@@ -1,7 +1,7 @@
1
1
  import { DEFAULT_API_URL, VocalStackAPI } from '../api.js';
2
2
  import { resolveAPIKey } from '../settings.js';
3
3
  import { attachWords } from '../text.js';
4
- import { apiError, checkJob, locate, toSentences } from './transcribe.js';
4
+ import { apiError, checkJob, locate, refileWith, toSentences } from './transcribe.js';
5
5
  const OVER = new Set(['done', 'failed', 'cropping', 'ended', 'finalized']);
6
6
  /**
7
7
  * GET /:id/vocalstack/stream: the job live, as Server-Sent Events. The server holds
@@ -57,8 +57,10 @@ export function streamEndpoint(collection, options, rowFields) {
57
57
  };
58
58
  // VocalStack signals the end several ways (progress, state, socket close); check once at a time.
59
59
  let settling;
60
- const settle = () => (settling ??= checkJob(api, target, transcriptionId)
61
- .then((r) => (r.status === 'processing' ? undefined : finish(r)), (err) => finish({ error: err.message, status: 'failed' }))
60
+ const settle = () => (settling ??= checkJob(api, target, transcriptionId, refileWith(req, api, target, collection, options.spokenLanguage))
61
+ .then(
62
+ // A job started again from the file's bytes (its link failed) has a new id: close, and EventSource reconnects to follow it.
63
+ (r) => (r.status === 'processing' && (!r.vocalstack || r.vocalstack.transcriptionId === transcriptionId) ? undefined : finish(r)), (err) => finish({ error: err.message, status: 'failed' }))
62
64
  .finally(() => (settling = undefined)));
63
65
  // What the page has been told: settled sentences by id, the words of committed
64
66
  // segments (sentences take theirs by time), and the words heard since.
@@ -1,6 +1,6 @@
1
1
  import type { CollectionSlug, Endpoint, PayloadRequest } from 'payload';
2
2
  import type { ArrayRow, AudioFieldConfig, StatusResponse, TranscriptSentence, VocalStackFieldData, VocalStackPluginOptions } from '../types.js';
3
- import { type Transcript, VocalStackAPI } from '../api.js';
3
+ import { type Job, type Transcript, type Transcription, VocalStackAPI } from '../api.js';
4
4
  /** Whether the signed-in user may update this document, by the collection's own `access.update`. */
5
5
  export declare function canUpdate(req: PayloadRequest, collection: CollectionSlug, id: number | string): Promise<boolean>;
6
6
  type Patch = ((current: VocalStackFieldData) => VocalStackFieldData) | VocalStackFieldData;
@@ -20,11 +20,22 @@ export declare function locate(req: PayloadRequest, collection: CollectionSlug,
20
20
  /** A transcript's sentences, each with its words. */
21
21
  export declare function toSentences(t: Pick<Transcript, 'segments' | 'sentences'>): TranscriptSentence[];
22
22
  export declare function apiError(err: unknown): Response;
23
+ /** Start a job for the target's file: by link when VocalStack can fetch it, otherwise (or when `asFile`) by sending the bytes. */
24
+ export declare function startJob(req: PayloadRequest, api: VocalStackAPI, target: Target, call: {
25
+ idempotencyKey: string;
26
+ name: string;
27
+ spokenLanguage?: string;
28
+ }, asFile?: boolean): Promise<Transcription & {
29
+ job: Job;
30
+ }>;
31
+ /** Sends the file's bytes in place of a link VocalStack could not use; the new job is saved on the target. */
32
+ export declare function refileWith(req: PayloadRequest, api: VocalStackAPI, target: Target, collection: CollectionSlug, spokenLanguage?: string): () => Promise<StatusResponse>;
23
33
  /**
24
34
  * Where a job stands, saving the outcome on the document once it is over: the
25
- * whole transcript when done, the reason when it failed.
35
+ * whole transcript when done, the reason when it failed. With `refile`, a job whose
36
+ * link failed (see REFILE_CODES) is started again from the file's bytes.
26
37
  */
27
- export declare function checkJob(api: VocalStackAPI, target: Target, transcriptionId: string): Promise<StatusResponse>;
38
+ export declare function checkJob(api: VocalStackAPI, target: Target, transcriptionId: string, refile?: () => Promise<StatusResponse>): Promise<StatusResponse>;
28
39
  /**
29
40
  * POST /:id/vocalstack/transcribe and GET /:id/vocalstack/status. With no query
30
41
  * they act on the upload document itself; with `?field=<array>&row=<row id>` on one row.
@@ -18,6 +18,8 @@ function serially(key, run) {
18
18
  }
19
19
  /** Finished jobs being saved, so that every "done" signal for one job shares a single save. */
20
20
  const finishing = new Map();
21
+ /** Jobs whose link failed, being started again from the bytes: one new job per failed one. */
22
+ const refiling = new Map();
21
23
  /** Whether the signed-in user may update this document, by the collection's own `access.update`. */
22
24
  export async function canUpdate(req, collection, id) {
23
25
  if (!req.user)
@@ -113,11 +115,39 @@ export function apiError(err) {
113
115
  }
114
116
  return json({ error: err instanceof Error ? err.message : String(err) }, 500);
115
117
  }
118
+ /**
119
+ * Link failures that sending the bytes can get past: the file's server refused
120
+ * VocalStack (signed for one viewer, IP address or region), answered with nothing,
121
+ * or could not be reached or found from VocalStack. Payload may still read the file.
122
+ */
123
+ const REFILE_CODES = new Set(['link_empty', 'link_not_found', 'link_refused', 'link_unreachable']);
124
+ /** Start a job for the target's file: by link when VocalStack can fetch it, otherwise (or when `asFile`) by sending the bytes. */
125
+ export async function startJob(req, api, target, call, asFile = false) {
126
+ const url = await target.url();
127
+ if (!url)
128
+ throw new Error('There is no audio file here.');
129
+ const tx = !asFile && isPublicURL(url)
130
+ ? await api.transcribeURL(url, call)
131
+ : await api.transcribeFile(await fetchFile(req, url), decodeURIComponent(new URL(url).pathname.split('/').pop() || target.fileName), call);
132
+ if (!tx.job)
133
+ throw new Error('VocalStack did not start a job for this file.');
134
+ return tx;
135
+ }
136
+ /** Sends the file's bytes in place of a link VocalStack could not use; the new job is saved on the target. */
137
+ export function refileWith(req, api, target, collection, spokenLanguage) {
138
+ return async () => {
139
+ const id = req.routeParams?.id;
140
+ const tx = await startJob(req, api, target, { idempotencyKey: `payload:${collection}:${id}:${randomUUID()}`, name: target.name, spokenLanguage }, true);
141
+ const vocalstack = await target.save({ error: null, status: 'processing', transcriptionId: tx.id });
142
+ return { phase: tx.job.state, progress: 0, status: 'processing', vocalstack };
143
+ };
144
+ }
116
145
  /**
117
146
  * Where a job stands, saving the outcome on the document once it is over: the
118
- * whole transcript when done, the reason when it failed.
147
+ * whole transcript when done, the reason when it failed. With `refile`, a job whose
148
+ * link failed (see REFILE_CODES) is started again from the file's bytes.
119
149
  */
120
- export async function checkJob(api, target, transcriptionId) {
150
+ export async function checkJob(api, target, transcriptionId, refile) {
121
151
  let job;
122
152
  try {
123
153
  job = await api.job(transcriptionId);
@@ -131,6 +161,18 @@ export async function checkJob(api, target, transcriptionId) {
131
161
  }
132
162
  if (job.state === 'stopped' || (job.state === 'failed' && job.errorCode === 'stopped'))
133
163
  return restore(target);
164
+ if (job.state === 'failed' && refile && job.errorCode && REFILE_CODES.has(job.errorCode)) {
165
+ let again = refiling.get(transcriptionId);
166
+ if (!again) {
167
+ again = refile();
168
+ refiling.set(transcriptionId, again);
169
+ void again.catch(() => undefined).then(() => setTimeout(() => refiling.delete(transcriptionId), 60_000));
170
+ }
171
+ // Reading or sending the file failed too: report the link's reason, as before.
172
+ const started = await again.catch(() => undefined);
173
+ if (started)
174
+ return started;
175
+ }
134
176
  if (job.state === 'failed' || job.state === 'cropping') {
135
177
  const error = job.state === 'cropping' ? 'VocalStack is waiting for a crop window; open the transcription in VocalStack.' : (job.error ?? 'The transcription failed.');
136
178
  return { error, status: 'failed', vocalstack: await target.save({ error, status: 'failed' }) };
@@ -200,17 +242,12 @@ export function transcribeEndpoints(collection, options, rowFields) {
200
242
  return target;
201
243
  if (target.data.status === 'processing')
202
244
  return json({ status: 'processing', vocalstack: target.data });
203
- const url = await target.url();
204
- if (!url)
245
+ if (!(await target.url()))
205
246
  return json({ error: 'There is no audio file here.' }, 400);
206
247
  const api = new VocalStackAPI(apiKey, apiURL);
207
248
  const call = { idempotencyKey: `payload:${collection}:${id}:${randomUUID()}`, name: target.name, spokenLanguage: options.spokenLanguage };
208
249
  try {
209
- const tx = isPublicURL(url)
210
- ? await api.transcribeURL(url, call)
211
- : await api.transcribeFile(await fetchFile(req, url), decodeURIComponent(new URL(url).pathname.split('/').pop() || target.fileName), call);
212
- if (!tx.job)
213
- throw new Error('VocalStack did not start a job for this file.');
250
+ const tx = await startJob(req, api, target, call);
214
251
  const vocalstack = await target.save({ error: null, recordingId: null, status: 'processing', transcriptionId: tx.id });
215
252
  return json({ phase: tx.job.state, progress: 0, status: 'processing', vocalstack }, 202);
216
253
  }
@@ -236,7 +273,8 @@ export function transcribeEndpoints(collection, options, rowFields) {
236
273
  if (!apiKey)
237
274
  return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
238
275
  try {
239
- return json(await checkJob(new VocalStackAPI(apiKey, apiURL), target, field.transcriptionId));
276
+ const api = new VocalStackAPI(apiKey, apiURL);
277
+ return json(await checkJob(api, target, field.transcriptionId, refileWith(req, api, target, collection, options.spokenLanguage)));
240
278
  }
241
279
  catch (err) {
242
280
  return apiError(err);
@@ -269,7 +307,7 @@ export function transcribeEndpoints(collection, options, rowFields) {
269
307
  catch (err) {
270
308
  // Too late to stop: the job ended meanwhile, so take its outcome instead.
271
309
  if (err instanceof VocalStackAPIError && err.status === 409)
272
- return json(await checkJob(api, target, transcriptionId).catch(() => restore(target)));
310
+ return json(await checkJob(api, target, transcriptionId, refileWith(req, api, target, collection, options.spokenLanguage)).catch(() => restore(target)));
273
311
  return apiError(err);
274
312
  }
275
313
  },
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  export declare const PACKAGE_NAME = "@vocalstack/payload";
2
- export declare const VERSION = "0.9.1";
2
+ export declare const VERSION = "0.10.0";
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // Written by scripts/version.mjs from package.json. Do not edit.
2
2
  export const PACKAGE_NAME = "@vocalstack/payload";
3
- export const VERSION = "0.9.1";
3
+ export const VERSION = "0.10.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vocalstack/payload",
3
- "version": "0.9.1",
3
+ "version": "0.10.0",
4
4
  "description": "VocalStack for Payload CMS: transcribe audio, translate it into other languages and read it aloud, kept in your own database and storage.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -50,6 +50,6 @@
50
50
  },
51
51
  "packageManager": "pnpm@10.15.1",
52
52
  "dependencies": {
53
- "@vocalstack/js-sdk": "2.0.0"
53
+ "@vocalstack/js-sdk": "2.2.0"
54
54
  }
55
55
  }