@vocalstack/sanity 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 VocalStack
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,126 @@
1
- # Temporary Holding Version
1
+ # @vocalstack/sanity
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ VocalStack for [Sanity](https://www.sanity.io) Studio 3 and later: a **Transcribe** button next to every audio file. The transcript is saved on the document as text plus timed sentences.
4
+
5
+ ## Install
6
+
7
+ Not on npm. Install from this repo; `dist/` is committed, so nothing builds on install (run `pnpm build` and commit `dist/` with every change):
8
+
9
+ ```sh
10
+ npm i github:vocalstack/sanity-plugin
11
+ ```
12
+
13
+ VocalStack API keys are for servers: the API refuses a key sent from a web page. So the plugin has two halves, the Studio plugin and a small server handler that holds the key.
14
+
15
+ **1. The handler.** A Web-standard `(Request) => Promise<Response>`. In a Next.js app (most Sanity sites have one):
16
+
17
+ ```ts
18
+ // app/api/vocalstack/[...path]/route.ts
19
+ import { createVocalStackHandler } from '@vocalstack/sanity/server'
20
+
21
+ const handler = createVocalStackHandler({
22
+ apiKey: process.env.VOCALSTACK_API_KEY, // the default; a vs_key_… key with Read and Write
23
+ sanity: {
24
+ projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID!,
25
+ dataset: process.env.NEXT_PUBLIC_SANITY_DATASET!,
26
+ token: process.env.SANITY_API_READ_TOKEN!, // a Viewer token is enough
27
+ },
28
+ })
29
+
30
+ export { handler as GET, handler as OPTIONS, handler as POST }
31
+ ```
32
+
33
+ Any other host works the same way: Remix, Hono, Bun, Deno, Cloudflare Workers, a Node server with a Fetch adapter. The handler matches the end of the path, so mount it under any prefix.
34
+
35
+ **2. The Studio plugin.**
36
+
37
+ ```ts
38
+ // sanity.config.ts
39
+ import { vocalstack } from '@vocalstack/sanity'
40
+
41
+ export default defineConfig({
42
+ // …
43
+ plugins: [
44
+ vocalstack({
45
+ handlerURL: 'https://www.example.com/api/vocalstack', // or '/api/vocalstack' for a Studio embedded in the same Next.js app
46
+ }),
47
+ ],
48
+ })
49
+ ```
50
+
51
+ Then add a transcript field next to the audio:
52
+
53
+ ```ts
54
+ defineType({
55
+ name: 'episode',
56
+ type: 'document',
57
+ fields: [
58
+ defineField({ name: 'title', type: 'string' }),
59
+ defineField({ name: 'audio', type: 'file', options: { accept: 'audio/*' } }),
60
+ defineField({ name: 'transcript', type: 'vocalstack.transcript' }),
61
+ ],
62
+ })
63
+ ```
64
+
65
+ ## What it adds
66
+
67
+ - **A `vocalstack.transcript` field type**, to put next to a `file` field (at the top level of a document, or inside an object). Its input has:
68
+ - a **Transcribe** button, shown when the sibling file is `audio/*`. It shows progress and survives a reload mid-job, because `recordingId` and `status` are saved on the document. **Stop** ends a job you no longer want: the field goes back to how it was (an earlier transcript stays), and VocalStack keeps what it transcribed before the stop.
69
+ - the stored value:
70
+ - `transcript`: text you can edit; paragraphs break on a speaker change or a pause.
71
+ - `sentences`: `[{ start, end, speaker, text }]` in seconds.
72
+ - `status` (`idle`, `processing`, `done` or `failed`), `language`, `error`, `recordingId`, `transcriptionId` and `transcribedAt`.
73
+ - **A "Transcribe audio" document action** on every document type with a transcript field. It starts a job for each transcript field next to an audio file; the field follows the job from there.
74
+ - **The handler** (`@vocalstack/sanity/server`): `GET …/connection`, `POST …/transcriptions`, `GET …/recordings/:id/job` and `POST …/recordings/:id/stop`.
75
+
76
+ Like any edit in the Studio, the transcript lands in the draft; publish to make it public. Transcripts are plain fields, so GROQ reads them like any other:
77
+
78
+ ```groq
79
+ *[_type == "episode"]{ title, "text": transcript.transcript, "captions": transcript.sentences }
80
+ ```
81
+
82
+ ## Options
83
+
84
+ The Studio plugin, `vocalstack({ … })`:
85
+
86
+ | Option | Default | |
87
+ |---|---|---|
88
+ | `handlerURL` | required | Where the handler is mounted. The Studio calls only this URL. |
89
+
90
+ A transcript field, `options: { … }`:
91
+
92
+ | Option | Default | |
93
+ |---|---|---|
94
+ | `audioField` | the first sibling `file` field holding `audio/*` | The name of the sibling file field to transcribe. |
95
+
96
+ The handler, `createVocalStackHandler({ … })`:
97
+
98
+ | Option | Default | |
99
+ |---|---|---|
100
+ | `apiKey` | `process.env.VOCALSTACK_API_KEY` | A `vs_key_…` key with Read and Write. |
101
+ | `sanity` | required | `{ projectId, dataset, token, apiVersion?, apiHost?, useProjectHostname? }`: the Studio's dataset, and a token that can read it. `apiHost` and `useProjectHostname` work as in `@sanity/client`, for a custom API domain. |
102
+ | `spokenLanguage` | auto-detect | A Whisper language code (`en`, `ro`, …). |
103
+ | `fileURL` | the asset's URL on Sanity's CDN | `(asset) => string`: the audio's address. Return a signed URL if your assets are private. |
104
+ | `allowedOrigins` | any | The Studio origins allowed to call the handler (CORS), e.g. `['https://example.sanity.studio']`. |
105
+ | `apiURL` | `https://api.vocalstack.com` | |
106
+
107
+ **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 account is billed per second, with a 5-minute minimum per transcription.
108
+
109
+ ## How the handler knows the caller
110
+
111
+ The handler only answers someone signed in to the Studio with permission to edit the dataset:
112
+
113
+ 1. The Studio makes a random secret and, with the editor's own Sanity login, creates a document `vocalstack-session.<sha256 of the secret>` (type `vocalstack.session`).
114
+ 2. Every call to the handler carries `Authorization: Bearer <secret>`. The handler hashes it and looks the document up with its own token; a session is good for 12 hours from the document's `_updatedAt`.
115
+
116
+ Only someone who can write to the dataset can create a session. The id has a dot in it, so Sanity never serves it to unauthenticated requests, even from a public dataset; project members who can read the dataset see the hash, never the secret. Expired sessions are swept by the Studio. The handler keeps no cookies, so CORS from any origin is safe; `allowedOrigins` narrows it further.
117
+
118
+ The VocalStack key never reaches a browser: it lives in the handler's environment only. Anyone who can edit the dataset can start, follow and stop transcriptions on that key's account.
119
+
120
+ ## Testing
121
+
122
+ `e2e/run.sh` runs a real Studio on a fake Content Lake against the handler and a real VocalStack, in Chromium; see [e2e/README.md](e2e/README.md).
123
+
124
+ ## One-click connect
125
+
126
+ Not in this version. The handler has no storage of its own to keep a connected key in, and the Studio cannot redeem a connect code (the API refuses it from a web page), so the key goes in `VOCALSTACK_API_KEY`. Create one with Read and Write permissions under [Developers → API keys](https://app.vocalstack.com/developers/keys).
@@ -0,0 +1,13 @@
1
+ import type { DocumentActionComponent, SchemaType } from 'sanity';
2
+ import type { VocalStackPluginOptions, VocalStackTranscript } from './types.js';
3
+ type Found = {
4
+ path: string[];
5
+ siblings: Record<string, unknown> | undefined;
6
+ value: VocalStackTranscript | undefined;
7
+ audioField?: string;
8
+ };
9
+ /** Transcript fields in a document: top level and inside object fields (not arrays). */
10
+ export declare function transcriptFields(type: SchemaType | undefined, doc?: Record<string, unknown>, path?: string[], depth?: number): Found[];
11
+ /** "Transcribe audio": start a job for every transcript field next to an audio file. The field's input follows it. */
12
+ export declare const transcribeAction: (options: VocalStackPluginOptions) => DocumentActionComponent;
13
+ export {};
package/dist/action.js ADDED
@@ -0,0 +1,86 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { Box, Text } from '@sanity/ui';
3
+ import { useState } from 'react';
4
+ import { useDocumentOperation, useSchema } from 'sanity';
5
+ import { findAudio, jobName, siblingFileRefs, TRANSCRIPT_TYPE } from './core.js';
6
+ import { useHandler } from './handler.js';
7
+ import { Mark } from './components/Brand.js';
8
+ const isTranscript = (type) => {
9
+ for (let t = type; t; t = t.type)
10
+ if (t.name === TRANSCRIPT_TYPE)
11
+ return true;
12
+ return false;
13
+ };
14
+ /** Transcript fields in a document: top level and inside object fields (not arrays). */
15
+ export function transcriptFields(type, doc, path = [], depth = 0) {
16
+ if (!type || type.jsonType !== 'object' || depth > 4)
17
+ return [];
18
+ return type.fields.flatMap((field) => {
19
+ const value = doc?.[field.name];
20
+ if (isTranscript(field.type)) {
21
+ const audioField = field.type.options?.audioField;
22
+ return [{ audioField, path: [...path, field.name], siblings: doc, value: value }];
23
+ }
24
+ return field.type.jsonType === 'object' ? transcriptFields(field.type, value, [...path, field.name], depth + 1) : [];
25
+ });
26
+ }
27
+ /** "Transcribe audio": start a job for every transcript field next to an audio file. The field's input follows it. */
28
+ export const transcribeAction = (options) => {
29
+ const TranscribeAudioAction = (props) => {
30
+ const schema = useSchema();
31
+ const { call, client } = useHandler(options);
32
+ const { patch } = useDocumentOperation(props.id, props.type);
33
+ const [running, setRunning] = useState(false);
34
+ // What happened, in a popover under the action (Sanity UI moved its toasts between versions).
35
+ const [message, setMessage] = useState();
36
+ const doc = (props.draft ?? props.published);
37
+ const targets = transcriptFields(schema.get(props.type), doc ?? undefined).filter((t) => siblingFileRefs(t.siblings, t.audioField).length);
38
+ const idle = targets.filter((t) => t.value?.status !== 'processing');
39
+ return {
40
+ disabled: running || !doc || !idle.length || Boolean(patch.disabled),
41
+ icon: () => _jsx(Mark, { height: 16 }),
42
+ label: running ? 'Transcribing…' : 'Transcribe audio',
43
+ dialog: message
44
+ ? {
45
+ type: 'popover',
46
+ content: (_jsx(Box, { padding: 3, style: { maxWidth: 320 }, children: _jsx(Text, { size: 1, children: message }) })),
47
+ onClose: () => {
48
+ setMessage(undefined);
49
+ props.onComplete();
50
+ },
51
+ }
52
+ : undefined,
53
+ title: !targets.length ? 'Add an audio file first.' : !idle.length ? 'Already transcribing.' : undefined,
54
+ onHandle: async () => {
55
+ if (!doc)
56
+ return;
57
+ setRunning(true);
58
+ let started = 0;
59
+ try {
60
+ for (const t of idle) {
61
+ const asset = await findAudio(client, siblingFileRefs(t.siblings, t.audioField));
62
+ if (!asset)
63
+ continue;
64
+ const at = t.path.join('.');
65
+ const body = { assetId: asset._id, documentId: doc._id, fieldPath: at, name: jobName(doc, asset) };
66
+ const fields = await call('/transcriptions', { body, method: 'POST' });
67
+ patch.execute([
68
+ { setIfMissing: { [at]: { _type: TRANSCRIPT_TYPE } } },
69
+ { set: { [`${at}.status`]: fields.status, [`${at}.recordingId`]: fields.recordingId, [`${at}.transcriptionId`]: fields.transcriptionId } },
70
+ { unset: [`${at}.error`] },
71
+ ]);
72
+ started++;
73
+ }
74
+ setMessage(started ? 'Transcribing. The transcript appears in the field when it is ready.' : 'Only audio files can be transcribed.');
75
+ }
76
+ catch (err) {
77
+ setMessage(err.message);
78
+ }
79
+ finally {
80
+ setRunning(false);
81
+ }
82
+ },
83
+ };
84
+ };
85
+ return TranscribeAudioAction;
86
+ };
package/dist/api.d.ts ADDED
@@ -0,0 +1,78 @@
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
4
+ */
5
+ export declare const DEFAULT_API_URL = "https://api.vocalstack.com";
6
+ export declare const DEFAULT_DASHBOARD_URL = "https://app.vocalstack.com";
7
+ export type JobState = 'cropping' | 'done' | 'failed' | 'fetching' | 'queued' | 'stopped' | 'transcribing';
8
+ export type Job = {
9
+ error?: null | string;
10
+ /** Why a failed job failed; `stopped` when its owner stopped it. */
11
+ errorCode?: null | string;
12
+ progress: {
13
+ pct: number;
14
+ phase?: null | string;
15
+ phasePct?: null | number;
16
+ processedS?: number;
17
+ totalS?: null | number;
18
+ };
19
+ recordingId: string;
20
+ state: JobState;
21
+ transcriptionId: string;
22
+ };
23
+ export type Transcription = {
24
+ id: string;
25
+ job?: Job | null;
26
+ name: string;
27
+ };
28
+ export type Transcript = {
29
+ lang?: null | string;
30
+ segments: {
31
+ end: number;
32
+ seq: number;
33
+ start: number;
34
+ suppressed?: boolean;
35
+ words?: {
36
+ end: number;
37
+ start: number;
38
+ text: string;
39
+ }[] | null;
40
+ }[];
41
+ sentences: {
42
+ end: number;
43
+ language?: null | string;
44
+ sentenceId: number;
45
+ speaker: number;
46
+ start: number;
47
+ suppressed?: boolean;
48
+ text: string;
49
+ }[];
50
+ };
51
+ export declare class VocalStackAPIError extends Error {
52
+ code: string;
53
+ status: number;
54
+ constructor(status: number, code: string, message: string);
55
+ }
56
+ export declare class VocalStackAPI {
57
+ private apiKey;
58
+ private baseURL;
59
+ constructor(apiKey: string, baseURL?: string);
60
+ private request;
61
+ me(): Promise<Record<string, unknown>>;
62
+ transcribeURL(url: string, opts: {
63
+ idempotencyKey: string;
64
+ name: string;
65
+ spokenLanguage?: string;
66
+ }): Promise<Transcription>;
67
+ transcribeFile(file: Blob, fileName: string, opts: {
68
+ idempotencyKey: string;
69
+ name: string;
70
+ spokenLanguage?: string;
71
+ }): Promise<Transcription>;
72
+ job(recordingId: string): Promise<Job>;
73
+ /** Stop a job before it is done. Its job fails with `stopped`; what was transcribed so far stays in VocalStack. */
74
+ stop(recordingId: string, reason?: string): Promise<unknown>;
75
+ transcript(recordingId: string): Promise<Transcript>;
76
+ }
77
+ /** A short label for the connected account, from whatever `/v1/me` carries. */
78
+ export declare function accountLabel(me: Record<string, unknown>): string | undefined;
package/dist/api.js ADDED
@@ -0,0 +1,74 @@
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
4
+ */
5
+ export const DEFAULT_API_URL = 'https://api.vocalstack.com';
6
+ export const DEFAULT_DASHBOARD_URL = 'https://app.vocalstack.com';
7
+ export class VocalStackAPIError extends Error {
8
+ code;
9
+ status;
10
+ constructor(status, code, message) {
11
+ super(message);
12
+ this.code = code;
13
+ this.status = status;
14
+ }
15
+ }
16
+ export class VocalStackAPI {
17
+ apiKey;
18
+ baseURL;
19
+ constructor(apiKey, baseURL = DEFAULT_API_URL) {
20
+ this.apiKey = apiKey;
21
+ this.baseURL = baseURL;
22
+ }
23
+ async request(method, path, body, headers = {}) {
24
+ const init = { headers: { accept: 'application/json', authorization: `Bearer ${this.apiKey}`, ...headers }, method };
25
+ if (body instanceof FormData)
26
+ init.body = body;
27
+ else if (body !== undefined) {
28
+ init.body = JSON.stringify(body);
29
+ init.headers['content-type'] = 'application/json';
30
+ }
31
+ const res = await fetch(`${this.baseURL}${path}`, init);
32
+ const data = await res.json().catch(() => undefined);
33
+ if (!res.ok) {
34
+ const err = (data?.error ?? data);
35
+ throw new VocalStackAPIError(res.status, err?.code ?? 'http_error', err?.message ?? `VocalStack answered ${res.status}`);
36
+ }
37
+ return data;
38
+ }
39
+ me() {
40
+ return this.request('GET', '/v1/me');
41
+ }
42
+ transcribeURL(url, opts) {
43
+ return this.request('POST', '/v1/transcriptions', { name: opts.name, settings: opts.spokenLanguage ? { spokenLanguage: opts.spokenLanguage } : undefined, url }, { 'idempotency-key': opts.idempotencyKey });
44
+ }
45
+ transcribeFile(file, fileName, opts) {
46
+ const form = new FormData();
47
+ form.append('options', JSON.stringify({ name: opts.name, settings: opts.spokenLanguage ? { spokenLanguage: opts.spokenLanguage } : undefined }));
48
+ form.append('file', file, fileName);
49
+ return this.request('POST', '/v1/transcriptions', form, { 'idempotency-key': opts.idempotencyKey });
50
+ }
51
+ job(recordingId) {
52
+ return this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/job`);
53
+ }
54
+ /** Stop a job before it is done. Its job fails with `stopped`; what was transcribed so far stays in VocalStack. */
55
+ stop(recordingId, reason) {
56
+ return this.request('POST', `/v1/recordings/${encodeURIComponent(recordingId)}/stop`, { reason: reason ?? null });
57
+ }
58
+ transcript(recordingId) {
59
+ return this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/transcript`);
60
+ }
61
+ }
62
+ /** A short label for the connected account, from whatever `/v1/me` carries. */
63
+ export function accountLabel(me) {
64
+ const pick = (o, ...keys) => {
65
+ if (!o || typeof o !== 'object')
66
+ return undefined;
67
+ for (const k of keys) {
68
+ const v = o[k];
69
+ if (typeof v === 'string' && v)
70
+ return v;
71
+ }
72
+ };
73
+ return pick(me.principal, 'name', 'displayName') ?? pick(me.organization, 'name') ?? pick(me.user, 'email', 'name') ?? pick(me, 'email', 'name', 'displayName');
74
+ }
@@ -0,0 +1,12 @@
1
+ /** Whether the Studio is in its dark scheme. */
2
+ export declare function useDark(): boolean;
3
+ /** The accent for progress bars, following the Studio's scheme. */
4
+ export declare const useAccent: () => "#245B8F" | "#55ABE5";
5
+ /** The VocalStack wordmark. */
6
+ export declare const Logo: React.FC<{
7
+ height?: number;
8
+ }>;
9
+ /** The V on its own, for small spaces (the tool's icon). */
10
+ export declare const Mark: React.FC<{
11
+ height?: number;
12
+ }>;
@@ -0,0 +1,21 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useRootTheme } from '@sanity/ui';
3
+ import { BRAND, LOGO_DARK, LOGO_LIGHT, MARK_DARK, MARK_LIGHT } from './brandAssets.js';
4
+ /** Whether the Studio is in its dark scheme. */
5
+ export function useDark() {
6
+ try {
7
+ return useRootTheme().scheme === 'dark';
8
+ }
9
+ catch {
10
+ return false;
11
+ }
12
+ }
13
+ /** The accent for progress bars, following the Studio's scheme. */
14
+ export const useAccent = () => (useDark() ? BRAND.lightBlue : BRAND.blue);
15
+ /** The artwork has no width or height of its own: size it by the wrapper's height. */
16
+ const sized = (svg) => svg.replace('<svg ', '<svg style="height:100%;width:auto" ');
17
+ const Art = ({ dark, height, label, light }) => (_jsx("span", { "aria-label": label, dangerouslySetInnerHTML: { __html: sized(useDark() ? dark : light) }, role: label ? 'img' : undefined, style: { display: 'inline-flex', height, lineHeight: 0, verticalAlign: 'middle' } }));
18
+ /** The VocalStack wordmark. */
19
+ export const Logo = ({ height = 16 }) => _jsx(Art, { dark: LOGO_DARK, height: height, label: "VocalStack", light: LOGO_LIGHT });
20
+ /** The V on its own, for small spaces (the tool's icon). */
21
+ export const Mark = ({ height = 18 }) => _jsx(Art, { dark: MARK_DARK, height: height, light: MARK_LIGHT });
@@ -0,0 +1,7 @@
1
+ import type { ObjectInputProps, Path } from 'sanity';
2
+ import type { VocalStackPluginOptions, VocalStackTranscript } from '../types.js';
3
+ /** `['body', { _key: 'a1' }, 'transcript']` → `body[_key=="a1"].transcript`, for the job's idempotency key. */
4
+ export declare const pathString: (path: Path) => string;
5
+ export declare function TranscriptInput(props: ObjectInputProps<VocalStackTranscript> & {
6
+ pluginOptions: VocalStackPluginOptions;
7
+ }): import("react").JSX.Element;
@@ -0,0 +1,173 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Box, Button, Card, Flex, Stack, Text, TextArea } from '@sanity/ui';
3
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
4
+ import { set, setIfMissing, unset, useFormValue } from 'sanity';
5
+ import { findAudio, jobName, POLL_MS, restored, siblingFileRefs, TRANSCRIPT_TYPE } from '../core.js';
6
+ import { HandlerError, useConnection, useHandler } from '../handler.js';
7
+ import { transcriptText } from '../text.js';
8
+ import { Logo, useAccent } from './Brand.js';
9
+ /** 2433.0 → "40:33", 4000 → "1:06:40". */
10
+ const clock = (s) => {
11
+ const t = Math.floor(s);
12
+ const [h, m, sec] = [Math.floor(t / 3600), Math.floor((t % 3600) / 60), t % 60];
13
+ return `${h ? `${h}:${String(m).padStart(2, '0')}` : m}:${String(sec).padStart(2, '0')}`;
14
+ };
15
+ const PHASES = {
16
+ extracting: 'Extracting audio',
17
+ fetching: 'Fetching the file',
18
+ queued: 'Queued',
19
+ transcribing: 'Transcribing',
20
+ };
21
+ /** `['body', { _key: 'a1' }, 'transcript']` → `body[_key=="a1"].transcript`, for the job's idempotency key. */
22
+ export const pathString = (path) => path
23
+ .map((p, i) => (typeof p === 'string' ? (i ? `.${p}` : p) : typeof p === 'number' ? `[${p}]` : Array.isArray(p) ? `[${p.join(':')}]` : `[_key=="${p._key}"]`))
24
+ .join('');
25
+ export function TranscriptInput(props) {
26
+ const { onChange, path, pluginOptions: options, readOnly, schemaType, value } = props;
27
+ const accent = useAccent();
28
+ const { call, client } = useHandler(options);
29
+ const connection = useConnection(call);
30
+ const document = useFormValue([]);
31
+ // The object holding this field: the document itself, or an object field inside it.
32
+ const parent = useFormValue(path.slice(0, -1));
33
+ const audioField = schemaType.options?.audioField;
34
+ const refs = siblingFileRefs(parent, audioField);
35
+ const refsKey = refs.join(',');
36
+ const [asset, setAsset] = useState();
37
+ useEffect(() => {
38
+ let live = true;
39
+ setAsset(undefined);
40
+ findAudio(client, refsKey ? refsKey.split(',') : []).then((a) => live && setAsset(a ?? null), () => live && setAsset(null));
41
+ return () => {
42
+ live = false;
43
+ };
44
+ }, [client, refsKey]);
45
+ const [starting, setStarting] = useState(false);
46
+ const [stopping, setStopping] = useState(false);
47
+ const [progress, setProgress] = useState({});
48
+ const [error, setError] = useState();
49
+ // A short note after a job ends. Inline rather than a toast: Sanity UI moved its toasts between versions.
50
+ const [notice, setNotice] = useState();
51
+ useEffect(() => {
52
+ if (!notice)
53
+ return;
54
+ const t = setTimeout(() => setNotice(undefined), 5000);
55
+ return () => clearTimeout(t);
56
+ }, [notice]);
57
+ const valueRef = useRef(value);
58
+ valueRef.current = value;
59
+ /** Write fields of the transcript object (null removes one). */
60
+ const apply = useCallback((fields) => {
61
+ if (readOnly)
62
+ return;
63
+ onChange([
64
+ setIfMissing({ _type: TRANSCRIPT_TYPE }),
65
+ ...Object.entries(fields).map(([k, v]) => (v === null || v === undefined ? unset([k]) : set(v, [k]))),
66
+ ]);
67
+ }, [onChange, readOnly]);
68
+ const finish = useCallback((outcome) => {
69
+ apply(outcome.kind === 'stopped' ? restored(valueRef.current) : outcome.save);
70
+ setProgress({});
71
+ if (outcome.kind === 'stopped')
72
+ setNotice('Transcription stopped.');
73
+ else if (outcome.kind === 'done')
74
+ setNotice('Transcript ready.');
75
+ }, [apply]);
76
+ // Follow a running job, also one started before a reload or from the document action:
77
+ // recordingId and status are saved on the document.
78
+ const status = value?.status ?? 'idle';
79
+ const recordingId = value?.recordingId;
80
+ useEffect(() => {
81
+ if (status !== 'processing' || !recordingId)
82
+ return;
83
+ let cancelled = false;
84
+ let timer;
85
+ const tick = async () => {
86
+ try {
87
+ const outcome = await call(`/recordings/${encodeURIComponent(recordingId)}/job`);
88
+ if (cancelled)
89
+ return;
90
+ setError(undefined);
91
+ if (outcome.kind === 'processing') {
92
+ setProgress(outcome);
93
+ timer = setTimeout(tick, POLL_MS);
94
+ }
95
+ else
96
+ finish(outcome);
97
+ }
98
+ catch (err) {
99
+ if (cancelled)
100
+ return;
101
+ // A network blip or a server hiccup should not end the wait; anything refused should.
102
+ if (err instanceof HandlerError && err.status && err.status < 500)
103
+ return setError(err.message);
104
+ if (err instanceof HandlerError && err.status)
105
+ setError(err.message);
106
+ timer = setTimeout(tick, POLL_MS * 2);
107
+ }
108
+ };
109
+ void tick();
110
+ return () => {
111
+ cancelled = true;
112
+ clearTimeout(timer);
113
+ };
114
+ }, [call, finish, recordingId, status]);
115
+ const transcribe = async () => {
116
+ if (!asset)
117
+ return;
118
+ setError(undefined);
119
+ setNotice(undefined);
120
+ setStarting(true);
121
+ setProgress({});
122
+ try {
123
+ const body = { assetId: asset._id, documentId: document._id, fieldPath: pathString(path), name: jobName(document, asset) };
124
+ apply({ ...(await call('/transcriptions', { body, method: 'POST' })), error: null });
125
+ }
126
+ catch (err) {
127
+ setError(err.message);
128
+ }
129
+ finally {
130
+ setStarting(false);
131
+ }
132
+ };
133
+ /** Stop the job. The field goes back to how it was; VocalStack keeps what it heard so far. */
134
+ const stop = async () => {
135
+ if (!recordingId)
136
+ return;
137
+ if (!window.confirm('Stop transcribing? What VocalStack has transcribed so far stays in your VocalStack dashboard.'))
138
+ return;
139
+ setStopping(true);
140
+ try {
141
+ const outcome = await call(`/recordings/${encodeURIComponent(recordingId)}/stop`, { method: 'POST' });
142
+ if (outcome.kind !== 'processing')
143
+ finish(outcome);
144
+ }
145
+ catch (err) {
146
+ setError(err.message);
147
+ }
148
+ finally {
149
+ setStopping(false);
150
+ }
151
+ };
152
+ const busy = status === 'processing';
153
+ const shownError = error ?? (status === 'failed' ? (value?.error ?? undefined) : undefined);
154
+ const partialText = useMemo(() => (busy && progress.partial?.length ? transcriptText(progress.partial) : undefined), [busy, progress.partial]);
155
+ const muted = { muted: true, size: 1 };
156
+ let action;
157
+ if (!connection)
158
+ action = _jsx(Text, { ...muted, children: "Checking the VocalStack connection\u2026" });
159
+ else if (!connection.connected) {
160
+ action = (_jsx(Card, { padding: 2, radius: 2, tone: "caution", children: _jsx(Text, { size: 1, children: connection.error ?? 'VocalStack is not connected.' }) }));
161
+ }
162
+ else if (asset === undefined && refs.length)
163
+ action = _jsx(Text, { ...muted, children: "Looking for the audio file\u2026" });
164
+ else if (!asset && !busy)
165
+ action = _jsx(Text, { ...muted, children: refs.length ? 'Only audio files can be transcribed.' : 'Add an audio file, then transcribe.' });
166
+ else {
167
+ action = (_jsxs(Flex, { gap: 2, wrap: "wrap", children: [_jsx(Button, { disabled: busy || starting || readOnly || !asset, onClick: transcribe, text: busy || starting ? 'Transcribing…' : status === 'done' ? 'Transcribe again' : 'Transcribe', tone: "primary" }), busy && _jsx(Button, { disabled: stopping || readOnly, mode: "ghost", onClick: stop, text: stopping ? 'Stopping…' : 'Stop' })] }));
168
+ }
169
+ return (_jsx(Card, { border: true, padding: 3, radius: 2, children: _jsxs(Stack, { space: 3, children: [_jsx(Logo, { height: 14 }), 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) => {
170
+ const text = e.currentTarget.value;
171
+ onChange([setIfMissing({ _type: TRANSCRIPT_TYPE }), text ? set(text, ['transcript']) : unset(['transcript'])]);
172
+ }, readOnly: readOnly || Boolean(partialText), rows: 10, value: partialText ?? value?.transcript ?? '' }) }))] }) }));
173
+ }