@vocalstack/payload 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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +141 -2
  3. package/dist/api.d.ts +171 -0
  4. package/dist/api.js +178 -0
  5. package/dist/components/Brand.d.ts +13 -0
  6. package/dist/components/Brand.js +19 -0
  7. package/dist/components/ConnectionPanel.d.ts +3 -0
  8. package/dist/components/ConnectionPanel.js +41 -0
  9. package/dist/components/SpeechField.d.ts +7 -0
  10. package/dist/components/SpeechField.js +177 -0
  11. package/dist/components/TranscribeButton.d.ts +8 -0
  12. package/dist/components/TranscribeButton.js +197 -0
  13. package/dist/components/TranscriptField.d.ts +3 -0
  14. package/dist/components/TranscriptField.js +167 -0
  15. package/dist/components/VoiceField.d.ts +1 -0
  16. package/dist/components/VoiceField.js +226 -0
  17. package/dist/components/brandAssets.d.ts +11 -0
  18. package/dist/components/brandAssets.js +6 -0
  19. package/dist/components/useConnection.d.ts +11 -0
  20. package/dist/components/useConnection.js +59 -0
  21. package/dist/endpoints/connection.d.ts +14 -0
  22. package/dist/endpoints/connection.js +132 -0
  23. package/dist/endpoints/speech.d.ts +12 -0
  24. package/dist/endpoints/speech.js +392 -0
  25. package/dist/endpoints/stream.d.ts +14 -0
  26. package/dist/endpoints/stream.js +180 -0
  27. package/dist/endpoints/transcribe.d.ts +33 -0
  28. package/dist/endpoints/transcribe.js +268 -0
  29. package/dist/endpoints/voices.d.ts +20 -0
  30. package/dist/endpoints/voices.js +275 -0
  31. package/dist/exports/client.d.ts +5 -0
  32. package/dist/exports/client.js +6 -0
  33. package/dist/fileSource.d.ts +12 -0
  34. package/dist/fileSource.js +40 -0
  35. package/dist/index.d.ts +7 -0
  36. package/dist/index.js +184 -0
  37. package/dist/readings.d.ts +6 -0
  38. package/dist/readings.js +24 -0
  39. package/dist/settings.d.ts +20 -0
  40. package/dist/settings.js +47 -0
  41. package/dist/text.d.ts +29 -0
  42. package/dist/text.js +78 -0
  43. package/dist/types.d.ts +218 -0
  44. package/dist/types.js +1 -0
  45. package/package.json +47 -4
