@vocalstack/sanity 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,12 +2,12 @@
2
2
 
3
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
4
 
5
- ## Install
5
+ Read more about the [VocalStack transcription plugin for Sanity](https://vocalstack.com/sanity-transcription-plugin/) on the [VocalStack website](https://vocalstack.com/).
6
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):
7
+ ## Install
8
8
 
9
9
  ```sh
10
- npm i github:vocalstack/sanity-plugin
10
+ npm i @vocalstack/sanity
11
11
  ```
12
12
 
13
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.
@@ -65,13 +65,14 @@ defineType({
65
65
  ## What it adds
66
66
 
67
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.
68
+ - the **workspace** the Studio is connected to, with its icon, at the top of the field (see [Workspace](#workspace));
69
+ - a **Transcribe** button, shown when the sibling file is `audio/*`. It shows progress and survives a reload mid-job, because `transcriptionId` 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
70
  - the stored value:
70
71
  - `transcript`: text you can edit; paragraphs break on a speaker change or a pause.
71
72
  - `sentences`: `[{ start, end, speaker, text }]` in seconds.
72
- - `status` (`idle`, `processing`, `done` or `failed`), `language`, `error`, `recordingId`, `transcriptionId` and `transcribedAt`.
73
+ - `status` (`idle`, `processing`, `done` or `failed`), `language`, `error`, `transcriptionId` and `transcribedAt`. Documents saved by 0.2.x also carry a hidden `recordingId`, which is no longer read: a job left running under it is followed by its `transcriptionId`, and one with no `transcriptionId` offers Transcribe again.
73
74
  - **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
+ - **The handler** (`@vocalstack/sanity/server`): `GET …/connection` (`{ connected, account, workspace: { id, name, personal, iconUrl } }`), `POST …/transcriptions`, `GET …/transcriptions/:id/job` and `POST …/transcriptions/:id/stop`.
75
76
 
76
77
  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
 
@@ -104,7 +105,7 @@ The handler, `createVocalStackHandler({ … })`:
104
105
  | `allowedOrigins` | any | The Studio origins allowed to call the handler (CORS), e.g. `['https://example.sanity.studio']`. |
105
106
  | `apiURL` | `https://api.vocalstack.com` | |
106
107
 
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
+ **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
109
 
109
110
  ## How the handler knows the caller
110
111
 
@@ -115,11 +116,19 @@ The handler only answers someone signed in to the Studio with permission to edit
115
116
 
116
117
  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
 
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
+ 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 in that key's workspace.
120
+
121
+ ## Workspace
122
+
123
+ A VocalStack API key belongs to one workspace: every transcription the plugin makes lands in that workspace and is billed there. The transcript field shows which one, as the VocalStack Dashboard does: **Workspace**, its icon (its own picture, a person for the personal workspace, or its initials on its colour) and its name. The handler reads it from `GET /v1/me` and keeps it for five minutes, so a new name or icon shows up in the Studio without a redeploy.
124
+
125
+ There is no workspace switch in the Studio, because the key lives in the handler's environment. To use another workspace, set `VOCALSTACK_API_KEY` where the handler runs to a key made in that workspace: in the [Dashboard](https://app.vocalstack.com), switch to the workspace, then Developers → API keys. **Change**, next to the workspace's name, says the same.
126
+
127
+ After the key moves to another workspace, transcripts already saved on documents stay as they are. A job that was still running under the old key cannot be followed any more: its field says that the transcription is not in the connected workspace and offers **Transcribe again**, which makes a new one in the new workspace.
119
128
 
120
129
  ## Testing
121
130
 
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).
131
+ `pnpm test` builds `dist/` and runs the unit tests in `test/` (the workspace mark, the handler's `…/connection` answer). `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
132
 
124
133
  ## One-click connect
125
134
 
package/dist/action.js CHANGED
@@ -66,8 +66,8 @@ export const transcribeAction = (options) => {
66
66
  const fields = await call('/transcriptions', { body, method: 'POST' });
67
67
  patch.execute([
68
68
  { setIfMissing: { [at]: { _type: TRANSCRIPT_TYPE } } },
69
- { set: { [`${at}.status`]: fields.status, [`${at}.recordingId`]: fields.recordingId, [`${at}.transcriptionId`]: fields.transcriptionId } },
70
- { unset: [`${at}.error`] },
69
+ { set: { [`${at}.status`]: fields.status, [`${at}.transcriptionId`]: fields.transcriptionId } },
70
+ { unset: [`${at}.error`, `${at}.recordingId`] },
71
71
  ]);
72
72
  started++;
73
73
  }
package/dist/api.d.ts CHANGED
@@ -2,7 +2,12 @@
2
2
  * The handful of VocalStack API calls the plugin needs, on plain fetch (the
3
3
  * SDK is not on npm yet). Contract: https://api.vocalstack.com/v1/openapi.json
4
4
  */
5
+ import type { ConnectionWorkspace } from './wire.js';
5
6
  export declare const DEFAULT_API_URL = "https://api.vocalstack.com";
7
+ /** Sent as the User-Agent of every call to VocalStack (they run in the
8
+ * handler, on the server): VocalStack lists the transcriptions it makes
9
+ * as made in Sanity. Keep it to package.json's version. */
10
+ export declare const PLUGIN_VERSION = "0.3.0";
6
11
  export declare const DEFAULT_DASHBOARD_URL = "https://app.vocalstack.com";
7
12
  export type JobState = 'cropping' | 'done' | 'failed' | 'fetching' | 'queued' | 'stopped' | 'transcribing';
8
13
  export type Job = {
@@ -16,7 +21,6 @@ export type Job = {
16
21
  processedS?: number;
17
22
  totalS?: null | number;
18
23
  };
19
- recordingId: string;
20
24
  state: JobState;
21
25
  transcriptionId: string;
22
26
  };
@@ -69,10 +73,16 @@ export declare class VocalStackAPI {
69
73
  name: string;
70
74
  spokenLanguage?: string;
71
75
  }): Promise<Transcription>;
72
- job(recordingId: string): Promise<Job>;
76
+ job(transcriptionId: string): Promise<Job>;
73
77
  /** 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>;
78
+ stop(transcriptionId: string, reason?: string): Promise<unknown>;
79
+ transcript(transcriptionId: string): Promise<Transcript>;
76
80
  }
77
81
  /** A short label for the connected account, from whatever `/v1/me` carries. */
78
82
  export declare function accountLabel(me: Record<string, unknown>): string | undefined;
83
+ /**
84
+ * The workspace the key belongs to, from `/v1/me` (`workspace: { id, name, personal,
85
+ * iconUrl }`), with the icon's link made absolute against the API's address. Undefined
86
+ * when the API does not say (an older VocalStack).
87
+ */
88
+ export declare function workspaceOf(me: Record<string, unknown>, baseURL?: string): ConnectionWorkspace | undefined;
package/dist/api.js CHANGED
@@ -3,6 +3,10 @@
3
3
  * SDK is not on npm yet). Contract: https://api.vocalstack.com/v1/openapi.json
4
4
  */
5
5
  export const DEFAULT_API_URL = 'https://api.vocalstack.com';
6
+ /** Sent as the User-Agent of every call to VocalStack (they run in the
7
+ * handler, on the server): VocalStack lists the transcriptions it makes
8
+ * as made in Sanity. Keep it to package.json's version. */
9
+ export const PLUGIN_VERSION = '0.3.0';
6
10
  export const DEFAULT_DASHBOARD_URL = 'https://app.vocalstack.com';
7
11
  export class VocalStackAPIError extends Error {
8
12
  code;
@@ -21,7 +25,7 @@ export class VocalStackAPI {
21
25
  this.baseURL = baseURL;
22
26
  }
23
27
  async request(method, path, body, headers = {}) {
24
- const init = { headers: { accept: 'application/json', authorization: `Bearer ${this.apiKey}`, ...headers }, method };
28
+ const init = { headers: { accept: 'application/json', authorization: `Bearer ${this.apiKey}`, 'user-agent': `VocalStack-Sanity/${PLUGIN_VERSION}`, ...headers }, method };
25
29
  if (body instanceof FormData)
26
30
  init.body = body;
27
31
  else if (body !== undefined) {
@@ -48,15 +52,15 @@ export class VocalStackAPI {
48
52
  form.append('file', file, fileName);
49
53
  return this.request('POST', '/v1/transcriptions', form, { 'idempotency-key': opts.idempotencyKey });
50
54
  }
51
- job(recordingId) {
52
- return this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/job`);
55
+ job(transcriptionId) {
56
+ return this.request('GET', `/v1/transcriptions/${encodeURIComponent(transcriptionId)}/job`);
53
57
  }
54
58
  /** 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 });
59
+ stop(transcriptionId, reason) {
60
+ return this.request('POST', `/v1/transcriptions/${encodeURIComponent(transcriptionId)}/stop`, { reason: reason ?? null });
57
61
  }
58
- transcript(recordingId) {
59
- return this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/transcript`);
62
+ transcript(transcriptionId) {
63
+ return this.request('GET', `/v1/transcriptions/${encodeURIComponent(transcriptionId)}/transcript`);
60
64
  }
61
65
  }
62
66
  /** A short label for the connected account, from whatever `/v1/me` carries. */
@@ -72,3 +76,23 @@ export function accountLabel(me) {
72
76
  };
73
77
  return pick(me.principal, 'name', 'displayName') ?? pick(me.organization, 'name') ?? pick(me.user, 'email', 'name') ?? pick(me, 'email', 'name', 'displayName');
74
78
  }
79
+ /**
80
+ * The workspace the key belongs to, from `/v1/me` (`workspace: { id, name, personal,
81
+ * iconUrl }`), with the icon's link made absolute against the API's address. Undefined
82
+ * when the API does not say (an older VocalStack).
83
+ */
84
+ export function workspaceOf(me, baseURL = DEFAULT_API_URL) {
85
+ const w = me.workspace;
86
+ if (!w || typeof w !== 'object' || typeof w.id !== 'string' || !w.id || typeof w.name !== 'string' || !w.name.trim())
87
+ return undefined;
88
+ let iconUrl = null;
89
+ if (typeof w.iconUrl === 'string' && w.iconUrl) {
90
+ try {
91
+ const url = new URL(w.iconUrl, baseURL);
92
+ if (url.protocol === 'https:' || url.protocol === 'http:')
93
+ iconUrl = url.href;
94
+ }
95
+ catch { }
96
+ }
97
+ return { iconUrl, id: w.id, name: w.name, personal: w.personal === true };
98
+ }
@@ -5,7 +5,9 @@ import { set, setIfMissing, unset, useFormValue } from 'sanity';
5
5
  import { findAudio, jobName, POLL_MS, restored, siblingFileRefs, TRANSCRIPT_TYPE } from '../core.js';
6
6
  import { HandlerError, useConnection, useHandler } from '../handler.js';
7
7
  import { transcriptText } from '../text.js';
8
+ import { NOT_IN_WORKSPACE } from '../wire.js';
8
9
  import { Logo, useAccent } from './Brand.js';
10
+ import { WorkspaceMark } from './WorkspaceMark.js';
9
11
  /** 2433.0 → "40:33", 4000 → "1:06:40". */
10
12
  const clock = (s) => {
11
13
  const t = Math.floor(s);
@@ -46,6 +48,10 @@ export function TranscriptInput(props) {
46
48
  const [stopping, setStopping] = useState(false);
47
49
  const [progress, setProgress] = useState({});
48
50
  const [error, setError] = useState();
51
+ // The transcription this field was following, when the connected workspace does not have it:
52
+ // VOCALSTACK_API_KEY now belongs to another workspace. The field offers Transcribe again.
53
+ const [lost, setLost] = useState();
54
+ const [changing, setChanging] = useState(false);
49
55
  // A short note after a job ends. Inline rather than a toast: Sanity UI moved its toasts between versions.
50
56
  const [notice, setNotice] = useState();
51
57
  useEffect(() => {
@@ -74,17 +80,17 @@ export function TranscriptInput(props) {
74
80
  setNotice('Transcript ready.');
75
81
  }, [apply]);
76
82
  // Follow a running job, also one started before a reload or from the document action:
77
- // recordingId and status are saved on the document.
83
+ // transcriptionId and status are saved on the document.
78
84
  const status = value?.status ?? 'idle';
79
- const recordingId = value?.recordingId;
85
+ const transcriptionId = value?.transcriptionId;
80
86
  useEffect(() => {
81
- if (status !== 'processing' || !recordingId)
87
+ if (status !== 'processing' || !transcriptionId)
82
88
  return;
83
89
  let cancelled = false;
84
90
  let timer;
85
91
  const tick = async () => {
86
92
  try {
87
- const outcome = await call(`/recordings/${encodeURIComponent(recordingId)}/job`);
93
+ const outcome = await call(`/transcriptions/${encodeURIComponent(transcriptionId)}/job`);
88
94
  if (cancelled)
89
95
  return;
90
96
  setError(undefined);
@@ -98,6 +104,8 @@ export function TranscriptInput(props) {
98
104
  catch (err) {
99
105
  if (cancelled)
100
106
  return;
107
+ if (err instanceof HandlerError && err.code === NOT_IN_WORKSPACE)
108
+ setLost(transcriptionId);
101
109
  // A network blip or a server hiccup should not end the wait; anything refused should.
102
110
  if (err instanceof HandlerError && err.status && err.status < 500)
103
111
  return setError(err.message);
@@ -111,7 +119,7 @@ export function TranscriptInput(props) {
111
119
  cancelled = true;
112
120
  clearTimeout(timer);
113
121
  };
114
- }, [call, finish, recordingId, status]);
122
+ }, [call, finish, status, transcriptionId]);
115
123
  const transcribe = async () => {
116
124
  if (!asset)
117
125
  return;
@@ -121,7 +129,7 @@ export function TranscriptInput(props) {
121
129
  setProgress({});
122
130
  try {
123
131
  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 });
132
+ apply({ ...(await call('/transcriptions', { body, method: 'POST' })), error: null, recordingId: null });
125
133
  }
126
134
  catch (err) {
127
135
  setError(err.message);
@@ -132,24 +140,29 @@ export function TranscriptInput(props) {
132
140
  };
133
141
  /** Stop the job. The field goes back to how it was; VocalStack keeps what it heard so far. */
134
142
  const stop = async () => {
135
- if (!recordingId)
143
+ if (!transcriptionId)
136
144
  return;
137
145
  if (!window.confirm('Stop transcribing? What VocalStack has transcribed so far stays in your VocalStack dashboard.'))
138
146
  return;
139
147
  setStopping(true);
140
148
  try {
141
- const outcome = await call(`/recordings/${encodeURIComponent(recordingId)}/stop`, { method: 'POST' });
149
+ const outcome = await call(`/transcriptions/${encodeURIComponent(transcriptionId)}/stop`, { method: 'POST' });
142
150
  if (outcome.kind !== 'processing')
143
151
  finish(outcome);
144
152
  }
145
153
  catch (err) {
154
+ if (err instanceof HandlerError && err.code === NOT_IN_WORKSPACE)
155
+ setLost(transcriptionId);
146
156
  setError(err.message);
147
157
  }
148
158
  finally {
149
159
  setStopping(false);
150
160
  }
151
161
  };
152
- const busy = status === 'processing';
162
+ // A job saved without a transcription id cannot be followed: offer Transcribe again.
163
+ const isLost = status === 'processing' && (!transcriptionId || lost === transcriptionId);
164
+ const busy = status === 'processing' && !isLost;
165
+ const workspace = connection?.connected ? connection.workspace : undefined;
153
166
  const shownError = error ?? (status === 'failed' ? (value?.error ?? undefined) : undefined);
154
167
  const partialText = useMemo(() => (busy && progress.partial?.length ? transcriptText(progress.partial) : undefined), [busy, progress.partial]);
155
168
  const muted = { muted: true, size: 1 };
@@ -164,9 +177,9 @@ export function TranscriptInput(props) {
164
177
  else if (!asset && !busy)
165
178
  action = _jsx(Text, { ...muted, children: refs.length ? 'Only audio files can be transcribed.' : 'Add an audio file, then transcribe.' });
166
179
  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' })] }));
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' })] }));
168
181
  }
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) => {
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) => {
170
183
  const text = e.currentTarget.value;
171
184
  onChange([setIfMissing({ _type: TRANSCRIPT_TYPE }), text ? set(text, ['transcript']) : unset(['transcript'])]);
172
185
  }, readOnly: readOnly || Boolean(partialText), rows: 10, value: partialText ?? value?.transcript ?? '' }) }))] }) }));
