@vocalstack/sanity 0.0.0-stage → 0.2.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/schema.js ADDED
@@ -0,0 +1,51 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { defineField, defineType } from 'sanity';
3
+ import { TranscriptInput } from './components/TranscriptInput.js';
4
+ import { TRANSCRIPT_TYPE } from './core.js';
5
+ /**
6
+ * `vocalstack.transcript`: an object field to put next to a `file` field. Its input
7
+ * renders the Transcribe button, the progress and the editable transcript; the rest
8
+ * is written by the plugin and readable with GROQ like any field.
9
+ */
10
+ export const transcriptType = (options) => defineType({
11
+ name: TRANSCRIPT_TYPE,
12
+ title: 'Transcript',
13
+ type: 'object',
14
+ fields: [
15
+ defineField({ name: 'transcript', title: 'Transcript', type: 'text', description: 'Paragraphs break on a speaker change or a pause.' }),
16
+ defineField({
17
+ name: 'sentences',
18
+ title: 'Sentences',
19
+ description: 'Timed sentences, in seconds, for captions or a synced player.',
20
+ type: 'array',
21
+ readOnly: true,
22
+ of: [
23
+ {
24
+ name: 'sentence',
25
+ type: 'object',
26
+ fields: [
27
+ defineField({ name: 'start', type: 'number' }),
28
+ defineField({ name: 'end', type: 'number' }),
29
+ defineField({ name: 'speaker', type: 'number' }),
30
+ defineField({ name: 'text', type: 'string' }),
31
+ ],
32
+ },
33
+ ],
34
+ }),
35
+ defineField({
36
+ name: 'status',
37
+ type: 'string',
38
+ initialValue: 'idle',
39
+ readOnly: true,
40
+ options: { list: ['idle', 'processing', 'done', 'failed'] },
41
+ }),
42
+ defineField({ name: 'language', type: 'string', readOnly: true }),
43
+ defineField({ name: 'error', type: 'string', readOnly: true }),
44
+ defineField({ name: 'recordingId', title: 'Recording ID', type: 'string', readOnly: true }),
45
+ defineField({ name: 'transcriptionId', title: 'Transcription ID', type: 'string', readOnly: true }),
46
+ defineField({ name: 'transcribedAt', type: 'datetime', readOnly: true }),
47
+ ],
48
+ components: {
49
+ input: (props) => _jsx(TranscriptInput, { ...props, pluginOptions: options }),
50
+ },
51
+ });
@@ -0,0 +1,46 @@
1
+ export type { ConnectionResponse, ConnectionWorkspace, JobOutcome, StartRequest, StartResponse } from '../wire.js';
2
+ export type VocalStackHandlerOptions = {
3
+ /** A VocalStack API key (`vs_key_…`, Read + Write). Default: `process.env.VOCALSTACK_API_KEY`. */
4
+ apiKey?: string;
5
+ /**
6
+ * The dataset the Studio edits, and a token that can read it (a Viewer token is enough).
7
+ * `apiHost` and `useProjectHostname` work as in `@sanity/client`: requests go to
8
+ * `https://<projectId>.api.sanity.io` unless you use a custom API domain.
9
+ */
10
+ sanity: {
11
+ apiHost?: string;
12
+ apiVersion?: string;
13
+ dataset: string;
14
+ projectId: string;
15
+ token: string;
16
+ useProjectHostname?: boolean;
17
+ };
18
+ /** A Whisper language code (`en`, `ro`, …). Leave out to auto-detect. */
19
+ spokenLanguage?: string;
20
+ /**
21
+ * The URL of the audio. Default: the asset's URL on Sanity's CDN. Return a signed URL
22
+ * here if your assets are private. VocalStack fetches a public URL itself; for one it
23
+ * cannot reach (localhost, a private network) the handler reads the file and uploads it.
24
+ */
25
+ fileURL?: (asset: SanityFileAsset) => Promise<string | undefined> | string | undefined;
26
+ /**
27
+ * Origins allowed to call the handler (the Studio's), e.g. `['https://my.sanity.studio']`.
28
+ * Default: any. Callers prove themselves with a Studio session, not a cookie, so any origin is safe.
29
+ */
30
+ allowedOrigins?: string[];
31
+ /** Default https://api.vocalstack.com */
32
+ apiURL?: string;
33
+ };
34
+ export type SanityFileAsset = {
35
+ _id: string;
36
+ mimeType?: string;
37
+ originalFilename?: string;
38
+ url?: string;
39
+ };
40
+ type Handler = (request: Request) => Promise<Response>;
41
+ /**
42
+ * The connection answer, briefly: a rename or a new icon in the Dashboard, and the
43
+ * icon's re-signed link, reach the Studio within minutes, without a redeploy.
44
+ */
45
+ export declare const CONNECTION_CACHE_MS: number;
46
+ export declare function createVocalStackHandler(options: VocalStackHandlerOptions): Handler;
@@ -0,0 +1,170 @@
1
+ import { accountLabel, DEFAULT_API_URL, VocalStackAPI, VocalStackAPIError, workspaceOf } from '../api.js';
2
+ import { NOT_IN_WORKSPACE, SESSION_MAX_AGE_MS, SESSION_PREFIX, SESSION_TYPE, sha256Hex } from '../wire.js';
3
+ import { checkJob, stopJob } from './jobs.js';
4
+ /** `https://<projectId>.api.sanity.io`, or the custom API host, as `@sanity/client` builds it. */
5
+ function sanityHost({ apiHost = 'https://api.sanity.io', projectId, useProjectHostname = true }) {
6
+ const host = new URL(apiHost);
7
+ if (useProjectHostname)
8
+ host.hostname = `${projectId}.${host.hostname}`;
9
+ return host.origin;
10
+ }
11
+ /**
12
+ * Whether VocalStack can fetch this address itself. The API refuses loopback,
13
+ * private and link-local hosts, so for those the handler sends the bytes instead.
14
+ */
15
+ function isPublicURL(url) {
16
+ const { hostname, protocol } = new URL(url);
17
+ if (protocol !== 'https:' && protocol !== 'http:')
18
+ return false;
19
+ const host = hostname.replace(/^\[|\]$/g, '').toLowerCase();
20
+ if (host === 'localhost' || host.endsWith('.localhost') || host.endsWith('.local') || host.endsWith('.internal'))
21
+ return false;
22
+ const v4 = host.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
23
+ if (v4) {
24
+ const [a, b] = [Number(v4[1]), Number(v4[2])];
25
+ return !(a === 10 || a === 127 || a === 0 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127));
26
+ }
27
+ if (host.includes(':'))
28
+ return !(host === '::1' || host.startsWith('fc') || host.startsWith('fd') || host.startsWith('fe80'));
29
+ return true;
30
+ }
31
+ async function fetchFile(url) {
32
+ const res = await fetch(url);
33
+ if (!res.ok)
34
+ throw new Error(`Could not read the audio file (${res.status} from ${url}).`);
35
+ return res.blob();
36
+ }
37
+ /** Verified sessions, briefly, so a poll every 3 s is not a Sanity query every 3 s. */
38
+ const SESSION_CACHE_MS = 60_000;
39
+ /**
40
+ * The connection answer, briefly: a rename or a new icon in the Dashboard, and the
41
+ * icon's re-signed link, reach the Studio within minutes, without a redeploy.
42
+ */
43
+ export const CONNECTION_CACHE_MS = 5 * 60_000;
44
+ export function createVocalStackHandler(options) {
45
+ const apiKey = options.apiKey ?? globalThis.process?.env?.VOCALSTACK_API_KEY;
46
+ const { dataset, projectId, token } = options.sanity;
47
+ const sanityBase = `${sanityHost(options.sanity)}/v${(options.sanity.apiVersion ?? '2024-01-01').replace(/^v/, '')}`;
48
+ const sessions = new Map();
49
+ let connection;
50
+ async function query(groq, params) {
51
+ const url = new URL(`${sanityBase}/data/query/${encodeURIComponent(dataset)}`);
52
+ url.searchParams.set('query', groq);
53
+ for (const [k, v] of Object.entries(params))
54
+ url.searchParams.set(`$${k}`, JSON.stringify(v));
55
+ const res = await fetch(url, { headers: { authorization: `Bearer ${token}` } });
56
+ if (!res.ok)
57
+ throw new Error(`Sanity answered ${res.status} to the handler's query. Check its projectId, dataset and token.`);
58
+ return (await res.json()).result;
59
+ }
60
+ /**
61
+ * Is the caller signed in to the Studio? The Studio creates a session document whose id
62
+ * is the hash of a random secret and sends the secret. Only someone who may write to the
63
+ * dataset can create one; readers see the hash, never the secret.
64
+ */
65
+ async function signedIn(request) {
66
+ const secret = request.headers.get('authorization')?.match(/^Bearer\s+(\S{32,})$/)?.[1];
67
+ if (!secret)
68
+ return false;
69
+ const id = SESSION_PREFIX + (await sha256Hex(secret));
70
+ const cached = sessions.get(id);
71
+ if (cached && cached > Date.now())
72
+ return true;
73
+ const updatedAt = await query('*[_id == $id && _type == $type][0]._updatedAt', { id, type: SESSION_TYPE });
74
+ const expires = updatedAt ? Date.parse(updatedAt) + SESSION_MAX_AGE_MS : 0;
75
+ if (expires <= Date.now())
76
+ return false;
77
+ sessions.set(id, Math.min(expires, Date.now() + SESSION_CACHE_MS));
78
+ return true;
79
+ }
80
+ const cors = (request) => {
81
+ const origin = request.headers.get('origin');
82
+ const allowed = !options.allowedOrigins || (origin !== null && options.allowedOrigins.includes(origin));
83
+ return allowed
84
+ ? {
85
+ 'access-control-allow-headers': 'authorization, content-type',
86
+ 'access-control-allow-methods': 'GET, POST, OPTIONS',
87
+ 'access-control-allow-origin': options.allowedOrigins ? (origin ?? '') : '*',
88
+ 'access-control-max-age': '86400',
89
+ vary: 'origin',
90
+ }
91
+ : {};
92
+ };
93
+ return async (request) => {
94
+ const headers = { ...cors(request), 'cache-control': 'no-store' };
95
+ const json = (body, status = 200) => new Response(JSON.stringify(body), { headers: { ...headers, 'content-type': 'application/json' }, status });
96
+ const fail = (status, error, code) => json({ code, error }, status);
97
+ if (request.method === 'OPTIONS')
98
+ return new Response(null, { headers, status: 204 });
99
+ // The route's tail, wherever the handler is mounted: …/connection, …/transcriptions,
100
+ // …/recordings/:id/job, …/recordings/:id/stop.
101
+ const path = new URL(request.url).pathname.replace(/\/+$/, '');
102
+ const route = path.match(/\/(connection|transcriptions)$/)?.[1] ?? path.match(/\/recordings\/([^/]+)\/(job|stop)$/)?.slice(1).join(' ');
103
+ if (!route)
104
+ return fail(404, 'Not a VocalStack route.');
105
+ try {
106
+ if (!(await signedIn(request)))
107
+ return fail(401, 'Sign in to the Studio again.', 'session');
108
+ }
109
+ catch (err) {
110
+ return fail(502, err.message, 'sanity');
111
+ }
112
+ if (!apiKey)
113
+ return fail(503, 'VOCALSTACK_API_KEY is not set where the VocalStack handler runs.', 'not_connected');
114
+ const apiURL = options.apiURL ?? DEFAULT_API_URL;
115
+ const api = new VocalStackAPI(apiKey, apiURL);
116
+ const recordingRoute = route !== 'connection' && route !== 'transcriptions';
117
+ try {
118
+ if (route === 'connection' && request.method === 'GET') {
119
+ if (!connection || connection.until <= Date.now()) {
120
+ const me = await api.me();
121
+ const workspace = workspaceOf(me, apiURL);
122
+ connection = { answer: { account: workspace?.name ?? accountLabel(me), connected: true, workspace }, until: Date.now() + CONNECTION_CACHE_MS };
123
+ }
124
+ return json(connection.answer);
125
+ }
126
+ if (route === 'transcriptions' && request.method === 'POST') {
127
+ const body = (await request.json().catch(() => ({})));
128
+ if (typeof body.assetId !== 'string' || !body.assetId.startsWith('file-') || typeof body.documentId !== 'string')
129
+ return fail(400, 'Send assetId and documentId.');
130
+ const asset = await query('*[_id == $id][0]{ _id, url, mimeType, originalFilename }', { id: body.assetId });
131
+ if (!asset)
132
+ return fail(404, 'There is no such file in the dataset.');
133
+ if (!asset.mimeType?.startsWith('audio/'))
134
+ return fail(400, 'Only audio files can be transcribed.');
135
+ const url = (await options.fileURL?.(asset)) ?? asset.url;
136
+ if (!url)
137
+ return fail(400, 'There is no audio file here.');
138
+ const job = {
139
+ idempotencyKey: `sanity:${body.documentId.replace(/^drafts\./, '')}:${body.fieldPath ?? ''}:${crypto.randomUUID()}`,
140
+ name: (typeof body.name === 'string' && body.name.trim()) || asset.originalFilename || 'Sanity audio',
141
+ spokenLanguage: options.spokenLanguage,
142
+ };
143
+ // VocalStack refuses links to loopback and private addresses: send those files' bytes.
144
+ const tx = isPublicURL(url) ? await api.transcribeURL(url, job) : await api.transcribeFile(await fetchFile(url), asset.originalFilename || 'audio', job);
145
+ if (!tx.job)
146
+ return fail(502, 'VocalStack did not start a job for this file.');
147
+ return json({ recordingId: tx.job.recordingId, status: 'processing', transcriptionId: tx.id }, 202);
148
+ }
149
+ const [recordingId, action] = route.split(' ');
150
+ if (action === 'job' && request.method === 'GET')
151
+ return json(await checkJob(api, decodeURIComponent(recordingId)));
152
+ if (action === 'stop' && request.method === 'POST')
153
+ return json(await stopJob(api, decodeURIComponent(recordingId)));
154
+ return fail(405, 'Method not allowed.');
155
+ }
156
+ catch (err) {
157
+ if (err instanceof VocalStackAPIError) {
158
+ if (err.status === 401)
159
+ return fail(502, 'VocalStack refused the API key in VOCALSTACK_API_KEY.', 'not_connected');
160
+ // A key sees only its own workspace: after VOCALSTACK_API_KEY moved to another one, a
161
+ // recording made with the old key is not found (as is one deleted in VocalStack).
162
+ if (err.status === 404 && recordingRoute) {
163
+ return fail(404, 'This transcription is not in the workspace VocalStack is connected to now: it was made in another workspace, or deleted. Transcribe the audio again to make it here.', NOT_IN_WORKSPACE);
164
+ }
165
+ return fail(err.status >= 500 ? 502 : err.status, err.message, err.code);
166
+ }
167
+ return fail(500, err instanceof Error ? err.message : String(err));
168
+ }
169
+ };
170
+ }
@@ -0,0 +1,10 @@
1
+ import type { TranscriptSentence, SavedSentence } from '../types.js';
2
+ import type { JobOutcome } from '../wire.js';
3
+ import { type Transcript, type VocalStackAPI } from '../api.js';
4
+ /** A transcript's sentences: seconds, speaker, text. */
5
+ export declare function toSentences(t: Pick<Transcript, 'sentences'>): TranscriptSentence[];
6
+ /** As stored on the document: an array item needs a `_key`. */
7
+ export declare const toSaved: (sentences: TranscriptSentence[]) => SavedSentence[];
8
+ export declare function checkJob(api: VocalStackAPI, recordingId: string): Promise<JobOutcome>;
9
+ /** Stop a job. If it ended meanwhile, take its outcome instead. */
10
+ export declare function stopJob(api: VocalStackAPI, recordingId: string): Promise<JobOutcome>;
@@ -0,0 +1,53 @@
1
+ import { VocalStackAPIError } from '../api.js';
2
+ import { transcriptText } from '../text.js';
3
+ /** A transcript's sentences: seconds, speaker, text. */
4
+ export function toSentences(t) {
5
+ return t.sentences
6
+ .filter((s) => !s.suppressed && s.text.trim())
7
+ .map(({ end, sentenceId, speaker, start, text }) => ({ id: sentenceId, end, speaker, start, text: text.trim() }));
8
+ }
9
+ const round = (n) => Math.round(n * 1000) / 1000;
10
+ /** As stored on the document: an array item needs a `_key`. */
11
+ export const toSaved = (sentences) => sentences.map((s, i) => ({ _key: `s${s.id ?? i}`, _type: 'sentence', end: round(s.end), speaker: s.speaker, start: round(s.start), text: s.text }));
12
+ export async function checkJob(api, recordingId) {
13
+ const job = await api.job(recordingId);
14
+ if (job.state === 'stopped' || (job.state === 'failed' && job.errorCode === 'stopped'))
15
+ return { kind: 'stopped' };
16
+ if (job.state === 'failed' || job.state === 'cropping') {
17
+ const error = job.state === 'cropping' ? 'VocalStack is waiting for a crop window; open the transcription in VocalStack.' : (job.error ?? 'The transcription failed.');
18
+ return { kind: 'failed', message: error, save: { error, status: 'failed' } };
19
+ }
20
+ if (job.state !== 'done') {
21
+ const progress = job.state === 'fetching' ? (job.progress.phasePct ?? 0) : job.progress.pct;
22
+ if (job.state !== 'transcribing')
23
+ return { kind: 'processing', phase: job.progress.phase ?? job.state, progress };
24
+ // Sentences are readable while the job runs; send what is there so far.
25
+ const partial = await api.transcript(recordingId).then(toSentences, () => undefined);
26
+ return { audio: { processedS: job.progress.processedS ?? 0, totalS: job.progress.totalS ?? undefined }, kind: 'processing', partial, phase: 'transcribing', progress };
27
+ }
28
+ const transcript = await api.transcript(recordingId);
29
+ const sentences = toSentences(transcript);
30
+ return {
31
+ kind: 'done',
32
+ save: {
33
+ error: null,
34
+ language: transcript.lang ?? transcript.sentences.find((s) => s.language)?.language ?? null,
35
+ sentences: toSaved(sentences),
36
+ status: 'done',
37
+ transcribedAt: new Date().toISOString(),
38
+ transcript: transcriptText(sentences),
39
+ },
40
+ };
41
+ }
42
+ /** Stop a job. If it ended meanwhile, take its outcome instead. */
43
+ export async function stopJob(api, recordingId) {
44
+ try {
45
+ await api.stop(recordingId, 'Stopped from Sanity');
46
+ return { kind: 'stopped' };
47
+ }
48
+ catch (err) {
49
+ if (err instanceof VocalStackAPIError && err.status === 409)
50
+ return checkJob(api, recordingId).catch(() => ({ kind: 'stopped' }));
51
+ throw err;
52
+ }
53
+ }
package/dist/text.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import type { TranscriptSentence, TranscriptWord } from './types.js';
2
+ /** Whether a new paragraph starts at this sentence: a new speaker, or a long pause. */
3
+ export declare const breaksParagraph: (s: TranscriptSentence, prev: TranscriptSentence | undefined) => boolean;
4
+ /** Sentences grouped into paragraphs. */
5
+ export declare function paragraphs(sentences: TranscriptSentence[]): TranscriptSentence[][];
6
+ /** The plain text: sentences joined, a blank line between paragraphs. */
7
+ export declare function transcriptText(sentences: TranscriptSentence[]): string;
8
+ /**
9
+ * Give each sentence the words that fall inside it, as compact [start, end, text]
10
+ * tuples. Words come from segments, which do not line up with sentences.
11
+ */
12
+ export declare function attachWords<T extends TranscriptSentence>(sentences: T[], words: {
13
+ end: number;
14
+ start: number;
15
+ text: string;
16
+ }[]): T[];
17
+ /**
18
+ * The sentence's text as timed tokens. The text wins over the words (it carries
19
+ * VocalStack's later corrections); the words give the timing. When the counts
20
+ * differ, the times are spread evenly across the sentence.
21
+ */
22
+ export declare function timedTokens(s: TranscriptSentence): TranscriptWord[];
package/dist/text.js ADDED
@@ -0,0 +1,52 @@
1
+ /** Whether a new paragraph starts at this sentence: a new speaker, or a long pause. */
2
+ export const breaksParagraph = (s, prev) => !prev || s.speaker !== prev.speaker || s.start - prev.end > 2.5;
3
+ /** Sentences grouped into paragraphs. */
4
+ export function paragraphs(sentences) {
5
+ const out = [];
6
+ sentences.forEach((s, i) => {
7
+ if (breaksParagraph(s, sentences[i - 1]))
8
+ out.push([]);
9
+ out[out.length - 1].push(s);
10
+ });
11
+ return out;
12
+ }
13
+ /** The plain text: sentences joined, a blank line between paragraphs. */
14
+ export function transcriptText(sentences) {
15
+ return paragraphs(sentences)
16
+ .map((p) => p.map((s) => s.text.trim()).join(' '))
17
+ .join('\n\n');
18
+ }
19
+ /**
20
+ * Give each sentence the words that fall inside it, as compact [start, end, text]
21
+ * tuples. Words come from segments, which do not line up with sentences.
22
+ */
23
+ export function attachWords(sentences, words) {
24
+ const sorted = [...words].sort((a, b) => a.start - b.start);
25
+ let i = 0;
26
+ return sentences.map((s) => {
27
+ const own = [];
28
+ while (i < sorted.length && sorted[i].start < s.start - 0.05)
29
+ i++;
30
+ while (i < sorted.length && sorted[i].start < s.end + 0.05) {
31
+ const w = sorted[i++];
32
+ own.push([round(w.start), round(w.end), w.text.trim()]);
33
+ }
34
+ return own.length ? { ...s, words: own } : s;
35
+ });
36
+ }
37
+ const round = (n) => Math.round(n * 100) / 100;
38
+ /**
39
+ * The sentence's text as timed tokens. The text wins over the words (it carries
40
+ * VocalStack's later corrections); the words give the timing. When the counts
41
+ * differ, the times are spread evenly across the sentence.
42
+ */
43
+ export function timedTokens(s) {
44
+ const tokens = s.text.trim().split(/\s+/).filter(Boolean);
45
+ const words = s.words ?? [];
46
+ if (words.length === tokens.length)
47
+ return tokens.map((t, i) => [words[i][0], words[i][1], t]);
48
+ if (!tokens.length)
49
+ return words;
50
+ const span = (s.end - s.start) / tokens.length;
51
+ return tokens.map((t, i) => [round(s.start + i * span), round(s.start + (i + 1) * span), t]);
52
+ }
@@ -0,0 +1,55 @@
1
+ export type VocalStackPluginOptions = {
2
+ /**
3
+ * Where the server handler (`@vocalstack/sanity/server`) is mounted, e.g.
4
+ * `https://www.example.com/api/vocalstack`. The Studio calls only this URL;
5
+ * the VocalStack API key stays on that server.
6
+ */
7
+ handlerURL: string;
8
+ };
9
+ /** Options on a `vocalstack.transcript` field itself. */
10
+ export type TranscriptFieldOptions = {
11
+ /** The sibling `file` field holding the audio. Default: the first sibling file whose asset is `audio/*`. */
12
+ audioField?: string;
13
+ };
14
+ /** What the plugin reads from a `sanity.fileAsset`. */
15
+ export type AudioAsset = {
16
+ _id: string;
17
+ mimeType?: null | string;
18
+ originalFilename?: null | string;
19
+ url?: null | string;
20
+ };
21
+ export type TranscriptStatus = 'done' | 'failed' | 'idle' | 'processing';
22
+ /** A sentence as stored on the document: seconds, and the speaker's number. */
23
+ export type SavedSentence = {
24
+ _key: string;
25
+ _type?: string;
26
+ end: number;
27
+ speaker: number;
28
+ start: number;
29
+ text: string;
30
+ };
31
+ /** The `vocalstack.transcript` value. */
32
+ export type VocalStackTranscript = {
33
+ _type?: 'vocalstack.transcript';
34
+ error?: null | string;
35
+ language?: null | string;
36
+ recordingId?: null | string;
37
+ sentences?: null | SavedSentence[];
38
+ status?: null | TranscriptStatus;
39
+ transcript?: null | string;
40
+ transcriptionId?: null | string;
41
+ transcribedAt?: null | string;
42
+ };
43
+ /** [start, end, text], seconds. */
44
+ export type TranscriptWord = [number, number, string];
45
+ export type TranscriptSentence = {
46
+ /** Live only: words heard after the last settled sentence. */
47
+ draft?: boolean;
48
+ end: number;
49
+ /** VocalStack's sentenceId. */
50
+ id?: number;
51
+ speaker: number;
52
+ start: number;
53
+ text: string;
54
+ words?: TranscriptWord[];
55
+ };
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/wire.d.ts ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * What the Studio and the server handler say to each other. No imports: both
3
+ * the Studio bundle and the server use it.
4
+ */
5
+ import type { TranscriptSentence, VocalStackTranscript } from './types.js';
6
+ /** Where a job stands. `save` carries the fields to write on the document once it is over. */
7
+ export type JobOutcome = {
8
+ audio?: {
9
+ processedS: number;
10
+ totalS?: number;
11
+ };
12
+ kind: 'processing';
13
+ partial?: TranscriptSentence[];
14
+ phase: string;
15
+ progress: number;
16
+ } | {
17
+ kind: 'done' | 'failed';
18
+ message?: string;
19
+ save: VocalStackTranscript;
20
+ }
21
+ /** Stopped before it finished: the Studio puts the field back to how it was. */
22
+ | {
23
+ kind: 'stopped';
24
+ };
25
+ /** `POST {handlerURL}/transcriptions` */
26
+ export type StartRequest = {
27
+ /** The `sanity.fileAsset` id of the audio. The handler reads its URL and type itself. */
28
+ assetId: string;
29
+ documentId: string;
30
+ /** The transcript field's path in the document, for the job's idempotency key. */
31
+ fieldPath: string;
32
+ /** The transcription's name in VocalStack. Default: the file's name. */
33
+ name?: string;
34
+ };
35
+ export type StartResponse = Required<Pick<VocalStackTranscript, 'recordingId' | 'status' | 'transcriptionId'>>;
36
+ /** `GET {handlerURL}/connection` */
37
+ export type ConnectionResponse = {
38
+ /** The workspace's name; against an older VocalStack, the key's label. */
39
+ account?: string;
40
+ connected: boolean;
41
+ /** The workspace the handler's API key belongs to. Absent against a VocalStack that does not say. */
42
+ workspace?: ConnectionWorkspace;
43
+ };
44
+ /**
45
+ * A VocalStack workspace. `iconUrl` is its own icon as an absolute link that needs no
46
+ * key (re-signed from time to time, so not for keeping), or null when it has none.
47
+ */
48
+ export type ConnectionWorkspace = {
49
+ iconUrl: null | string;
50
+ id: string;
51
+ name: string;
52
+ personal: boolean;
53
+ };
54
+ /** The handler's `code` when a recording is not in the workspace its key belongs to. */
55
+ export declare const NOT_IN_WORKSPACE = "not_in_workspace";
56
+ /** Every error: `{ code?, error }`. `session` means the Studio should prove itself again. */
57
+ export type ErrorResponse = {
58
+ code?: string;
59
+ error: string;
60
+ };
61
+ /** The document type of a Studio session (see `SESSION_PREFIX`). */
62
+ export declare const SESSION_TYPE = "vocalstack.session";
63
+ /** Session ids are `vocalstack-session.<sha256 hex of the secret>`: dotted, so never public. */
64
+ export declare const SESSION_PREFIX = "vocalstack-session.";
65
+ /** How long a Studio session lasts, from the session document's `_updatedAt`. */
66
+ export declare const SESSION_MAX_AGE_MS: number;
67
+ export declare function sha256Hex(text: string): Promise<string>;
package/dist/wire.js ADDED
@@ -0,0 +1,12 @@
1
+ /** The handler's `code` when a recording is not in the workspace its key belongs to. */
2
+ export const NOT_IN_WORKSPACE = 'not_in_workspace';
3
+ /** The document type of a Studio session (see `SESSION_PREFIX`). */
4
+ export const SESSION_TYPE = 'vocalstack.session';
5
+ /** Session ids are `vocalstack-session.<sha256 hex of the secret>`: dotted, so never public. */
6
+ export const SESSION_PREFIX = 'vocalstack-session.';
7
+ /** How long a Studio session lasts, from the session document's `_updatedAt`. */
8
+ export const SESSION_MAX_AGE_MS = 12 * 60 * 60 * 1000;
9
+ export async function sha256Hex(text) {
10
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)));
11
+ return Array.from(digest, (b) => b.toString(16).padStart(2, '0')).join('');
12
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * A workspace's mark when it has no icon of its own, exactly as the VocalStack
3
+ * Dashboard draws it: its initials, on a tile tinted with its colour.
4
+ */
5
+ /** "Acme studio" → "AS", "Podcast" → "PO"; words with no letter or digit are skipped. */
6
+ export declare function workspaceInitials(name: string): string;
7
+ /** The hue of a workspace's colour, `oklch(.66 .13 <hue>)`: always the same for one id. */
8
+ export declare function workspaceHue(id: string): number;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * A workspace's mark when it has no icon of its own, exactly as the VocalStack
3
+ * Dashboard draws it: its initials, on a tile tinted with its colour.
4
+ */
5
+ /** "Acme studio" → "AS", "Podcast" → "PO"; words with no letter or digit are skipped. */
6
+ export function workspaceInitials(name) {
7
+ const words = name
8
+ .trim()
9
+ .split(/\s+/)
10
+ .filter((w) => /[\p{L}\p{N}]/u.test(w));
11
+ const first = (w) => Array.from(w.replace(/^[^\p{L}\p{N}]+/u, ''))[0] ?? '';
12
+ if (words.length === 0)
13
+ return '?';
14
+ if (words.length === 1)
15
+ return Array.from(words[0].replace(/[^\p{L}\p{N}]/gu, '')).slice(0, 2).join('').toUpperCase() || '?';
16
+ return (first(words[0]) + first(words[1])).toUpperCase();
17
+ }
18
+ const HUES = [252, 200, 160, 128, 85, 40, 12, 330, 296];
19
+ /** The hue of a workspace's colour, `oklch(.66 .13 <hue>)`: always the same for one id. */
20
+ export function workspaceHue(id) {
21
+ let h = 2166136261;
22
+ for (let i = 0; i < id.length; i++) {
23
+ h ^= id.charCodeAt(i);
24
+ h = Math.imul(h, 16777619);
25
+ }
26
+ return HUES[(h >>> 0) % HUES.length];
27
+ }
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@vocalstack/sanity",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "VocalStack for Sanity Studio: a Transcribe button next to every audio file.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./server": {
15
+ "types": "./dist/server/index.d.ts",
16
+ "default": "./dist/server/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "sideEffects": false,
23
+ "scripts": {
24
+ "build": "rm -rf dist && tsc -p tsconfig.json",
25
+ "typecheck": "tsc -p tsconfig.json --noEmit",
26
+ "test": "npm run build && node --test test/*.test.mjs"
27
+ },
28
+ "peerDependencies": {
29
+ "@sanity/ui": "^2.0.0 || ^3.0.0 || ^4.0.0",
30
+ "react": "^18 || ^19",
31
+ "sanity": "^3 || ^4 || ^5 || ^6"
32
+ },
33
+ "peerDependenciesMeta": {
34
+ "@sanity/ui": {
35
+ "optional": true
36
+ }
37
+ },
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",
49
+ "typescript": "^5.6.0"
50
+ },
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "git+ssh://git@github.com/vocalstack/sanity-plugin.git"
54
+ },
55
+ "engines": {
56
+ "node": ">=20"
57
+ }
58
+ }