@vocalstack/sanity 0.3.0 → 0.4.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
@@ -105,7 +105,7 @@ The handler, `createVocalStackHandler({ … })`:
105
105
  | `allowedOrigins` | any | The Studio origins allowed to call the handler (CORS), e.g. `['https://example.sanity.studio']`. |
106
106
  | `apiURL` | `https://api.vocalstack.com` | |
107
107
 
108
- **How the audio reaches VocalStack.** The Studio sends the handler the file's asset id; the handler reads the asset from your dataset, checks that it is `audio/*`, and VocalStack fetches it from Sanity's CDN (`POST /v1/transcriptions { url }`). VocalStack does not fetch loopback or private addresses, so for those the handler reads the file and uploads it. The job runs on VocalStack, and the Studio polls the handler every 3 s. The key's workspace is billed per second, with a 5-minute minimum per transcription.
108
+ **How the audio reaches VocalStack.** The Studio sends the handler the file's asset id; the handler reads the asset from your dataset, checks that it is `audio/*`, and VocalStack fetches it from Sanity's CDN (`POST /v1/transcriptions { url }`). VocalStack does not fetch loopback or private addresses, so for those the handler reads the file and uploads it. The handler calls VocalStack through the [VocalStack JS SDK](https://www.npmjs.com/package/@vocalstack/js-sdk), which installs with the plugin; the Studio's bundle does not include it. The job runs on VocalStack, and the Studio polls the handler every 3 s. The key's workspace is billed per second, with a 5-minute minimum per transcription.
109
109
 
110
110
  ## How the handler knows the caller
111
111
 
package/dist/api.d.ts CHANGED
@@ -1,13 +1,17 @@
1
1
  /**
2
- * The handful of VocalStack API calls the plugin needs, on plain fetch (the
3
- * SDK is not on npm yet). Contract: https://api.vocalstack.com/v1/openapi.json
2
+ * The handful of VocalStack API calls the plugin needs, made through the VocalStack
3
+ * JS SDK (`@vocalstack/js-sdk`). Only the server handler uses this: the API key, and
4
+ * the SDK, stay out of the Studio's bundle.
5
+ * Contract: https://api.vocalstack.com/v1/openapi.json
4
6
  */
7
+ import { VocalStack } from '@vocalstack/js-sdk';
5
8
  import type { ConnectionWorkspace } from './wire.js';
6
9
  export declare const DEFAULT_API_URL = "https://api.vocalstack.com";
7
10
  /** Sent as the User-Agent of every call to VocalStack (they run in the
8
11
  * handler, on the server): VocalStack lists the transcriptions it makes
9
12
  * as made in Sanity. Keep it to package.json's version. */
10
- export declare const PLUGIN_VERSION = "0.3.0";
13
+ export declare const PLUGIN_VERSION = "0.4.0";
14
+ export declare const USER_AGENT = "VocalStack-Sanity/0.4.0";
11
15
  export declare const DEFAULT_DASHBOARD_URL = "https://app.vocalstack.com";
12
16
  export type JobState = 'cropping' | 'done' | 'failed' | 'fetching' | 'queued' | 'stopped' | 'transcribing';
13
17
  export type Job = {
@@ -57,22 +61,17 @@ export declare class VocalStackAPIError extends Error {
57
61
  status: number;
58
62
  constructor(status: number, code: string, message: string);
59
63
  }
64
+ type JobOptions = {
65
+ idempotencyKey: string;
66
+ name: string;
67
+ spokenLanguage?: string;
68
+ };
60
69
  export declare class VocalStackAPI {
61
- private apiKey;
62
- private baseURL;
70
+ readonly sdk: VocalStack;
63
71
  constructor(apiKey: string, baseURL?: string);
64
- private request;
65
72
  me(): Promise<Record<string, unknown>>;
66
- transcribeURL(url: string, opts: {
67
- idempotencyKey: string;
68
- name: string;
69
- spokenLanguage?: string;
70
- }): Promise<Transcription>;
71
- transcribeFile(file: Blob, fileName: string, opts: {
72
- idempotencyKey: string;
73
- name: string;
74
- spokenLanguage?: string;
75
- }): Promise<Transcription>;
73
+ transcribeURL(url: string, opts: JobOptions): Promise<Transcription>;
74
+ transcribeFile(file: Blob, fileName: string, opts: JobOptions): Promise<Transcription>;
76
75
  job(transcriptionId: string): Promise<Job>;
77
76
  /** Stop a job before it is done. Its job fails with `stopped`; what was transcribed so far stays in VocalStack. */
78
77
  stop(transcriptionId: string, reason?: string): Promise<unknown>;
@@ -86,3 +85,4 @@ export declare function accountLabel(me: Record<string, unknown>): string | unde
86
85
  * when the API does not say (an older VocalStack).
87
86
  */
88
87
  export declare function workspaceOf(me: Record<string, unknown>, baseURL?: string): ConnectionWorkspace | undefined;
88
+ export {};
package/dist/api.js CHANGED
@@ -1,12 +1,16 @@
1
1
  /**
2
- * The handful of VocalStack API calls the plugin needs, on plain fetch (the
3
- * SDK is not on npm yet). Contract: https://api.vocalstack.com/v1/openapi.json
2
+ * The handful of VocalStack API calls the plugin needs, made through the VocalStack
3
+ * JS SDK (`@vocalstack/js-sdk`). Only the server handler uses this: the API key, and
4
+ * the SDK, stay out of the Studio's bundle.
5
+ * Contract: https://api.vocalstack.com/v1/openapi.json
4
6
  */
7
+ import { VocalStack, VocalStackError } from '@vocalstack/js-sdk';
5
8
  export const DEFAULT_API_URL = 'https://api.vocalstack.com';
6
9
  /** Sent as the User-Agent of every call to VocalStack (they run in the
7
10
  * handler, on the server): VocalStack lists the transcriptions it makes
8
11
  * as made in Sanity. Keep it to package.json's version. */
9
- export const PLUGIN_VERSION = '0.3.0';
12
+ export const PLUGIN_VERSION = '0.4.0';
13
+ export const USER_AGENT = `VocalStack-Sanity/${PLUGIN_VERSION}`;
10
14
  export const DEFAULT_DASHBOARD_URL = 'https://app.vocalstack.com';
11
15
  export class VocalStackAPIError extends Error {
12
16
  code;
@@ -17,50 +21,60 @@ export class VocalStackAPIError extends Error {
17
21
  this.status = status;
18
22
  }
19
23
  }
24
+ /** The SDK's errors as the handler reads them: VocalStack's status, code and message. */
25
+ function toAPIError(err) {
26
+ if (!(err instanceof VocalStackError))
27
+ return err;
28
+ // VocalStack was not reached: fetch's own error says why.
29
+ if (err.status === undefined)
30
+ return err.cause ?? err;
31
+ // An answer that is not VocalStack's error body (a proxy's page, say).
32
+ if (err.code === 'internal' && /^unexpected error \(status \d+\)$/.test(err.message))
33
+ return new VocalStackAPIError(err.status, 'http_error', `VocalStack answered ${err.status}`);
34
+ return new VocalStackAPIError(err.status, err.code, err.message);
35
+ }
36
+ const call = async (run) => {
37
+ try {
38
+ return (await run());
39
+ }
40
+ catch (err) {
41
+ throw toAPIError(err);
42
+ }
43
+ };
44
+ const createOptions = (opts) => ({ name: opts.name, settings: opts.spokenLanguage ? { spokenLanguage: opts.spokenLanguage } : undefined });
20
45
  export class VocalStackAPI {
21
- apiKey;
22
- baseURL;
46
+ sdk;
23
47
  constructor(apiKey, baseURL = DEFAULT_API_URL) {
24
- this.apiKey = apiKey;
25
- this.baseURL = baseURL;
26
- }
27
- async request(method, path, body, headers = {}) {
28
- const init = { headers: { accept: 'application/json', authorization: `Bearer ${this.apiKey}`, 'user-agent': `VocalStack-Sanity/${PLUGIN_VERSION}`, ...headers }, method };
29
- if (body instanceof FormData)
30
- init.body = body;
31
- else if (body !== undefined) {
32
- init.body = JSON.stringify(body);
33
- init.headers['content-type'] = 'application/json';
34
- }
35
- const res = await fetch(`${this.baseURL}${path}`, init);
36
- const data = await res.json().catch(() => undefined);
37
- if (!res.ok) {
38
- const err = (data?.error ?? data);
39
- throw new VocalStackAPIError(res.status, err?.code ?? 'http_error', err?.message ?? `VocalStack answered ${res.status}`);
40
- }
41
- return data;
48
+ this.sdk = new VocalStack({
49
+ apiKey,
50
+ baseUrl: baseURL,
51
+ // The Studio asks again by itself (it polls), so a call is made once.
52
+ maxRetries: 0,
53
+ fetch: (input, init) => {
54
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
55
+ headers.set('user-agent', USER_AGENT);
56
+ return fetch(input, { ...init, headers });
57
+ },
58
+ });
42
59
  }
43
60
  me() {
44
- return this.request('GET', '/v1/me');
61
+ return call(() => this.sdk.me.get());
45
62
  }
46
63
  transcribeURL(url, opts) {
47
- return this.request('POST', '/v1/transcriptions', { name: opts.name, settings: opts.spokenLanguage ? { spokenLanguage: opts.spokenLanguage } : undefined, url }, { 'idempotency-key': opts.idempotencyKey });
64
+ return call(() => this.sdk.transcriptions.create({ ...createOptions(opts), url }, { idempotencyKey: opts.idempotencyKey }));
48
65
  }
49
66
  transcribeFile(file, fileName, opts) {
50
- const form = new FormData();
51
- form.append('options', JSON.stringify({ name: opts.name, settings: opts.spokenLanguage ? { spokenLanguage: opts.spokenLanguage } : undefined }));
52
- form.append('file', file, fileName);
53
- return this.request('POST', '/v1/transcriptions', form, { 'idempotency-key': opts.idempotencyKey });
67
+ return call(() => this.sdk.transcriptions.create({ ...createOptions(opts), file, fileName }, { idempotencyKey: opts.idempotencyKey }));
54
68
  }
55
69
  job(transcriptionId) {
56
- return this.request('GET', `/v1/transcriptions/${encodeURIComponent(transcriptionId)}/job`);
70
+ return call(() => this.sdk.transcriptions.job(transcriptionId));
57
71
  }
58
72
  /** Stop a job before it is done. Its job fails with `stopped`; what was transcribed so far stays in VocalStack. */
59
73
  stop(transcriptionId, reason) {
60
- return this.request('POST', `/v1/transcriptions/${encodeURIComponent(transcriptionId)}/stop`, { reason: reason ?? null });
74
+ return call(() => this.sdk.transcriptions.stop(transcriptionId, reason));
61
75
  }
62
76
  transcript(transcriptionId) {
63
- return this.request('GET', `/v1/transcriptions/${encodeURIComponent(transcriptionId)}/transcript`);
77
+ return call(() => this.sdk.transcriptions.transcript(transcriptionId));
64
78
  }
65
79
  }
66
80
  /** A short label for the connected account, from whatever `/v1/me` carries. */
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { Box, Button, Card, Flex, Stack, Text, TextArea } from '@sanity/ui';
2
+ import { Box, Button, Card, Flex, Text, TextArea } from '@sanity/ui';
3
3
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
4
4
  import { set, setIfMissing, unset, useFormValue } from 'sanity';
5
5
  import { findAudio, jobName, POLL_MS, restored, siblingFileRefs, TRANSCRIPT_TYPE } from '../core.js';
@@ -179,7 +179,7 @@ export function TranscriptInput(props) {
179
179
  else {
180
180
  action = (_jsxs(Flex, { gap: 2, wrap: "wrap", children: [_jsx(Button, { disabled: busy || starting || readOnly || !asset, onClick: transcribe, text: busy || starting ? 'Transcribing…' : status === 'done' || isLost ? 'Transcribe again' : 'Transcribe', tone: "primary" }), busy && _jsx(Button, { disabled: stopping || readOnly, mode: "ghost", onClick: stop, text: stopping ? 'Stopping…' : 'Stop' })] }));
181
181
  }
182
- return (_jsx(Card, { border: true, padding: 3, radius: 2, children: _jsxs(Stack, { space: 3, children: [_jsxs(Flex, { align: "center", gap: 3, justify: "space-between", wrap: "wrap", children: [_jsx(Logo, { height: 14 }), workspace && (_jsxs(Flex, { align: "center", "data-testid": "vocalstack-workspace", gap: 2, style: { minWidth: 0 }, children: [_jsx(Text, { ...muted, children: "Workspace" }), _jsx(WorkspaceMark, { size: 18, workspace: workspace }), _jsx(Text, { size: 1, textOverflow: "ellipsis", weight: "medium", children: workspace.name }), _jsx(Button, { "aria-expanded": changing, fontSize: 1, mode: "bleed", onClick: () => setChanging((c) => !c), padding: 2, text: "Change" })] }))] }), workspace && changing && (_jsx(Card, { border: true, padding: 2, radius: 2, children: _jsxs(Text, { ...muted, children: ["Transcriptions made here go to the workspace this Studio\u2019s VocalStack API key was made in. To use another workspace, set ", _jsx("code", { children: "VOCALSTACK_API_KEY" }), ' ', "where the VocalStack handler runs to a key made in that workspace: in the VocalStack Dashboard, switch to the workspace, then Developers \u2192 API keys."] }) })), action, busy && (_jsxs(Stack, { space: 2, children: [_jsxs(Text, { ...muted, children: [PHASES[progress.phase ?? 'queued'] ?? progress.phase, progress.progress ? ` · ${progress.progress}%` : '…', progress.audio?.totalS ? ` · ${clock(progress.audio.processedS)} of ${clock(progress.audio.totalS)}` : ''] }), _jsx(Card, { radius: 1, style: { height: 4, overflow: 'hidden' }, tone: "transparent", children: _jsx("div", { style: { background: accent, height: '100%', transition: 'width .4s', width: `${progress.progress || 2}%` } }) })] })), notice && (_jsx(Card, { padding: 2, radius: 2, tone: "positive", children: _jsx(Text, { size: 1, children: notice }) })), !busy && status === 'done' && !shownError && (_jsxs(Text, { ...muted, children: ["Transcribed", value?.language ? ` (${value.language})` : '', value?.sentences?.length ? ` · ${value.sentences.length} sentences with timings` : '', "."] })), shownError && (_jsx(Card, { padding: 2, radius: 2, tone: "critical", children: _jsx(Text, { size: 1, children: shownError }) })), (partialText || value?.transcript) && (_jsx(Box, { children: _jsx(TextArea, { onChange: (e) => {
182
+ return (_jsx(Card, { border: true, padding: 3, radius: 2, children: _jsxs(Flex, { direction: "column", gap: 3, children: [_jsxs(Flex, { align: "center", gap: 3, justify: "space-between", wrap: "wrap", children: [_jsx(Logo, { height: 14 }), workspace && (_jsxs(Flex, { align: "center", "data-testid": "vocalstack-workspace", gap: 2, style: { minWidth: 0 }, children: [_jsx(Text, { ...muted, children: "Workspace" }), _jsx(WorkspaceMark, { size: 18, workspace: workspace }), _jsx(Text, { size: 1, textOverflow: "ellipsis", weight: "medium", children: workspace.name }), _jsx(Button, { "aria-expanded": changing, fontSize: 1, mode: "bleed", onClick: () => setChanging((c) => !c), padding: 2, text: "Change" })] }))] }), workspace && changing && (_jsx(Card, { border: true, padding: 2, radius: 2, children: _jsxs(Text, { ...muted, children: ["Transcriptions made here go to the workspace this Studio\u2019s VocalStack API key was made in. To use another workspace, set ", _jsx("code", { children: "VOCALSTACK_API_KEY" }), ' ', "where the VocalStack handler runs to a key made in that workspace: in the VocalStack Dashboard, switch to the workspace, then Developers \u2192 API keys."] }) })), action, busy && (_jsxs(Flex, { direction: "column", gap: 2, children: [_jsxs(Text, { ...muted, children: [PHASES[progress.phase ?? 'queued'] ?? progress.phase, progress.progress ? ` · ${progress.progress}%` : '…', progress.audio?.totalS ? ` · ${clock(progress.audio.processedS)} of ${clock(progress.audio.totalS)}` : ''] }), _jsx(Card, { radius: 1, style: { height: 4, overflow: 'hidden' }, tone: "transparent", children: _jsx("div", { style: { background: accent, height: '100%', transition: 'width .4s', width: `${progress.progress || 2}%` } }) })] })), notice && (_jsx(Card, { padding: 2, radius: 2, tone: "positive", children: _jsx(Text, { size: 1, children: notice }) })), !busy && status === 'done' && !shownError && (_jsxs(Text, { ...muted, children: ["Transcribed", value?.language ? ` (${value.language})` : '', value?.sentences?.length ? ` · ${value.sentences.length} sentences with timings` : '', "."] })), shownError && (_jsx(Card, { padding: 2, radius: 2, tone: "critical", children: _jsx(Text, { size: 1, children: shownError }) })), (partialText || value?.transcript) && (_jsx(Box, { children: _jsx(TextArea, { onChange: (e) => {
183
183
  const text = e.currentTarget.value;
184
184
  onChange([setIfMissing({ _type: TRANSCRIPT_TYPE }), text ? set(text, ['transcript']) : unset(['transcript'])]);
185
185
  }, readOnly: readOnly || Boolean(partialText), rows: 10, value: partialText ?? value?.transcript ?? '' }) }))] }) }));
package/dist/schema.d.ts CHANGED
@@ -1,12 +1,16 @@
1
+ import type { ObjectDefinition, PreviewConfig } from 'sanity';
1
2
  import type { VocalStackPluginOptions } from './types.js';
3
+ import { TRANSCRIPT_TYPE } from './core.js';
4
+ /** Spelled out, so the published types read the same whichever Sanity major built them. */
5
+ export type TranscriptTypeDefinition = {
6
+ name: typeof TRANSCRIPT_TYPE;
7
+ type: 'object';
8
+ } & Omit<ObjectDefinition, 'preview'> & {
9
+ preview?: PreviewConfig<Record<string, string>, Record<never, any>>;
10
+ };
2
11
  /**
3
12
  * `vocalstack.transcript`: an object field to put next to a `file` field. Its input
4
13
  * renders the Transcribe button, the progress and the editable transcript; the rest
5
14
  * is written by the plugin and readable with GROQ like any field.
6
15
  */
7
- export declare const transcriptType: (options: VocalStackPluginOptions) => {
8
- type: "object";
9
- name: "vocalstack.transcript";
10
- } & Omit<import("sanity").ObjectDefinition, "preview"> & {
11
- preview?: import("sanity").PreviewConfig<Record<string, string>, Record<never, any>> | undefined;
12
- };
16
+ export declare const transcriptType: (options: VocalStackPluginOptions) => TranscriptTypeDefinition;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vocalstack/sanity",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "VocalStack for Sanity Studio: a Transcribe button next to every audio file.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -36,16 +36,16 @@
36
36
  }
37
37
  },
38
38
  "devDependencies": {
39
- "@sanity/mutator": "4.22.1",
40
- "@sanity/ui": "^3.1.11",
41
- "@types/react": "^19.0.0",
42
- "groq-js": "1.30.3",
43
- "mendoza": "3.0.8",
44
- "playwright-core": "1.64.1",
45
- "react": "^19.1.0",
46
- "react-dom": "^19.1.0",
47
- "sanity": "4.22.1",
48
- "styled-components": "^6.1.15",
39
+ "@sanity/mutator": "6.25.0",
40
+ "@sanity/ui": "^4.4.14",
41
+ "@types/react": "^19.3.3",
42
+ "groq-js": "2.0.4",
43
+ "mendoza": "6.0.0",
44
+ "playwright-core": "1.65.1",
45
+ "react": "^19.3.1",
46
+ "react-dom": "^19.3.1",
47
+ "sanity": "6.25.0",
48
+ "styled-components": "^6.7.0",
49
49
  "typescript": "^5.6.0"
50
50
  },
51
51
  "repository": {
@@ -54,5 +54,8 @@
54
54
  },
55
55
  "engines": {
56
56
  "node": ">=20"
57
+ },
58
+ "dependencies": {
59
+ "@vocalstack/js-sdk": "2.3.1"
57
60
  }
58
61
  }