package/dist/index.js ADDED
@@ -0,0 +1,184 @@
1
+ import { connectionEndpoints } from './endpoints/connection.js';
2
+ import { speechEndpoints } from './endpoints/speech.js';
3
+ import { streamEndpoint } from './endpoints/stream.js';
4
+ import { transcribeEndpoints } from './endpoints/transcribe.js';
5
+ import { lookupEndpoints, voiceEndpoints } from './endpoints/voices.js';
6
+ import { readingsCollection, readingsSlug } from './readings.js';
7
+ import { settingsGlobal } from './settings.js';
8
+ export { spokenSentences, timedTokens, transcriptText } from './text.js';
9
+ /** The voice to read translations in (`clone:<id>`), once a person's cloned voice is ready. */
10
+ export const clonedVoiceKey = (data) => data?.state === 'ready' && data.voiceId ? `clone:${data.voiceId}` : undefined;
11
+ const isAudioDoc = (data) => typeof data?.mimeType === 'string' && data.mimeType.startsWith('audio/');
12
+ /** An upload collection that can hold audio: `audio/*`, a wildcard, or no restriction at all. */
13
+ function acceptsAudio(collection) {
14
+ if (!collection.upload)
15
+ return false;
16
+ const mimeTypes = collection.upload === true ? undefined : collection.upload.mimeTypes;
17
+ return !mimeTypes?.length || mimeTypes.some((m) => m.startsWith('audio') || m === '*' || m === '*/*');
18
+ }
19
+ const hidden = { admin: { hidden: true, readOnly: true } };
20
+ /** The Transcribe button and the `vocalstack` group, for an upload document or for each row of an array. */
21
+ function transcriptionFields(enabled, options, target) {
22
+ return [
23
+ ...(enabled
24
+ ? [
25
+ {
26
+ name: 'vocalstackTranscribe',
27
+ type: 'ui',
28
+ admin: {
29
+ components: {
30
+ Field: {
31
+ clientProps: { field: target.field, oneClickConnect: Boolean(options.oneClickConnect) },
32
+ path: '@vocalstack/payload/client#TranscribeButton',
33
+ },
34
+ },
35
+ condition: target.condition,
36
+ ...(target.sidebar ? { position: 'sidebar' } : {}),
37
+ },
38
+ },
39
+ ]
40
+ : []),
41
+ {
42
+ name: 'vocalstack',
43
+ type: 'group',
44
+ label: 'Transcript',
45
+ admin: { condition: target.condition },
46
+ fields: [
47
+ {
48
+ name: 'transcript',
49
+ type: 'textarea',
50
+ label: false,
51
+ admin: { components: { Field: '@vocalstack/payload/client#TranscriptField' } },
52
+ },
53
+ {
54
+ name: 'status',
55
+ type: 'select',
56
+ defaultValue: 'idle',
57
+ options: ['idle', 'processing', 'done', 'failed'],
58
+ ...hidden,
59
+ },
60
+ { name: 'error', type: 'text', ...hidden },
61
+ { name: 'language', type: 'text', ...hidden },
62
+ { name: 'recordingId', type: 'text', ...hidden },
63
+ { name: 'transcriptionId', type: 'text', ...hidden },
64
+ { name: 'transcribedAt', type: 'date', ...hidden },
65
+ // [{ start, end, speaker, text }] in seconds, for captions or a synced player.
66
+ { name: 'sentences', type: 'json', ...hidden },
67
+ // { [lang]: { translatedAt, sentences } }: the sentences above, translated.
68
+ { name: 'translations', type: 'json', ...hidden },
69
+ // { [lang]: { voice, state, …, sentences } }: translations read aloud, in the reading's timing.
70
+ { name: 'speech', type: 'json', ...hidden },
71
+ ...(enabled
72
+ ? [
73
+ {
74
+ name: 'vocalstackSpeech',
75
+ type: 'ui',
76
+ admin: {
77
+ components: { Field: { clientProps: { field: target.field }, path: '@vocalstack/payload/client#SpeechField' } },
78
+ condition: (_, siblingData) => siblingData?.status === 'done',
79
+ },
80
+ },
81
+ ]
82
+ : []),
83
+ ],
84
+ },
85
+ ];
86
+ }
87
+ /** A person's cloned voice: the panel, and what VocalStack says about the voice. */
88
+ function voiceFields(enabled) {
89
+ return [
90
+ ...(enabled
91
+ ? [
92
+ {
93
+ name: 'vocalstackVoicePanel',
94
+ type: 'ui',
95
+ admin: { components: { Field: '@vocalstack/payload/client#VoiceField' }, position: 'sidebar' },
96
+ },
97
+ ]
98
+ : []),
99
+ {
100
+ name: 'vocalstackVoice',
101
+ type: 'group',
102
+ label: 'Voice',
103
+ admin: { hidden: true },
104
+ fields: [
105
+ { name: 'voiceId', type: 'text', ...hidden },
106
+ { name: 'state', type: 'select', defaultValue: 'none', options: ['none', 'training', 'ready', 'failed'], ...hidden },
107
+ { name: 'progress', type: 'number', ...hidden },
108
+ { name: 'error', type: 'text', ...hidden },
109
+ { name: 'sampleS', type: 'number', ...hidden },
110
+ { name: 'consentAt', type: 'date', ...hidden },
111
+ { name: 'createdAt', type: 'date', ...hidden },
112
+ ],
113
+ },
114
+ ];
115
+ }
116
+ /** Add fields to the named array, looking through unnamed containers (rows, collapsibles, unnamed tabs). */
117
+ function addToArray(fields, name, extra) {
118
+ let found = false;
119
+ const visit = (list) => list.map((f) => {
120
+ if (found)
121
+ return f;
122
+ if (f.type === 'array' && f.name === name) {
123
+ found = true;
124
+ return { ...f, fields: [...f.fields, ...extra] };
125
+ }
126
+ if ((f.type === 'row' || f.type === 'collapsible') && !('name' in f && f.name))
127
+ return { ...f, fields: visit(f.fields) };
128
+ if (f.type === 'tabs')
129
+ return { ...f, tabs: f.tabs.map((t) => ('name' in t && t.name ? t : { ...t, fields: visit(t.fields) })) };
130
+ return f;
131
+ });
132
+ return { fields: visit(fields), found };
133
+ }
134
+ export const vocalstackPlugin = (options = {}) => (config) => {
135
+ const enabled = options.enabled !== false;
136
+ const collections = config.collections ?? [];
137
+ const readings = readingsSlug(options);
138
+ const uploads = new Set(options.collections ?? collections.filter((c) => c.slug !== readings && acceptsAudio(c)).map((c) => c.slug));
139
+ const audioFields = options.audioFields ?? [];
140
+ const voices = options.voices ?? [];
141
+ for (const v of voices) {
142
+ if (!collections.some((c) => c.slug === v.collection))
143
+ throw new Error(`vocalstackPlugin: no collection "${v.collection}" for voices`);
144
+ }
145
+ return {
146
+ ...config,
147
+ collections: [...collections, ...(readings && !collections.some((c) => c.slug === readings) ? [(options.readings && options.readings.overrides ? options.readings.overrides : (c) => c)(readingsCollection(readings))] : [])].map((original) => {
148
+ const voice = voices.find((v) => v.collection === original.slug);
149
+ const collection = voice
150
+ ? {
151
+ ...original,
152
+ endpoints: enabled ? [...(original.endpoints || []), ...voiceEndpoints(voice, options)] : original.endpoints,
153
+ fields: [...original.fields, ...voiceFields(enabled)],
154
+ }
155
+ : original;
156
+ const rowFields = audioFields.filter((f) => f.collection === collection.slug);
157
+ const isUpload = uploads.has(collection.slug);
158
+ if (!isUpload && !rowFields.length)
159
+ return collection;
160
+ let fields = isUpload ? [...collection.fields, ...transcriptionFields(enabled, options, { condition: isAudioDoc, sidebar: true })] : collection.fields;
161
+ for (const row of rowFields) {
162
+ const condition = (_, siblingData) => (row.condition ? row.condition(siblingData) : true);
163
+ const result = addToArray(fields, row.field, transcriptionFields(enabled, options, { condition, field: row.field, sidebar: false }));
164
+ if (!result.found)
165
+ throw new Error(`vocalstackPlugin: no array field "${row.field}" in collection "${collection.slug}"`);
166
+ fields = result.fields;
167
+ }
168
+ return {
169
+ ...collection,
170
+ endpoints: enabled
171
+ ? [
172
+ ...(collection.endpoints || []),
173
+ ...transcribeEndpoints(collection.slug, options, rowFields),
174
+ streamEndpoint(collection.slug, options, rowFields),
175
+ ...speechEndpoints(collection.slug, options, rowFields),
176
+ ]
177
+ : collection.endpoints,
178
+ fields,
179
+ };
180
+ }),
181
+ endpoints: enabled ? [...(config.endpoints ?? []), ...connectionEndpoints(options), ...lookupEndpoints(options)] : config.endpoints,
182
+ globals: [...(config.globals ?? []), settingsGlobal(options)],
183
+ };
184
+ };
@@ -0,0 +1,6 @@
1
+ import type { CollectionConfig, CollectionSlug } from 'payload';
2
+ import type { VocalStackPluginOptions } from './types.js';
3
+ /** The upload collection finished readings are saved in, or none. */
4
+ export declare const readingsSlug: (options: VocalStackPluginOptions) => CollectionSlug | undefined;
5
+ /** Spoken readings, kept as MP3 uploads so they are served from the site's own storage. */
6
+ export declare const readingsCollection: (slug: CollectionSlug) => CollectionConfig;
@@ -0,0 +1,24 @@
1
+ /** The upload collection finished readings are saved in, or none. */
2
+ export const readingsSlug = (options) => options.readings === false ? undefined : (options.readings?.slug ?? 'vocalstack-readings');
3
+ /** Spoken readings, kept as MP3 uploads so they are served from the site's own storage. */
4
+ export const readingsCollection = (slug) => ({
5
+ slug,
6
+ labels: { plural: 'Readings', singular: 'Reading' },
7
+ admin: {
8
+ description: 'Translations read aloud, saved from VocalStack once they are ready. Made and removed from the transcript.',
9
+ group: 'VocalStack',
10
+ useAsTitle: 'filename',
11
+ },
12
+ access: {
13
+ create: ({ req }) => Boolean(req.user),
14
+ delete: ({ req }) => Boolean(req.user),
15
+ read: () => true,
16
+ update: ({ req }) => Boolean(req.user),
17
+ },
18
+ upload: { mimeTypes: ['audio/mpeg'] },
19
+ fields: [
20
+ { name: 'lang', type: 'text', admin: { readOnly: true } },
21
+ { name: 'recordingId', type: 'text', admin: { readOnly: true } },
22
+ { name: 'voice', type: 'text', admin: { readOnly: true } },
23
+ ],
24
+ });
@@ -0,0 +1,20 @@
1
+ import type { GlobalConfig, PayloadRequest } from 'payload';
2
+ import type { VocalStackPluginOptions } from './types.js';
3
+ export declare const SETTINGS_SLUG = "vocalstack";
4
+ /**
5
+ * Where a key connected from the admin lives. Nothing here is readable or
6
+ * writable over the REST/GraphQL APIs: only the plugin's endpoints touch it
7
+ * (with `overrideAccess`), so the key never reaches a browser.
8
+ */
9
+ export declare const settingsGlobal: (options: VocalStackPluginOptions) => GlobalConfig;
10
+ export type StoredSettings = {
11
+ account?: null | string;
12
+ apiKey?: null | string;
13
+ connectExpiresAt?: null | string;
14
+ connectState?: null | string;
15
+ connectVerifier?: null | string;
16
+ };
17
+ export declare function readSettings(req: PayloadRequest): Promise<StoredSettings>;
18
+ export declare function writeSettings(req: PayloadRequest, data: StoredSettings): Promise<void>;
19
+ /** The key to call VocalStack with: the plugin option first, then a connected one. */
20
+ export declare function resolveAPIKey(req: PayloadRequest, options: VocalStackPluginOptions): Promise<string | undefined>;
@@ -0,0 +1,47 @@
1
+ export const SETTINGS_SLUG = 'vocalstack';
2
+ const hidden = { admin: { hidden: true }, access: { read: () => false, update: () => false } };
3
+ /**
4
+ * Where a key connected from the admin lives. Nothing here is readable or
5
+ * writable over the REST/GraphQL APIs: only the plugin's endpoints touch it
6
+ * (with `overrideAccess`), so the key never reaches a browser.
7
+ */
8
+ export const settingsGlobal = (options) => ({
9
+ slug: SETTINGS_SLUG,
10
+ label: 'VocalStack',
11
+ admin: {
12
+ group: 'Settings',
13
+ },
14
+ access: {
15
+ read: ({ req }) => Boolean(req.user),
16
+ update: () => false,
17
+ },
18
+ fields: [
19
+ {
20
+ name: 'connection',
21
+ type: 'ui',
22
+ admin: {
23
+ components: {
24
+ Field: { clientProps: { oneClickConnect: Boolean(options.oneClickConnect) }, path: '@vocalstack/payload/client#ConnectionPanel' },
25
+ },
26
+ },
27
+ },
28
+ { name: 'apiKey', type: 'text', ...hidden },
29
+ { name: 'account', type: 'text', ...hidden },
30
+ // A pending one-click connect: PKCE verifier and state, for ten minutes.
31
+ { name: 'connectState', type: 'text', ...hidden },
32
+ { name: 'connectVerifier', type: 'text', ...hidden },
33
+ { name: 'connectExpiresAt', type: 'date', ...hidden },
34
+ ],
35
+ });
36
+ export async function readSettings(req) {
37
+ return (await req.payload.findGlobal({ slug: SETTINGS_SLUG, overrideAccess: true, req }));
38
+ }
39
+ export async function writeSettings(req, data) {
40
+ await req.payload.updateGlobal({ slug: SETTINGS_SLUG, data, overrideAccess: true, req });
41
+ }
42
+ /** The key to call VocalStack with: the plugin option first, then a connected one. */
43
+ export async function resolveAPIKey(req, options) {
44
+ if (options.apiKey)
45
+ return options.apiKey;
46
+ return (await readSettings(req)).apiKey ?? undefined;
47
+ }
package/dist/text.d.ts ADDED
@@ -0,0 +1,29 @@
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[];
23
+ /**
24
+ * Translated sentences in the timing of their spoken track. The track keeps each
25
+ * sentence where it was said, unless the one before still runs: then it follows it
26
+ * after a short pause. Each sentence's words come from the clip's word times, paired
27
+ * with the translated text; when they do not pair up, they are spread evenly.
28
+ */
29
+ export declare function spokenSentences(translated: TranscriptSentence[], clipDur: Record<string, number>, wordTimes?: Record<string, [number, number][]>): TranscriptSentence[];
package/dist/text.js ADDED
@@ -0,0 +1,78 @@
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
+ }
53
+ /** The pause VocalStack leaves between two spoken sentences, at least. */
54
+ const SPOKEN_GAP_S = 0.15;
55
+ /**
56
+ * Translated sentences in the timing of their spoken track. The track keeps each
57
+ * sentence where it was said, unless the one before still runs: then it follows it
58
+ * after a short pause. Each sentence's words come from the clip's word times, paired
59
+ * with the translated text; when they do not pair up, they are spread evenly.
60
+ */
61
+ export function spokenSentences(translated, clipDur, wordTimes = {}) {
62
+ let cursor = 0;
63
+ const out = [];
64
+ for (const s of [...translated].sort((a, b) => (a.id ?? 0) - (b.id ?? 0))) {
65
+ const dur = s.id === undefined ? undefined : clipDur[String(s.id)];
66
+ if (!dur)
67
+ continue;
68
+ const at = Math.max(s.start, cursor);
69
+ cursor = at + dur + SPOKEN_GAP_S;
70
+ const tokens = s.text.trim().split(/\s+/).filter(Boolean);
71
+ const times = wordTimes[String(s.id)] ?? [];
72
+ const words = times.length === tokens.length
73
+ ? tokens.map((t, i) => [round(at + times[i][0]), round(at + times[i][1]), t])
74
+ : tokens.map((t, i) => [round(at + (i * dur) / tokens.length), round(at + ((i + 1) * dur) / tokens.length), t]);
75
+ out.push({ ...s, end: round(at + dur), start: round(at), words });
76
+ }
77
+ return out;
78
+ }
@@ -0,0 +1,218 @@
1
+ import type { CollectionConfig, CollectionSlug, PayloadRequest, TypeWithID } from 'payload';
2
+ export type VocalStackPluginOptions = {
3
+ /**
4
+ * Where finished spoken readings are kept: the plugin downloads each one's MP3
5
+ * once and saves it as an upload here, so listeners are served from your
6
+ * storage and VocalStack is not asked again. Default: an upload collection
7
+ * `vocalstack-readings` the plugin adds (point your storage adapter at it).
8
+ * `false` streams readings from VocalStack instead.
9
+ *
10
+ * `overrides` adjusts the added collection (access, labels, admin, upload
11
+ * options). A host may instead define its own upload collection with that slug;
12
+ * the plugin then uses it as it is. It needs to accept `audio/mpeg` and have text
13
+ * fields `lang`, `recordingId` and `voice`.
14
+ */
15
+ readings?: false | {
16
+ overrides?: (collection: CollectionConfig) => CollectionConfig;
17
+ slug?: CollectionSlug;
18
+ };
19
+ /** Turn the plugin off without removing it (fields stay in the schema). */
20
+ enabled?: boolean;
21
+ /**
22
+ * A VocalStack API key (`vs_key_…`, Read + Write). When set it wins over a key
23
+ * connected from the admin panel; leave it out to connect from the admin instead.
24
+ */
25
+ apiKey?: string;
26
+ /**
27
+ * Upload collections that get the Transcribe button. Defaults to every upload
28
+ * collection that accepts audio (or has no MIME type restriction). The button
29
+ * only appears on documents whose `mimeType` is `audio/*`.
30
+ */
31
+ collections?: CollectionSlug[];
32
+ /**
33
+ * Audio that is not an upload document: rows of an array field that each point
34
+ * at a file by address (a filename, an imported link). Every row gets its own
35
+ * Transcribe button and transcript.
36
+ */
37
+ audioFields?: AudioFieldConfig[];
38
+ /** Default https://api.vocalstack.com */
39
+ apiURL?: string;
40
+ /** Default https://app.vocalstack.com */
41
+ dashboardURL?: string;
42
+ /**
43
+ * Show "Connect VocalStack" (opens the dashboard in a new tab; one click on
44
+ * Authenticate there). Needs the dashboard's /connect flow; until then, paste a key.
45
+ */
46
+ oneClickConnect?: boolean;
47
+ /** A Whisper language code (`en`, `ro`, …). Leave out to auto-detect. */
48
+ spokenLanguage?: string;
49
+ /**
50
+ * The public URL VocalStack fetches the audio from. Defaults to the document's
51
+ * `url`, made absolute against `serverURL` or the request's origin. When that
52
+ * address is not public (localhost, a private network), the plugin uploads the
53
+ * file's bytes instead.
54
+ */
55
+ fileURL?: (args: {
56
+ collection: CollectionSlug;
57
+ doc: UploadDoc;
58
+ req: PayloadRequest;
59
+ }) => Promise<string | undefined> | string | undefined;
60
+ /** Who may start a transcription. Default: any signed-in user who can update the document. */
61
+ access?: (args: {
62
+ req: PayloadRequest;
63
+ }) => boolean | Promise<boolean>;
64
+ /**
65
+ * Collections of people (speakers, presenters) that each get a cloned VocalStack voice:
66
+ * made from a stretch of a recording they speak in, or from a sample, with their permission.
67
+ */
68
+ voices?: VoiceCollectionConfig[];
69
+ /**
70
+ * The VocalStack voice (`clone:<id>`, `F1`, …) a transcript's translations are spoken in
71
+ * by default, e.g. the cloned voice of the person speaking. Nothing: VocalStack's default.
72
+ */
73
+ speechVoice?: (args: {
74
+ collection: CollectionSlug;
75
+ doc: Record<string, unknown>;
76
+ req: PayloadRequest;
77
+ row?: ArrayRow;
78
+ }) => Promise<string | undefined> | string | undefined;
79
+ };
80
+ export type VoiceCollectionConfig = {
81
+ collection: CollectionSlug;
82
+ /** The voice's name in VocalStack. Default: the collection's `useAsTitle` field, else `name`. */
83
+ name?: (args: {
84
+ doc: Record<string, unknown>;
85
+ }) => string;
86
+ /** Transcribed recordings this person speaks in, offered as the sample to clone from. */
87
+ recordings?: (args: {
88
+ doc: Record<string, unknown>;
89
+ req: PayloadRequest;
90
+ }) => Promise<VoiceSource[]> | VoiceSource[];
91
+ };
92
+ /** A transcribed recording to take a voice sample from. */
93
+ export type VoiceSource = {
94
+ label: string;
95
+ recordingId: string;
96
+ sentences?: TranscriptSentence[];
97
+ };
98
+ export type VoiceState = 'failed' | 'none' | 'ready' | 'training';
99
+ /** The `vocalstackVoice` group on a voice collection's documents. */
100
+ export type VoiceFieldData = {
101
+ consentAt?: null | string;
102
+ createdAt?: null | string;
103
+ error?: null | string;
104
+ progress?: null | number;
105
+ sampleS?: null | number;
106
+ state?: null | VoiceState;
107
+ voiceId?: null | string;
108
+ };
109
+ export type Translation = {
110
+ /** The transcript's sentences (same ids and times), their text translated. */
111
+ sentences: TranscriptSentence[];
112
+ translatedAt: string;
113
+ };
114
+ export type SpeechState = 'failed' | 'queued' | 'running' | 'sealed';
115
+ export type Speech = {
116
+ durationS?: null | number;
117
+ error?: null | string;
118
+ renderedAt?: null | string;
119
+ requestedAt: string;
120
+ /** Once sealed: the translated sentences in the spoken track's timing, with their words. */
121
+ sentences?: null | TranscriptSentence[];
122
+ state: SpeechState;
123
+ /** The voice it is spoken in; `null` for VocalStack's default. */
124
+ voice: null | string;
125
+ /** Once sealed: the reading's MP3, saved once in the readings upload collection and served from there. */
126
+ audio?: null | {
127
+ filename?: null | string;
128
+ id: number | string;
129
+ url: string;
130
+ };
131
+ };
132
+ export type ArrayRow = Record<string, unknown> & {
133
+ id?: null | string;
134
+ vocalstack?: null | VocalStackFieldData;
135
+ };
136
+ export type AudioFieldConfig = {
137
+ collection: CollectionSlug;
138
+ /** An array field at the top level of the collection (or inside tabs, rows or collapsibles). */
139
+ field: string;
140
+ /** The row's audio address, or nothing when the row has no audio. Relative addresses resolve against the server URL. */
141
+ audioURL: (args: {
142
+ doc: Record<string, unknown>;
143
+ req: PayloadRequest;
144
+ row: ArrayRow;
145
+ }) => Promise<string | undefined> | string | undefined;
146
+ /** Show the button and transcript only on rows this accepts (admin condition). Default: every row. */
147
+ condition?: (row: ArrayRow) => boolean;
148
+ /** The transcription's name in VocalStack. Default: the document's title, else collection and id. */
149
+ name?: (args: {
150
+ doc: Record<string, unknown>;
151
+ row: ArrayRow;
152
+ }) => string;
153
+ };
154
+ export type UploadDoc = TypeWithID & {
155
+ filename?: null | string;
156
+ mimeType?: null | string;
157
+ url?: null | string;
158
+ vocalstack?: null | VocalStackFieldData;
159
+ };
160
+ export type TranscriptStatus = 'done' | 'failed' | 'idle' | 'processing';
161
+ export type VocalStackFieldData = {
162
+ error?: null | string;
163
+ language?: null | string;
164
+ recordingId?: null | string;
165
+ sentences?: null | TranscriptSentence[];
166
+ status?: null | TranscriptStatus;
167
+ transcript?: null | string;
168
+ transcriptionId?: null | string;
169
+ transcribedAt?: null | string;
170
+ /** By language code. */
171
+ translations?: null | Record<string, Translation>;
172
+ /** Spoken translations, by language code. */
173
+ speech?: null | Record<string, Speech>;
174
+ };
175
+ /** [start, end, text], seconds. */
176
+ export type TranscriptWord = [number, number, string];
177
+ export type TranscriptSentence = {
178
+ /** Live only: words heard after the last settled sentence. */
179
+ draft?: boolean;
180
+ end: number;
181
+ /** VocalStack's sentenceId. */
182
+ id?: number;
183
+ speaker: number;
184
+ start: number;
185
+ text: string;
186
+ words?: TranscriptWord[];
187
+ };
188
+ /** What the status endpoint answers, and what the Transcribe button renders. */
189
+ export type StatusResponse = {
190
+ /** Seconds of audio transcribed so far, and in all (while transcribing). */
191
+ audio?: {
192
+ processedS: number;
193
+ totalS?: number;
194
+ };
195
+ error?: string;
196
+ /** The sentences so far, while the job runs (the polling fallback). */
197
+ partial?: TranscriptSentence[];
198
+ phase?: string;
199
+ progress?: number;
200
+ status: TranscriptStatus;
201
+ /** The job was stopped before it finished; the field is back to how it was before. */
202
+ stopped?: boolean;
203
+ vocalstack?: VocalStackFieldData;
204
+ };
205
+ export type ConnectionResponse = {
206
+ account?: string;
207
+ connected: boolean;
208
+ /** `options`: the key is in the plugin config; `admin`: connected from the admin panel. */
209
+ source?: 'admin' | 'options';
210
+ };
211
+ /** What the translate and speak endpoints answer. */
212
+ export type SpeechResponse = {
213
+ /** The voice readings use unless one is picked (`speechVoice`); `null`: VocalStack's default. */
214
+ defaultVoice?: null | string;
215
+ /** The translate endpoint ran out of time; call it again to carry on. */
216
+ more?: boolean;
217
+ vocalstack: VocalStackFieldData;
218
+ };
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@vocalstack/payload",
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 Payload CMS: a Transcribe button on every audio upload.",
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
+ "./client": {
15
+ "types": "./dist/exports/client.d.ts",
16
+ "default": "./dist/exports/client.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "scripts": {
23
+ "build": "tsc -p tsconfig.json",
24
+ "typecheck": "tsc -p tsconfig.json --noEmit"
25
+ },
26
+ "peerDependencies": {
27
+ "@payloadcms/ui": "^3.0.0",
28
+ "next": ">=15",
29
+ "payload": "^3.0.0",
30
+ "react": "^19.0.0"
31
+ },
32
+ "devDependencies": {
33
+ "@payloadcms/ui": "3.80.0",
34
+ "@types/node": "^22.0.0",
35
+ "@types/react": "^19.0.0",
36
+ "next": "16.2.1",
37
+ "payload": "3.80.0",
38
+ "react": "19.2.4",
39
+ "react-dom": "19.2.4",
40
+ "typescript": "^5.6.0"
41
+ },
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git+ssh://git@github.com/vocalstack/payload-plugin.git"
45
+ },
46
+ "engines": {
47
+ "node": ">=20"
48
+ }
49
+ }