@@ -0,0 +1,9 @@
1
+ import type { ConnectionWorkspace } from '../wire.js';
2
+ /**
3
+ * A workspace's mark, as the VocalStack Dashboard draws it: its own icon when it has
4
+ * one; else a person for the personal workspace; else its initials on its colour.
5
+ */
6
+ export declare function WorkspaceMark({ size, workspace }: {
7
+ size?: number;
8
+ workspace: ConnectionWorkspace;
9
+ }): import("react").JSX.Element;
@@ -0,0 +1,45 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useEffect, useState } from 'react';
3
+ import { workspaceHue, workspaceInitials } from '../workspaceMark.js';
4
+ import { useDark } from './Brand.js';
5
+ const PERSON = 'M15.75 6a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0ZM4.501 20.118a7.5 7.5 0 0 1 14.998 0A17.933 17.933 0 0 1 12 21.75c-2.676 0-5.216-.584-7.499-1.632Z';
6
+ /**
7
+ * A workspace's mark, as the VocalStack Dashboard draws it: its own icon when it has
8
+ * one; else a person for the personal workspace; else its initials on its colour.
9
+ */
10
+ export function WorkspaceMark({ size = 20, workspace }) {
11
+ const dark = useDark();
12
+ const { iconUrl } = workspace;
13
+ // An icon that does not load (a link signed long ago, a network that blocks it) gives way to the drawn mark.
14
+ const [broken, setBroken] = useState();
15
+ useEffect(() => setBroken(undefined), [iconUrl]);
16
+ const ink = dark ? '#fff' : '#101112';
17
+ const hair = `inset 0 0 0 1px color-mix(in oklab, ${ink} 14%, transparent)`;
18
+ const tile = {
19
+ alignItems: 'center',
20
+ borderRadius: Math.round(size * 0.29),
21
+ display: 'inline-flex',
22
+ flex: 'none',
23
+ fontSize: Math.round(size * 0.39),
24
+ fontWeight: 600,
25
+ height: size,
26
+ justifyContent: 'center',
27
+ letterSpacing: '.02em',
28
+ lineHeight: 1,
29
+ width: size,
30
+ };
31
+ if (iconUrl && broken !== iconUrl) {
32
+ return (_jsx("span", { "aria-hidden": "true", "data-mark": "icon", style: { ...tile, background: `color-mix(in oklab, ${ink} 6%, transparent)`, boxShadow: hair, overflow: 'hidden' }, children: _jsx("img", { alt: "", draggable: false, onError: () => setBroken(iconUrl), src: iconUrl, style: { display: 'block', height: '100%', objectFit: 'cover', width: '100%' } }) }));
33
+ }
34
+ if (workspace.personal) {
35
+ const glyph = Math.round(size * 0.55);
36
+ return (_jsx("span", { "aria-hidden": "true", "data-mark": "personal", style: { ...tile, background: `color-mix(in oklab, ${ink} 9%, transparent)`, boxShadow: hair, color: `color-mix(in oklab, ${ink} 70%, transparent)` }, children: _jsx("svg", { fill: "none", height: glyph, stroke: "currentColor", strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 1.6, viewBox: "0 0 24 24", width: glyph, children: _jsx("path", { d: PERSON }) }) }));
37
+ }
38
+ const colour = `oklch(.66 .13 ${workspaceHue(workspace.id)})`;
39
+ return (_jsx("span", { "aria-hidden": "true", "data-mark": "initials", style: {
40
+ ...tile,
41
+ background: `color-mix(in oklab, ${colour} 22%, transparent)`,
42
+ boxShadow: `inset 0 0 0 1px color-mix(in oklab, ${colour} 30%, transparent)`,
43
+ color: `color-mix(in oklab, ${colour} 72%, ${ink})`,
44
+ }, children: workspaceInitials(workspace.name) }));
45
+ }
package/dist/schema.js CHANGED
@@ -41,7 +41,7 @@ export const transcriptType = (options) => defineType({
41
41
  }),
42
42
  defineField({ name: 'language', type: 'string', readOnly: true }),
43
43
  defineField({ name: 'error', type: 'string', readOnly: true }),
44
- defineField({ name: 'recordingId', title: 'Recording ID', type: 'string', readOnly: true }),
44
+ defineField({ name: 'recordingId', title: 'Recording ID', type: 'string', readOnly: true, hidden: true }),
45
45
  defineField({ name: 'transcriptionId', title: 'Transcription ID', type: 'string', readOnly: true }),
46
46
  defineField({ name: 'transcribedAt', type: 'datetime', readOnly: true }),
47
47
  ],
@@ -1,4 +1,4 @@
1
- export type { ConnectionResponse, JobOutcome, StartRequest, StartResponse } from '../wire.js';
1
+ export type { ConnectionResponse, ConnectionWorkspace, JobOutcome, StartRequest, StartResponse } from '../wire.js';
2
2
  export type VocalStackHandlerOptions = {
3
3
  /** A VocalStack API key (`vs_key_…`, Read + Write). Default: `process.env.VOCALSTACK_API_KEY`. */
4
4
  apiKey?: string;
@@ -38,4 +38,9 @@ export type SanityFileAsset = {
38
38
  url?: string;
39
39
  };
40
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;
41
46
  export declare function createVocalStackHandler(options: VocalStackHandlerOptions): Handler;
@@ -1,5 +1,5 @@
1
- import { accountLabel, DEFAULT_API_URL, VocalStackAPI, VocalStackAPIError } from '../api.js';
2
- import { SESSION_MAX_AGE_MS, SESSION_PREFIX, SESSION_TYPE, sha256Hex } from '../wire.js';
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
3
  import { checkJob, stopJob } from './jobs.js';
4
4
  /** `https://<projectId>.api.sanity.io`, or the custom API host, as `@sanity/client` builds it. */
5
5
  function sanityHost({ apiHost = 'https://api.sanity.io', projectId, useProjectHostname = true }) {
@@ -36,12 +36,17 @@ async function fetchFile(url) {
36
36
  }
37
37
  /** Verified sessions, briefly, so a poll every 3 s is not a Sanity query every 3 s. */
38
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;
39
44
  export function createVocalStackHandler(options) {
40
45
  const apiKey = options.apiKey ?? globalThis.process?.env?.VOCALSTACK_API_KEY;
41
46
  const { dataset, projectId, token } = options.sanity;
42
47
  const sanityBase = `${sanityHost(options.sanity)}/v${(options.sanity.apiVersion ?? '2024-01-01').replace(/^v/, '')}`;
43
48
  const sessions = new Map();
44
- let account;
49
+ let connection;
45
50
  async function query(groq, params) {
46
51
  const url = new URL(`${sanityBase}/data/query/${encodeURIComponent(dataset)}`);
47
52
  url.searchParams.set('query', groq);
@@ -92,9 +97,9 @@ export function createVocalStackHandler(options) {
92
97
  if (request.method === 'OPTIONS')
93
98
  return new Response(null, { headers, status: 204 });
94
99
  // The route's tail, wherever the handler is mounted: …/connection, …/transcriptions,
95
- // …/recordings/:id/job, …/recordings/:id/stop.
100
+ // …/transcriptions/:id/job, …/transcriptions/:id/stop.
96
101
  const path = new URL(request.url).pathname.replace(/\/+$/, '');
97
- const route = path.match(/\/(connection|transcriptions)$/)?.[1] ?? path.match(/\/recordings\/([^/]+)\/(job|stop)$/)?.slice(1).join(' ');
102
+ const route = path.match(/\/(connection|transcriptions)$/)?.[1] ?? path.match(/\/transcriptions\/([^/]+)\/(job|stop)$/)?.slice(1).join(' ');
98
103
  if (!route)
99
104
  return fail(404, 'Not a VocalStack route.');
100
105
  try {
@@ -106,11 +111,17 @@ export function createVocalStackHandler(options) {
106
111
  }
107
112
  if (!apiKey)
108
113
  return fail(503, 'VOCALSTACK_API_KEY is not set where the VocalStack handler runs.', 'not_connected');
109
- const api = new VocalStackAPI(apiKey, options.apiURL ?? DEFAULT_API_URL);
114
+ const apiURL = options.apiURL ?? DEFAULT_API_URL;
115
+ const api = new VocalStackAPI(apiKey, apiURL);
116
+ const jobRoute = route !== 'connection' && route !== 'transcriptions';
110
117
  try {
111
118
  if (route === 'connection' && request.method === 'GET') {
112
- account ??= accountLabel(await api.me());
113
- return json({ account, connected: true });
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);
114
125
  }
115
126
  if (route === 'transcriptions' && request.method === 'POST') {
116
127
  const body = (await request.json().catch(() => ({})));
@@ -133,19 +144,24 @@ export function createVocalStackHandler(options) {
133
144
  const tx = isPublicURL(url) ? await api.transcribeURL(url, job) : await api.transcribeFile(await fetchFile(url), asset.originalFilename || 'audio', job);
134
145
  if (!tx.job)
135
146
  return fail(502, 'VocalStack did not start a job for this file.');
136
- return json({ recordingId: tx.job.recordingId, status: 'processing', transcriptionId: tx.id }, 202);
147
+ return json({ status: 'processing', transcriptionId: tx.id }, 202);
137
148
  }
138
- const [recordingId, action] = route.split(' ');
149
+ const [transcriptionId, action] = route.split(' ');
139
150
  if (action === 'job' && request.method === 'GET')
140
- return json(await checkJob(api, decodeURIComponent(recordingId)));
151
+ return json(await checkJob(api, decodeURIComponent(transcriptionId)));
141
152
  if (action === 'stop' && request.method === 'POST')
142
- return json(await stopJob(api, decodeURIComponent(recordingId)));
153
+ return json(await stopJob(api, decodeURIComponent(transcriptionId)));
143
154
  return fail(405, 'Method not allowed.');
144
155
  }
145
156
  catch (err) {
146
157
  if (err instanceof VocalStackAPIError) {
147
158
  if (err.status === 401)
148
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
+ // transcription made with the old key is not found (as is one deleted in VocalStack).
162
+ if (err.status === 404 && jobRoute) {
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
+ }
149
165
  return fail(err.status >= 500 ? 502 : err.status, err.message, err.code);
150
166
  }
151
167
  return fail(500, err instanceof Error ? err.message : String(err));
@@ -5,6 +5,6 @@ import { type Transcript, type VocalStackAPI } from '../api.js';
5
5
  export declare function toSentences(t: Pick<Transcript, 'sentences'>): TranscriptSentence[];
6
6
  /** As stored on the document: an array item needs a `_key`. */
7
7
  export declare const toSaved: (sentences: TranscriptSentence[]) => SavedSentence[];
8
- export declare function checkJob(api: VocalStackAPI, recordingId: string): Promise<JobOutcome>;
8
+ export declare function checkJob(api: VocalStackAPI, transcriptionId: string): Promise<JobOutcome>;
9
9
  /** Stop a job. If it ended meanwhile, take its outcome instead. */
10
- export declare function stopJob(api: VocalStackAPI, recordingId: string): Promise<JobOutcome>;
10
+ export declare function stopJob(api: VocalStackAPI, transcriptionId: string): Promise<JobOutcome>;
@@ -9,8 +9,8 @@ export function toSentences(t) {
9
9
  const round = (n) => Math.round(n * 1000) / 1000;
10
10
  /** As stored on the document: an array item needs a `_key`. */
11
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);
12
+ export async function checkJob(api, transcriptionId) {
13
+ const job = await api.job(transcriptionId);
14
14
  if (job.state === 'stopped' || (job.state === 'failed' && job.errorCode === 'stopped'))
15
15
  return { kind: 'stopped' };
16
16
  if (job.state === 'failed' || job.state === 'cropping') {
@@ -22,10 +22,10 @@ export async function checkJob(api, recordingId) {
22
22
  if (job.state !== 'transcribing')
23
23
  return { kind: 'processing', phase: job.progress.phase ?? job.state, progress };
24
24
  // Sentences are readable while the job runs; send what is there so far.
25
- const partial = await api.transcript(recordingId).then(toSentences, () => undefined);
25
+ const partial = await api.transcript(transcriptionId).then(toSentences, () => undefined);
26
26
  return { audio: { processedS: job.progress.processedS ?? 0, totalS: job.progress.totalS ?? undefined }, kind: 'processing', partial, phase: 'transcribing', progress };
27
27
  }
28
- const transcript = await api.transcript(recordingId);
28
+ const transcript = await api.transcript(transcriptionId);
29
29
  const sentences = toSentences(transcript);
30
30
  return {
31
31
  kind: 'done',
@@ -40,14 +40,14 @@ export async function checkJob(api, recordingId) {
40
40
  };
41
41
  }
42
42
  /** Stop a job. If it ended meanwhile, take its outcome instead. */
43
- export async function stopJob(api, recordingId) {
43
+ export async function stopJob(api, transcriptionId) {
44
44
  try {
45
- await api.stop(recordingId, 'Stopped from Sanity');
45
+ await api.stop(transcriptionId, 'Stopped from Sanity');
46
46
  return { kind: 'stopped' };
47
47
  }
48
48
  catch (err) {
49
49
  if (err instanceof VocalStackAPIError && err.status === 409)
50
- return checkJob(api, recordingId).catch(() => ({ kind: 'stopped' }));
50
+ return checkJob(api, transcriptionId).catch(() => ({ kind: 'stopped' }));
51
51
  throw err;
52
52
  }
53
53
  }
package/dist/types.d.ts CHANGED
@@ -33,6 +33,7 @@ export type VocalStackTranscript = {
33
33
  _type?: 'vocalstack.transcript';
34
34
  error?: null | string;
35
35
  language?: null | string;
36
+ /** Written by versions before 0.3.0; no longer read (VocalStack's API has no recordings). */
36
37
  recordingId?: null | string;
37
38
  sentences?: null | SavedSentence[];
38
39
  status?: null | TranscriptStatus;
package/dist/wire.d.ts CHANGED
@@ -32,12 +32,27 @@ export type StartRequest = {
32
32
  /** The transcription's name in VocalStack. Default: the file's name. */
33
33
  name?: string;
34
34
  };
35
- export type StartResponse = Required<Pick<VocalStackTranscript, 'recordingId' | 'status' | 'transcriptionId'>>;
35
+ export type StartResponse = Required<Pick<VocalStackTranscript, 'status' | 'transcriptionId'>>;
36
36
  /** `GET {handlerURL}/connection` */
37
37
  export type ConnectionResponse = {
38
+ /** The workspace's name; against an older VocalStack, the key's label. */
38
39
  account?: string;
39
40
  connected: boolean;
41
+ /** The workspace the handler's API key belongs to. Absent against a VocalStack that does not say. */
42
+ workspace?: ConnectionWorkspace;
40
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 transcription is not in the workspace its key belongs to. */
55
+ export declare const NOT_IN_WORKSPACE = "not_in_workspace";
41
56
  /** Every error: `{ code?, error }`. `session` means the Studio should prove itself again. */
42
57
  export type ErrorResponse = {
43
58
  code?: string;
package/dist/wire.js CHANGED
@@ -1,3 +1,5 @@
1
+ /** The handler's `code` when a transcription is not in the workspace its key belongs to. */
2
+ export const NOT_IN_WORKSPACE = 'not_in_workspace';
1
3
  /** The document type of a Studio session (see `SESSION_PREFIX`). */
2
4
  export const SESSION_TYPE = 'vocalstack.session';
3
5
  /** Session ids are `vocalstack-session.<sha256 hex of the secret>`: dotted, so never public. */
@@ -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,6 @@
1
1
  {
2
2
  "name": "@vocalstack/sanity",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "VocalStack for Sanity Studio: a Transcribe button next to every audio file.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -22,7 +22,8 @@
22
22
  "sideEffects": false,
23
23
  "scripts": {
24
24
  "build": "rm -rf dist && tsc -p tsconfig.json",
25
- "typecheck": "tsc -p tsconfig.json --noEmit"
25
+ "typecheck": "tsc -p tsconfig.json --noEmit",
26
+ "test": "npm run build && node --test test/*.test.mjs"
26
27
  },
27
28
  "peerDependencies": {
28
29
  "@sanity/ui": "^2.0.0 || ^3.0.0 || ^4.0.0",