@skaile/forge-editor-audio 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/CHANGELOG.md ADDED
@@ -0,0 +1,22 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - ddf407c: First public release on npm: `bun add @skaile/forge-editor-audio`. The root entry is browser-safe (`audioFeature` with the derive methods `audio-tts` and `audio-mixdown`, the Derivation helpers, `takesOf`); `/server` holds `createElevenLabsSpeech`, the ffmpeg `mixdown` and the render target `audio-mixdown`.
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [3fc947a]
12
+ - Updated dependencies [311d04d]
13
+ - Updated dependencies [c5367de]
14
+ - @skaile/forge-editor@8.6.0
15
+
16
+ ## Unreleased
17
+
18
+ - Entries: the root entry is browser-safe (`audioFeature`, the Derivation helpers, `takesOf`); `@skaile/forge-editor-audio/server` holds `createElevenLabsSpeech`, `audioMixdownTarget` and the ffmpeg `mixdown` (`node:child_process`). The `/feature` subpath is gone. Every mixdown input carries `-format_whitelist` (audio and video containers) and `-protocol_whitelist file`, so an uploaded HLS playlist, concat script or DASH manifest is refused.
19
+
20
+ ### Added
21
+
22
+ - First release. `createElevenLabsSpeech({ apiKey, endpoint?, modelId?, voiceSettings? })`: the library's `SpeechProvider` over ElevenLabs (the account's voices as one engine, `POST /v1/text-to-speech/{voice_id}`, MP3 or WAV). `audioMixdownTarget({ assets })`: the render target `audio-mixdown` (`audio/mpeg`) that mixes the `recording` takes of a container or a Document through `ffmpeg` on the `PATH` (`concat` or `overlay`; error codes `ffmpeg-missing`, `ffmpeg-failed`, `too-few-takes`, `take-missing`, `foreign-take`). `audioFeature(options?)`: the derive methods `audio-tts` (a text block read aloud into a `recording` block, Derivation `method: 'tts'` with the inputs `text` and `voice`) and `audio-mixdown` (N recordings into one, Derivation `method: 'mixdown'` with the inputs `take-1` … `take-n`), so a changed take marks the mixdown stale. German and English messages in the add-on's own tables (`audioTranslator`).
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Matthias Ortegro
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # @skaile/forge-editor-audio
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Audio for [`@skaile/forge-editor`](../editor): an ElevenLabs speech provider, two derive methods that make `recording` blocks (**read aloud** and **mixdown**), and the render target `audio-mixdown`.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ bun add @skaile/forge-editor-audio
9
+ ```
10
+
11
+ Peer dependencies: `@skaile/forge-editor`, `@tiptap/core` and `@tiptap/pm`. The mixdown (`audioMixdownTarget`, `mixdown`) needs `ffmpeg` on the server's `PATH`.
12
+
13
+ ## Usage
14
+
15
+ | Piece | What it does |
16
+ |---|---|
17
+ | `createElevenLabsSpeech({ apiKey, endpoint? })` | the library's `SpeechProvider` over ElevenLabs: the account's voices as one engine, synthesis through the text-to-speech endpoint (server side) |
18
+ | `audioMixdownTarget({ assets })` | render target `audio-mixdown` (`audio/mpeg`): the takes of a container or a Document, mixed by `ffmpeg` on the `PATH` (error code `ffmpeg-missing` without it) |
19
+ | `audioFeature(options?)` | derive methods `audio-tts` (text block → `recording`, Derivation `method: 'tts'`, inputs `text` and `voice`) and `audio-mixdown` (N `recording` blocks → one, inputs `take-1` … `take-n`) |
20
+
21
+ ```ts
22
+ // server: installEditorServer({ ports: { speech, render, assets } })
23
+ import { createRenderer, markdownTarget } from '@skaile/forge-editor/adapters/render'
24
+ import { audioMixdownTarget, createElevenLabsSpeech } from '@skaile/forge-editor-audio/server'
25
+
26
+ const speech = createElevenLabsSpeech({ apiKey: process.env.ELEVENLABS_API_KEY! })
27
+ const render = createRenderer([markdownTarget(), audioMixdownTarget({ assets })])
28
+
29
+ // client: add the feature after the composites feature (the root entry is browser-safe; `/server` holds the Node-only mixdown, target and ElevenLabs)
30
+ import { audioFeature } from '@skaile/forge-editor-audio'
31
+ const feature = audioFeature({ mixdownMode: 'concat' })
32
+ ```
33
+
34
+ Both recordings record a Derivation with named inputs, so the library marks a mixdown **veraltet** as soon as the hash of one take changes. Pure pieces for your own pipeline: `ttsDerivation`, `mixdownDerivation`, `recordingJSON`, `takesOf` (root entry) and `mixdown`, `mixdownArgs` (`/server`). Mixdown inputs are user uploads: every one gets an ffmpeg `-format_whitelist` of audio and video containers and `-protocol_whitelist file`, so a playlist (HLS, concat, DASH) is refused instead of followed.
35
+
36
+ Guide: `apps/editor-docs/content/3.guides/46.audio.md` ([Audio: read aloud, mixdown and ElevenLabs](https://skaile-ai.github.io/forge/editor/guides/audio)).
@@ -0,0 +1,67 @@
1
+ import { Take } from "./takes.js";
2
+ import { Derivation, DerivationSource } from "@skaile/forge-editor/core";
3
+ import { Node } from "@tiptap/pm/model";
4
+ import { JSONContent } from "@tiptap/core";
5
+ /** The `Derivation.method` of a recording made from a text block by speech synthesis. */
6
+ export declare const TTS_METHOD = "tts";
7
+ /** The input names of a mixdown: `take-1` … `take-n`, in the order the takes are mixed. */
8
+ export declare const takeName: (index: number) => string;
9
+ /**
10
+ * The text a Typed block is read aloud with: its body (everything after title, description and tags) as plain text, the text of
11
+ * each body block as one paragraph. Empty when the body holds no text.
12
+ */
13
+ export declare function spokenTextOf(block: Node): string;
14
+ /**
15
+ * The `voice` input of a speech Derivation. A voice is no block and no file, so its `from` is the pseudo-asset
16
+ * `voice:<engine>/<voice>`; no block holds an asset of that name, so the library reads its live hash as unknown (never as changed).
17
+ * Its hash still enters the fingerprint: another voice makes another `inputHash`.
18
+ */
19
+ export declare function voiceInputOf(engine: string, voice: string): {
20
+ from: DerivationSource;
21
+ hash: string;
22
+ };
23
+ export interface TtsDerivationInput {
24
+ /** Block id of the text block that was read. */
25
+ sourceId: string;
26
+ /** SHA-256 of the Markdown of the source's body (`sha256Hex(bodyMarkdown(editor, source))`): what the library compares a block input against. */
27
+ sourceHash: string;
28
+ engine: string;
29
+ voice: string;
30
+ /** ISO timestamp. */
31
+ createdAt: string;
32
+ /** Id of the run (the request that made the audio). */
33
+ activityId: string;
34
+ }
35
+ /** `meta.derivation` of a recording that was read aloud from a text block: `from` and the input `text` are that block, the input `voice` names engine and voice; the engine is the activity's agent. */
36
+ export declare function ttsDerivation(input: TtsDerivationInput): Derivation;
37
+ export interface MixdownDerivationInput {
38
+ /** The takes that were mixed, in mixing order (at least one). */
39
+ takes: readonly Take[];
40
+ /** ISO timestamp. */
41
+ createdAt: string;
42
+ /** Id of the run (the render request). */
43
+ activityId: string;
44
+ }
45
+ /**
46
+ * `meta.derivation` of a recording that mixes several takes: one input `take-1` … `take-n` per take, each the take's audio asset
47
+ * with the hash of its bytes (`''` when the media block recorded none, which the library reads as unknown); `from` is the first take.
48
+ * When a take's audio changes, `derivationState` with an `inputHashOf` that reads the live hash reports the mixdown as stale.
49
+ */
50
+ export declare function mixdownDerivation(input: MixdownDerivationInput): Derivation;
51
+ export interface RecordingInput {
52
+ /** Block id of the new recording. */
53
+ id: string;
54
+ /** The title row of the recording. */
55
+ title: string;
56
+ documentId: string;
57
+ /** Name of the stored asset that holds the audio. */
58
+ asset: string;
59
+ fileName: string;
60
+ mime: string;
61
+ /** SHA-256 of the audio bytes; `null` when it could not be read. */
62
+ hash: string | null;
63
+ /** The Derivation of a recording the add-on made; absent for a plain recording (an uploaded take). */
64
+ derivation?: Derivation;
65
+ }
66
+ /** JSON of a `recording` Typed block whose source is the stored audio `asset`, with `derivation` (when there is one) in its meta. */
67
+ export declare function recordingJSON(input: RecordingInput): JSONContent;
package/dist/derive.js ADDED
@@ -0,0 +1,124 @@
1
+ import { MIXDOWN_METHOD } from "./takes.js";
2
+ import { sha256 } from "@noble/hashes/sha2.js";
3
+ import { bytesToHex } from "@noble/hashes/utils.js";
4
+ import { COMPOSITE_CHROME_COUNT } from "@skaile/forge-editor/composites/schema";
5
+ import { DERIVATION_KEY, TYPED_BLOCK_TITLE, derivationFingerprint, newTypedBlockJSON, sha256Hex } from "@skaile/forge-editor/core";
6
+ import { assetUrl } from "@skaile/forge-editor/media/schema";
7
+ // src/derive.ts
8
+ /** The `Derivation.method` of a recording made from a text block by speech synthesis. */
9
+ const TTS_METHOD = "tts";
10
+ /** The input names of a mixdown: `take-1` … `take-n`, in the order the takes are mixed. */
11
+ const takeName = (index) => `take-${index + 1}`;
12
+ /** SHA-256 of `data`, as lowercase hex: the `hash` a media block keeps of its file. */
13
+ const hashOfBytes = (data) => bytesToHex(sha256(data));
14
+ /**
15
+ * The text a Typed block is read aloud with: its body (everything after title, description and tags) as plain text, the text of
16
+ * each body block as one paragraph. Empty when the body holds no text.
17
+ */
18
+ function spokenTextOf(block) {
19
+ const paragraphs = [];
20
+ block.forEach((child, _offset, index) => {
21
+ if (index < COMPOSITE_CHROME_COUNT) return;
22
+ const text = child.textContent.trim();
23
+ if (text) paragraphs.push(text);
24
+ });
25
+ return paragraphs.join("\n\n");
26
+ }
27
+ /**
28
+ * The `voice` input of a speech Derivation. A voice is no block and no file, so its `from` is the pseudo-asset
29
+ * `voice:<engine>/<voice>`; no block holds an asset of that name, so the library reads its live hash as unknown (never as changed).
30
+ * Its hash still enters the fingerprint: another voice makes another `inputHash`.
31
+ */
32
+ function voiceInputOf(engine, voice) {
33
+ return {
34
+ from: { asset: `voice:${engine}/${voice}` },
35
+ hash: sha256Hex(`${engine}\n${voice}`)
36
+ };
37
+ }
38
+ /** `meta.derivation` of a recording that was read aloud from a text block: `from` and the input `text` are that block, the input `voice` names engine and voice; the engine is the activity's agent. */
39
+ function ttsDerivation(input) {
40
+ const inputs = {
41
+ text: {
42
+ from: { block: input.sourceId },
43
+ hash: input.sourceHash
44
+ },
45
+ voice: voiceInputOf(input.engine, input.voice)
46
+ };
47
+ return {
48
+ from: { block: input.sourceId },
49
+ method: "tts",
50
+ model: `${input.engine}/${input.voice}`,
51
+ createdAt: input.createdAt,
52
+ inputHash: derivationFingerprint({
53
+ method: "tts",
54
+ inputs
55
+ }),
56
+ outputHash: "",
57
+ inputs,
58
+ activity: {
59
+ id: input.activityId,
60
+ agent: input.engine,
61
+ at: input.createdAt
62
+ }
63
+ };
64
+ }
65
+ /**
66
+ * `meta.derivation` of a recording that mixes several takes: one input `take-1` … `take-n` per take, each the take's audio asset
67
+ * with the hash of its bytes (`''` when the media block recorded none, which the library reads as unknown); `from` is the first take.
68
+ * When a take's audio changes, `derivationState` with an `inputHashOf` that reads the live hash reports the mixdown as stale.
69
+ */
70
+ function mixdownDerivation(input) {
71
+ const inputs = Object.fromEntries(input.takes.map((take, index) => [takeName(index), {
72
+ from: { asset: take.asset.name },
73
+ hash: take.hash ?? ""
74
+ }]));
75
+ const first = inputs[takeName(0)];
76
+ if (!first) throw new Error("mixdownDerivation: no takes");
77
+ return {
78
+ from: first.from,
79
+ method: MIXDOWN_METHOD,
80
+ createdAt: input.createdAt,
81
+ inputHash: derivationFingerprint({
82
+ method: MIXDOWN_METHOD,
83
+ inputs
84
+ }),
85
+ outputHash: "",
86
+ inputs,
87
+ activity: {
88
+ id: input.activityId,
89
+ at: input.createdAt
90
+ }
91
+ };
92
+ }
93
+ /** JSON of a `recording` Typed block whose source is the stored audio `asset`, with `derivation` (when there is one) in its meta. */
94
+ function recordingJSON(input) {
95
+ const json = newTypedBlockJSON("recording", [{
96
+ type: "audio",
97
+ attrs: {
98
+ src: assetUrl(input.documentId, input.asset),
99
+ title: input.fileName,
100
+ mimeType: input.mime,
101
+ hash: input.hash
102
+ }
103
+ }]);
104
+ const [titleRow, ...rest] = json.content ?? [];
105
+ if (titleRow?.type !== TYPED_BLOCK_TITLE) throw new Error("recordingJSON: a Typed block starts with its title");
106
+ return {
107
+ ...json,
108
+ attrs: {
109
+ ...json.attrs,
110
+ id: input.id,
111
+ meta: input.derivation ? { [DERIVATION_KEY]: input.derivation } : {}
112
+ },
113
+ content: [{
114
+ ...titleRow,
115
+ content: [{
116
+ type: "text",
117
+ text: input.title
118
+ }]
119
+ }, ...rest]
120
+ };
121
+ }
122
+ export { TTS_METHOD, hashOfBytes, mixdownDerivation, recordingJSON, spokenTextOf, takeName, ttsDerivation, voiceInputOf };
123
+
124
+ //# sourceMappingURL=derive.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"derive.js","names":[],"sources":["../src/derive.ts"],"sourcesContent":["import { sha256 } from '@noble/hashes/sha2.js'\nimport { bytesToHex } from '@noble/hashes/utils.js'\nimport { COMPOSITE_CHROME_COUNT } from '@skaile/forge-editor/composites/schema'\nimport {\n DERIVATION_KEY,\n type Derivation,\n type DerivationSource,\n derivationFingerprint,\n newTypedBlockJSON,\n sha256Hex,\n TYPED_BLOCK_TITLE,\n} from '@skaile/forge-editor/core'\nimport { assetUrl } from '@skaile/forge-editor/media/schema'\nimport type { JSONContent } from '@tiptap/core'\nimport type { Node as PMNode } from '@tiptap/pm/model'\nimport { MIXDOWN_METHOD, type Take } from './takes'\n\n// The two Derivations of the add-on, as plain data: what a recording made by `tts` or by `mixdown` records in `meta.derivation`.\n// Both are N-to-1 Derivations: they name their inputs (`Derivation.inputs`), so the library can tell when an input changed\n// (`derivationState` with `inputHashOf`). `inputHash` is `derivationFingerprint` of method and input hashes.\n\n/** The `Derivation.method` of a recording made from a text block by speech synthesis. */\nexport const TTS_METHOD = 'tts'\n\n/** The input names of a mixdown: `take-1` … `take-n`, in the order the takes are mixed. */\nexport const takeName = (index: number): string => `take-${index + 1}`\n\n/** SHA-256 of `data`, as lowercase hex: the `hash` a media block keeps of its file. */\nexport const hashOfBytes = (data: Uint8Array): string => bytesToHex(sha256(data))\n\n/**\n * The text a Typed block is read aloud with: its body (everything after title, description and tags) as plain text, the text of\n * each body block as one paragraph. Empty when the body holds no text.\n */\nexport function spokenTextOf(block: PMNode): string {\n const paragraphs: string[] = []\n block.forEach((child, _offset, index) => {\n if (index < COMPOSITE_CHROME_COUNT) return\n const text = child.textContent.trim()\n if (text) paragraphs.push(text)\n })\n return paragraphs.join('\\n\\n')\n}\n\n/**\n * The `voice` input of a speech Derivation. A voice is no block and no file, so its `from` is the pseudo-asset\n * `voice:<engine>/<voice>`; no block holds an asset of that name, so the library reads its live hash as unknown (never as changed).\n * Its hash still enters the fingerprint: another voice makes another `inputHash`.\n */\nexport function voiceInputOf(engine: string, voice: string): { from: DerivationSource; hash: string } {\n return { from: { asset: `voice:${engine}/${voice}` }, hash: sha256Hex(`${engine}\\n${voice}`) }\n}\n\nexport interface TtsDerivationInput {\n /** Block id of the text block that was read. */\n sourceId: string\n /** SHA-256 of the Markdown of the source's body (`sha256Hex(bodyMarkdown(editor, source))`): what the library compares a block input against. */\n sourceHash: string\n engine: string\n voice: string\n /** ISO timestamp. */\n createdAt: string\n /** Id of the run (the request that made the audio). */\n activityId: string\n}\n\n/** `meta.derivation` of a recording that was read aloud from a text block: `from` and the input `text` are that block, the input `voice` names engine and voice; the engine is the activity's agent. */\nexport function ttsDerivation(input: TtsDerivationInput): Derivation {\n const inputs: NonNullable<Derivation['inputs']> = {\n text: { from: { block: input.sourceId }, hash: input.sourceHash },\n voice: voiceInputOf(input.engine, input.voice),\n }\n return {\n from: { block: input.sourceId },\n method: TTS_METHOD,\n model: `${input.engine}/${input.voice}`,\n createdAt: input.createdAt,\n inputHash: derivationFingerprint({ method: TTS_METHOD, inputs }),\n outputHash: '',\n inputs,\n activity: { id: input.activityId, agent: input.engine, at: input.createdAt },\n }\n}\n\nexport interface MixdownDerivationInput {\n /** The takes that were mixed, in mixing order (at least one). */\n takes: readonly Take[]\n /** ISO timestamp. */\n createdAt: string\n /** Id of the run (the render request). */\n activityId: string\n}\n\n/**\n * `meta.derivation` of a recording that mixes several takes: one input `take-1` … `take-n` per take, each the take's audio asset\n * with the hash of its bytes (`''` when the media block recorded none, which the library reads as unknown); `from` is the first take.\n * When a take's audio changes, `derivationState` with an `inputHashOf` that reads the live hash reports the mixdown as stale.\n */\nexport function mixdownDerivation(input: MixdownDerivationInput): Derivation {\n const inputs: NonNullable<Derivation['inputs']> = Object.fromEntries(\n input.takes.map((take, index) => [takeName(index), { from: { asset: take.asset.name }, hash: take.hash ?? '' }]),\n )\n const first = inputs[takeName(0)]\n if (!first) throw new Error('mixdownDerivation: no takes')\n return {\n from: first.from,\n method: MIXDOWN_METHOD,\n createdAt: input.createdAt,\n inputHash: derivationFingerprint({ method: MIXDOWN_METHOD, inputs }),\n outputHash: '',\n inputs,\n activity: { id: input.activityId, at: input.createdAt },\n }\n}\n\nexport interface RecordingInput {\n /** Block id of the new recording. */\n id: string\n /** The title row of the recording. */\n title: string\n documentId: string\n /** Name of the stored asset that holds the audio. */\n asset: string\n fileName: string\n mime: string\n /** SHA-256 of the audio bytes; `null` when it could not be read. */\n hash: string | null\n /** The Derivation of a recording the add-on made; absent for a plain recording (an uploaded take). */\n derivation?: Derivation\n}\n\n/** JSON of a `recording` Typed block whose source is the stored audio `asset`, with `derivation` (when there is one) in its meta. */\nexport function recordingJSON(input: RecordingInput): JSONContent {\n const json = newTypedBlockJSON('recording', [\n {\n type: 'audio',\n attrs: {\n src: assetUrl(input.documentId, input.asset),\n title: input.fileName,\n mimeType: input.mime,\n hash: input.hash,\n },\n },\n ])\n const [titleRow, ...rest] = json.content ?? []\n if (titleRow?.type !== TYPED_BLOCK_TITLE) throw new Error('recordingJSON: a Typed block starts with its title')\n return {\n ...json,\n attrs: { ...json.attrs, id: input.id, meta: input.derivation ? { [DERIVATION_KEY]: input.derivation } : {} },\n content: [{ ...titleRow, content: [{ type: 'text', text: input.title }] }, ...rest],\n }\n}\n"],"mappings":";;;;;;;;AAsBA,MAAa,aAAa;;AAG1B,MAAa,YAAY,UAA0B,QAAQ,QAAQ;;AAGnE,MAAa,eAAe,SAA6B,WAAW,OAAO,IAAI,CAAC;;;;;AAMhF,SAAgB,aAAa,OAAuB;CAClD,MAAM,aAAuB,CAAC;CAC9B,MAAM,SAAS,OAAO,SAAS,UAAU;EACvC,IAAI,QAAQ,wBAAwB;EACpC,MAAM,OAAO,MAAM,YAAY,KAAK;EACpC,IAAI,MAAM,WAAW,KAAK,IAAI;CAChC,CAAC;CACD,OAAO,WAAW,KAAK,MAAM;AAC/B;;;;;;AAOA,SAAgB,aAAa,QAAgB,OAAyD;CACpG,OAAO;EAAE,MAAM,EAAE,OAAO,SAAS,OAAO,GAAG,QAAQ;EAAG,MAAM,UAAU,GAAG,OAAO,IAAI,OAAO;CAAE;AAC/F;;AAgBA,SAAgB,cAAc,OAAuC;CACnE,MAAM,SAA4C;EAChD,MAAM;GAAE,MAAM,EAAE,OAAO,MAAM,SAAS;GAAG,MAAM,MAAM;EAAW;EAChE,OAAO,aAAa,MAAM,QAAQ,MAAM,KAAK;CAC/C;CACA,OAAO;EACL,MAAM,EAAE,OAAO,MAAM,SAAS;EAC9B,QAAA;EACA,OAAO,GAAG,MAAM,OAAO,GAAG,MAAM;EAChC,WAAW,MAAM;EACjB,WAAW,sBAAsB;GAAE,QAAA;GAAoB;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Provider } from "@skaile/forge-editor/server";
2
+ export interface ElevenLabsSpeechOptions {
3
+ /** Sent as `xi-api-key`. */
4
+ apiKey: string;
5
+ /** Base URL (default `https://api.elevenlabs.io`); the regional hosts (`https://api.eu.residency.elevenlabs.io`) go here. */
6
+ endpoint?: string;
7
+ /** The speech model (`model_id`; default `eleven_multilingual_v2`). */
8
+ modelId?: string;
9
+ /** The engine's id in `engines()` (default `elevenlabs`). */
10
+ id?: string;
11
+ /** The engine's label (default `ElevenLabs`). */
12
+ label?: string;
13
+ /** `voice_settings` of every synthesis (`stability`, `similarity_boost`, `style`, `speed`, `use_speaker_boost`); absent: the voice's stored settings. */
14
+ voiceSettings?: Readonly<Record<string, number | boolean>>;
15
+ /** How long the list of voices is kept, in ms (default five minutes). */
16
+ voiceCacheMs?: number;
17
+ /** The `fetch` the calls go through (default: the platform's). */
18
+ fetch?: typeof fetch;
19
+ /** The clock of the voice cache (default `Date.now`). */
20
+ now?: () => number;
21
+ }
22
+ /** A `SpeechProvider` with one engine that lists the account's voices and synthesizes through the ElevenLabs text-to-speech endpoint. */
23
+ export declare function createElevenLabsSpeech(options: ElevenLabsSpeechOptions): SpeechProvider;
@@ -0,0 +1,144 @@
1
+ import { HttpError } from "@skaile/forge-editor/server";
2
+ // src/elevenlabs.ts
3
+ /** The most characters of an upstream error body that go into the error message. */
4
+ const MAX_ERROR_DETAIL = 300;
5
+ /** The largest page the voices endpoint answers. */
6
+ const VOICES_PAGE_SIZE = 100;
7
+ /** The most pages of voices that are read (`VOICES_PAGE_SIZE` each), so an account with an endless list cannot stall `engines()`. */
8
+ const MAX_VOICE_PAGES = 10;
9
+ /** How long the voice list is kept before it is read again (ms). */
10
+ const DEFAULT_VOICE_CACHE_MS = 3e5;
11
+ /** The output format each `SpeechFormat` is requested as (`output_format` of the endpoint). WAV at 44.1 kHz needs a paid tier, so the 24 kHz one is used. */
12
+ const OUTPUT_FORMAT = {
13
+ mp3: "mp3_44100_128",
14
+ wav: "wav_24000"
15
+ };
16
+ /** The MIME type a format has when the endpoint names none. */
17
+ const MIME = {
18
+ mp3: "audio/mpeg",
19
+ wav: "audio/wav"
20
+ };
21
+ /** The BCP 47 tag of a voice: the locale of its first verified language, else that language, else its `language` label, else `und` (undetermined). */
22
+ function langOf(voice) {
23
+ const verified = voice.verified_languages?.[0];
24
+ return verified?.locale || verified?.language || voice.labels?.language || "und";
25
+ }
26
+ /** The text of the `message` or `msg` member of `value` when it is a string; else the empty string. */
27
+ function messageOf(value) {
28
+ if (!value || typeof value !== "object") return "";
29
+ if ("message" in value && typeof value.message === "string") return value.message;
30
+ if ("msg" in value && typeof value.msg === "string") return value.msg;
31
+ return "";
32
+ }
33
+ /** The readable part of an ElevenLabs error body: `detail.message`, a string `detail`, the validation messages, else the text itself. */
34
+ function errorDetailOf(text) {
35
+ let body;
36
+ try {
37
+ body = JSON.parse(text);
38
+ } catch {
39
+ return text;
40
+ }
41
+ const detail = body && typeof body === "object" && "detail" in body ? body.detail : void 0;
42
+ if (typeof detail === "string") return detail;
43
+ if (Array.isArray(detail)) return detail.map(messageOf).filter(Boolean).join("; ") || text;
44
+ return messageOf(detail) || text;
45
+ }
46
+ /** A `SpeechProvider` with one engine that lists the account's voices and synthesizes through the ElevenLabs text-to-speech endpoint. */
47
+ function createElevenLabsSpeech(options) {
48
+ const send = options.fetch ?? fetch;
49
+ const base = (options.endpoint ?? "https://api.elevenlabs.io").replace(/\/+$/, "");
50
+ const engineId = options.id ?? "elevenlabs";
51
+ const label = options.label ?? "ElevenLabs";
52
+ const modelId = options.modelId ?? "eleven_multilingual_v2";
53
+ const cacheMs = options.voiceCacheMs ?? DEFAULT_VOICE_CACHE_MS;
54
+ const now = options.now ?? Date.now;
55
+ let cached = null;
56
+ /** One call to ElevenLabs: network failures and error statuses become `Error`s with the upstream's own words; an abort stays an abort. */
57
+ async function call(url, init, signal) {
58
+ let response;
59
+ try {
60
+ response = await send(url, {
61
+ ...init,
62
+ headers: {
63
+ "xi-api-key": options.apiKey,
64
+ ...init.headers
65
+ },
66
+ ...signal && { signal }
67
+ });
68
+ } catch (error) {
69
+ if (signal?.aborted) throw error;
70
+ throw new Error(`ElevenLabs nicht erreichbar: ${error instanceof Error ? error.message : String(error)}`.slice(0, 500), { cause: error });
71
+ }
72
+ if (!response.ok) {
73
+ const detail = errorDetailOf(await response.text().catch(() => "")).slice(0, MAX_ERROR_DETAIL);
74
+ throw new Error(`ElevenLabs: ${[response.status, detail || response.statusText].filter(Boolean).join(" ")}`);
75
+ }
76
+ return response;
77
+ }
78
+ async function loadVoices(signal) {
79
+ const voices = [];
80
+ let token = null;
81
+ for (let page = 0; page < MAX_VOICE_PAGES; page++) {
82
+ const url = new URL(`${base}/v2/voices`);
83
+ url.searchParams.set("page_size", String(VOICES_PAGE_SIZE));
84
+ url.searchParams.set("include_total_count", "false");
85
+ if (token) url.searchParams.set("next_page_token", token);
86
+ const body = await (await call(url.toString(), {
87
+ method: "GET",
88
+ headers: { Accept: "application/json" }
89
+ }, signal)).json();
90
+ for (const voice of body.voices ?? []) if (voice.voice_id) voices.push({
91
+ id: voice.voice_id,
92
+ label: voice.name || voice.voice_id,
93
+ lang: langOf(voice)
94
+ });
95
+ if (!body.has_more || !body.next_page_token) break;
96
+ token = body.next_page_token;
97
+ }
98
+ return voices;
99
+ }
100
+ async function voicesOf(signal) {
101
+ if (cached && now() - cached.at < cacheMs) return cached.voices;
102
+ const voices = await loadVoices(signal);
103
+ cached = {
104
+ at: now(),
105
+ voices
106
+ };
107
+ return voices;
108
+ }
109
+ const copyOf = (voices) => voices.map((voice) => ({ ...voice }));
110
+ return {
111
+ async engines() {
112
+ return [{
113
+ id: engineId,
114
+ label,
115
+ voices: copyOf(await voicesOf())
116
+ }];
117
+ },
118
+ async synthesize({ engine, voice, text, format }, _user, signal) {
119
+ if (engine !== engineId) throw new HttpError(404, `Sprach-Engine „${engine}“ ist unbekannt`);
120
+ if (!(await voicesOf(signal)).some((known) => known.id === voice)) throw new HttpError(404, `Stimme „${voice}“ ist bei „${label}“ unbekannt`);
121
+ const response = await call(`${base}/v1/text-to-speech/${encodeURIComponent(voice)}?output_format=${OUTPUT_FORMAT[format]}`, {
122
+ method: "POST",
123
+ headers: {
124
+ "Content-Type": "application/json",
125
+ Accept: MIME[format]
126
+ },
127
+ body: JSON.stringify({
128
+ text,
129
+ model_id: modelId,
130
+ ...options.voiceSettings && { voice_settings: options.voiceSettings }
131
+ })
132
+ }, signal);
133
+ const data = new Uint8Array(await response.arrayBuffer());
134
+ if (!data.byteLength) throw new Error("ElevenLabs: leere Antwort");
135
+ return {
136
+ data,
137
+ mime: response.headers.get("content-type")?.split(";")[0]?.trim() || MIME[format]
138
+ };
139
+ }
140
+ };
141
+ }
142
+ export { createElevenLabsSpeech };
143
+
144
+ //# sourceMappingURL=elevenlabs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"elevenlabs.js","names":[],"sources":["../src/elevenlabs.ts"],"sourcesContent":["import { HttpError, type SpeechProvider } from '@skaile/forge-editor/server'\nimport type { SpeechEngineInfo, SpeechFormat, SpeechVoice } from './types'\n\n// The speech port over ElevenLabs. The calls go from the server, so the key never reaches a page. The engine's voices are the\n// voices of the account (`GET /v2/voices`: the premade ones, the cloned ones and the ones the account added from the library);\n// a synthesis is `POST /v1/text-to-speech/{voice_id}`. `transcribe` is left out: the text-to-speech endpoint makes audio only.\n\n/** The most characters of an upstream error body that go into the error message. */\nconst MAX_ERROR_DETAIL = 300\n/** The largest page the voices endpoint answers. */\nconst VOICES_PAGE_SIZE = 100\n/** The most pages of voices that are read (`VOICES_PAGE_SIZE` each), so an account with an endless list cannot stall `engines()`. */\nconst MAX_VOICE_PAGES = 10\n/** How long the voice list is kept before it is read again (ms). */\nconst DEFAULT_VOICE_CACHE_MS = 5 * 60_000\n\n/** The output format each `SpeechFormat` is requested as (`output_format` of the endpoint). WAV at 44.1 kHz needs a paid tier, so the 24 kHz one is used. */\nconst OUTPUT_FORMAT: Record<SpeechFormat, string> = { mp3: 'mp3_44100_128', wav: 'wav_24000' }\n/** The MIME type a format has when the endpoint names none. */\nconst MIME: Record<SpeechFormat, string> = { mp3: 'audio/mpeg', wav: 'audio/wav' }\n\nexport interface ElevenLabsSpeechOptions {\n /** Sent as `xi-api-key`. */\n apiKey: string\n /** Base URL (default `https://api.elevenlabs.io`); the regional hosts (`https://api.eu.residency.elevenlabs.io`) go here. */\n endpoint?: string\n /** The speech model (`model_id`; default `eleven_multilingual_v2`). */\n modelId?: string\n /** The engine's id in `engines()` (default `elevenlabs`). */\n id?: string\n /** The engine's label (default `ElevenLabs`). */\n label?: string\n /** `voice_settings` of every synthesis (`stability`, `similarity_boost`, `style`, `speed`, `use_speaker_boost`); absent: the voice's stored settings. */\n voiceSettings?: Readonly<Record<string, number | boolean>>\n /** How long the list of voices is kept, in ms (default five minutes). */\n voiceCacheMs?: number\n /** The `fetch` the calls go through (default: the platform's). */\n fetch?: typeof fetch\n /** The clock of the voice cache (default `Date.now`). */\n now?: () => number\n}\n\n/** The part of `VoiceResponseModel` the add-on reads. */\ninterface ElevenLabsVoice {\n voice_id?: string\n name?: string\n labels?: Record<string, string>\n verified_languages?: { language?: string; locale?: string | null }[] | null\n}\n\ninterface ElevenLabsVoicesPage {\n voices?: ElevenLabsVoice[]\n has_more?: boolean\n next_page_token?: string | null\n}\n\n/** The BCP 47 tag of a voice: the locale of its first verified language, else that language, else its `language` label, else `und` (undetermined). */\nfunction langOf(voice: ElevenLabsVoice): string {\n const verified = voice.verified_languages?.[0]\n return verified?.locale || verified?.language || voice.labels?.language || 'und'\n}\n\n/** The text of the `message` or `msg` member of `value` when it is a string; else the empty string. */\nfunction messageOf(value: unknown): string {\n if (!value || typeof value !== 'object') return ''\n if ('message' in value && typeof value.message === 'string') return value.message\n if ('msg' in value && typeof value.msg === 'string') return value.msg\n return ''\n}\n\n/** The readable part of an ElevenLabs error body: `detail.message`, a string `detail`, the validation messages, else the text itself. */\nfunction errorDetailOf(text: string): string {\n let body: unknown\n try {\n body = JSON.parse(text)\n } catch {\n return text\n }\n const detail = body && typeof body === 'object' && 'detail' in body ? body.detail : undefined\n if (typeof detail === 'string') return detail\n if (Array.isArray(detail)) return detail.map(messageOf).filter(Boolean).join('; ') || text\n return messageOf(detail) || text\n}\n\n/** A `SpeechProvider` with one engine that lists the account's voices and synthesizes through the ElevenLabs text-to-speech endpoint. */\nexport function createElevenLabsSpeech(options: ElevenLabsSpeechOptions): SpeechProvider {\n const send = options.fetch ?? fetch\n const base = (options.endpoint ?? 'https://api.elevenlabs.io').replace(/\\/+$/, '')\n const engineId = options.id ?? 'elevenlabs'\n const label = options.label ?? 'ElevenLabs'\n const modelId = options.modelId ?? 'eleven_multilingual_v2'\n const cacheMs = options.voiceCacheMs ?? DEFAULT_VOICE_CACHE_MS\n const now = options.now ?? Date.now\n let cached: { at: number; voices: SpeechVoice[] } | null = null\n\n /** One call to ElevenLabs: network failures and error statuses become `Error`s with the upstream's own words; an abort stays an abort. */\n async function call(\n url: string,\n init: { method: 'GET' | 'POST'; headers: Record<string, string>; body?: string },\n signal?: AbortSignal,\n ): Promise<Response> {\n let response: Response\n try {\n response = await send(url, {\n ...init,\n headers: { 'xi-api-key': options.apiKey, ...init.headers },\n ...(signal && { signal }),\n })\n } catch (error) {\n if (signal?.aborted) throw error\n throw new Error(\n `ElevenLabs nicht erreichbar: ${error instanceof Error ? error.message : String(error)}`.slice(0, 500),\n { cause: error },\n )\n }\n if (!response.ok) {\n const detail = errorDetailOf(await response.text().catch(() => '')).slice(0, MAX_ERROR_DETAIL)\n throw new Error(`ElevenLabs: ${[response.status, detail || response.statusText].filter(Boolean).join(' ')}`)\n }\n return response\n }\n\n async function loadVoices(signal?: AbortSignal): Promise<SpeechVoice[]> {\n const voices: SpeechVoice[] = []\n let token: string | null = null\n for (let page = 0; page < MAX_VOICE_PAGES; page++) {\n const url = new URL(`${base}/v2/voices`)\n url.searchParams.set('page_size', String(VOICES_PAGE_SIZE))\n url.searchParams.set('include_total_count', 'false')\n if (token) url.searchParams.set('next_page_token', token)\n const body = (await (\n await call(url.toString(), { method: 'GET', headers: { Accept: 'application/json' } }, signal)\n ).json()) as ElevenLabsVoicesPage\n for (const voice of body.voices ?? []) {\n if (voice.voice_id)\n voices.push({ id: voice.voice_id, label: voice.name || voice.voice_id, lang: langOf(voice) })\n }\n if (!body.has_more || !body.next_page_token) break\n token = body.next_page_token\n }\n return voices\n }\n\n async function voicesOf(signal?: AbortSignal): Promise<SpeechVoice[]> {\n if (cached && now() - cached.at < cacheMs) return cached.voices\n const voices = await loadVoices(signal)\n cached = { at: now(), voices }\n return voices\n }\n\n const copyOf = (voices: readonly SpeechVoice[]): SpeechVoice[] => voices.map(voice => ({ ...voice }))\n\n return {\n async engines(): Promise<SpeechEngineInfo[]> {\n return [{ id: engineId, label, voices: copyOf(await voicesOf()) }]\n },\n async synthesize({ engine, voice, text, format }, _user, signal) {\n if (engine !== engineId) throw new HttpError(404, `Sprach-Engine „${engine}“ ist unbekannt`)\n if (!(await voicesOf(signal)).some(known => known.id === voice))\n throw new HttpError(404, `Stimme „${voice}“ ist bei „${label}“ unbekannt`)\n const url = `${base}/v1/text-to-speech/${encodeURIComponent(voice)}?output_format=${OUTPUT_FORMAT[format]}`\n const response = await call(\n url,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Accept: MIME[format] },\n body: JSON.stringify({\n text,\n model_id: modelId,\n ...(options.voiceSettings && { voice_settings: options.voiceSettings }),\n }),\n },\n signal,\n )\n const data = new Uint8Array(await response.arrayBuffer())\n if (!data.byteLength) throw new Error('ElevenLabs: leere Antwort')\n return { data, mime: response.headers.get('content-type')?.split(';')[0]?.trim() || MIME[format] }\n },\n }\n}\n"],"mappings":";;;AAQA,MAAM,mBAAmB;;AAEzB,MAAM,mBAAmB;;AAEzB,MAAM,kBAAkB;;AAExB,MAAM,yBAAyB;;AAG/B,MAAM,gBAA8C;CAAE,KAAK;CAAiB,KAAK;AAAY;;AAE7F,MAAM,OAAqC;CAAE,KAAK;CAAc,KAAK;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SAAS,OAAO,OAAO;EACzD,MAAM,SAAS,MAAM,WAAW,MAAM;EACtC,SAAS;GAAE,IAAI,IAAI;GAAG;EAAO;EAC7B,OAAO;CACT;CAEA,MAAM,UAAU,WAAkD,OAAO,KAAI,WAAU,EAAE,GAAG,MAAM,EAAE;CAEpG,OAAO;EACL,MAAM,UAAuC;GAC3C,OAAO,CAAC;IAAE,IAAI;IAAU;IAAO,QAAQ,OAAO,MAAM,SAAS,CAAC;GAAE,CAAC;EACnE;EACA,MAAM,WAAW,EAAE,QAAQ,OAAO,MAAM,UAAU,OAAO,QAAQ;GAC/D,IAAI,WAAW,UAAU,MAAM,IAAI,UAAU,KAAK,kBAAkB,OAAO,gBAAgB;GAC3F,IAAI,EAAE,MAAM,SAAS,MAAM,EAAA,CAAG,MAAK,UAAS,MAAM,OAAO,KAAK,GAC5D,MAAM,IAAI,UAAU,KAAK,WAAW,MAAM,aAAa,MAAM,YAAY;GAE3E,MAAM,WAAW,MAAM,KACrB,GAFa,KAAK,qBAAqB,mBAAmB,KAAK,EAAE,iBAAiB,cAAc,WAGhG;IACE,QAAQ;IACR,SAAS;KAAE,gBAAgB;KAAoB,QAAQ,KAAK;IAAQ;IACpE,MAAM,KAAK,UAAU;KACnB;KACA,UAAU;KACV,GAAI,QAAQ,iBAAiB,EAAE,gBAAgB,QAAQ,cAAc;IACvE,CAAC;GACH,GACA,MACF;GACA,MAAM,OAAO,IAAI,WAAW,MAAM,SAAS,YAAY,CAAC;GACxD,IAAI,CAAC,KAAK,YAAY,MAAM,IAAI,MAAM,2BAA2B;GACjE,OAAO;IAAE;IAAM,MAAM,SAAS,QAAQ,IAAI,cAAc,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,EAAE,EAAE,KAAK,KAAK,KAAK;GAAQ;EACnG;CACF;AACF"}
@@ -0,0 +1,9 @@
1
+ /** What went wrong in the audio add-on; `AudioError.code` tells the cases apart where the message (German, like the library's server messages) does not. */
2
+ export type AudioErrorCode = 'ffmpeg-missing' | 'ffmpeg-failed' | 'too-few-takes' | 'take-missing' | 'foreign-take' | 'no-voice';
3
+ /** An error of the audio add-on with a machine-readable `code`. */
4
+ export declare class AudioError extends Error {
5
+ readonly code: AudioErrorCode;
6
+ constructor(code: AudioErrorCode, message: string, options?: {
7
+ cause?: unknown;
8
+ });
9
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,13 @@
1
+ // src/errors.ts
2
+ /** An error of the audio add-on with a machine-readable `code`. */
3
+ var AudioError = class extends Error {
4
+ code;
5
+ constructor(code, message, options) {
6
+ super(message, options);
7
+ this.name = "AudioError";
8
+ this.code = code;
9
+ }
10
+ };
11
+ export { AudioError };
12
+
13
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/** What went wrong in the audio add-on; `AudioError.code` tells the cases apart where the message (German, like the library's server messages) does not. */\nexport type AudioErrorCode =\n | 'ffmpeg-missing' // no `ffmpeg` binary on the PATH of the server\n | 'ffmpeg-failed' // ffmpeg ran and exited with an error\n | 'too-few-takes' // a mixdown needs at least two recordings\n | 'take-missing' // a recording's audio is not in the asset store\n | 'foreign-take' // a recording's audio belongs to another Document than the one being rendered\n | 'no-voice' // the speech provider offers no voice to speak with\n\n/** An error of the audio add-on with a machine-readable `code`. */\nexport class AudioError extends Error {\n readonly code: AudioErrorCode\n\n constructor(code: AudioErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options)\n this.name = 'AudioError'\n this.code = code\n }\n}\n"],"mappings":";;AAUA,IAAa,aAAb,cAAgC,MAAM;CACpC;CAEA,YAAY,MAAsB,SAAiB,SAA+B;EAChF,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF"}
@@ -0,0 +1,11 @@
1
+ import { AudioMethodOptions } from "./methods.js";
2
+ import { EditorFeature } from "@skaile/forge-editor/core";
3
+ /** Options of `audioFeature`: those of the derive methods. */
4
+ export type AudioFeatureOptions = AudioMethodOptions;
5
+ /**
6
+ * The audio Feature: the derive methods `audio-tts` (a text block read aloud into a `recording` block) and `audio-mixdown` (the
7
+ * takes of a container mixed into one `recording`). Both are block actions on the Typed blocks they apply to; `audio-tts`
8
+ * needs the host's speech provider (`createElevenLabsSpeech`, `createOpenAiSpeech`), `audio-mixdown` the `audio-mixdown` render
9
+ * target (`audioMixdownTarget`). The Feature installs after `composites`.
10
+ */
11
+ export declare function audioFeature(options?: AudioFeatureOptions): EditorFeature<never>;
@@ -0,0 +1,19 @@
1
+ import { audioDeriveMethods } from "./methods.js";
2
+ // src/feature.ts
3
+ /**
4
+ * The audio Feature: the derive methods `audio-tts` (a text block read aloud into a `recording` block) and `audio-mixdown` (the
5
+ * takes of a container mixed into one `recording`). Both are block actions on the Typed blocks they apply to; `audio-tts`
6
+ * needs the host's speech provider (`createElevenLabsSpeech`, `createOpenAiSpeech`), `audio-mixdown` the `audio-mixdown` render
7
+ * target (`audioMixdownTarget`). The Feature installs after `composites`.
8
+ */
9
+ function audioFeature(options = {}) {
10
+ return {
11
+ id: "audio",
12
+ dimension: "interaction",
13
+ requires: ["composites"],
14
+ deriveMethods: audioDeriveMethods(options)
15
+ };
16
+ }
17
+ export { audioFeature };
18
+
19
+ //# sourceMappingURL=feature.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"feature.js","names":[],"sources":["../src/feature.ts"],"sourcesContent":["import type { EditorFeature } from '@skaile/forge-editor/core'\nimport { type AudioMethodOptions, audioDeriveMethods } from './methods'\n\n/** Options of `audioFeature`: those of the derive methods. */\nexport type AudioFeatureOptions = AudioMethodOptions\n\n/**\n * The audio Feature: the derive methods `audio-tts` (a text block read aloud into a `recording` block) and `audio-mixdown` (the\n * takes of a container mixed into one `recording`). Both are block actions on the Typed blocks they apply to; `audio-tts`\n * needs the host's speech provider (`createElevenLabsSpeech`, `createOpenAiSpeech`), `audio-mixdown` the `audio-mixdown` render\n * target (`audioMixdownTarget`). The Feature installs after `composites`.\n */\nexport function audioFeature(options: AudioFeatureOptions = {}): EditorFeature<never> {\n return {\n id: 'audio',\n dimension: 'interaction',\n requires: ['composites'],\n deriveMethods: audioDeriveMethods(options),\n }\n}\n"],"mappings":";;;;;;;;AAYA,SAAgB,aAAa,UAA+B,CAAC,GAAyB;CACpF,OAAO;EACL,IAAI;EACJ,WAAW;EACX,UAAU,CAAC,YAAY;EACvB,eAAe,mBAAmB,OAAO;CAC3C;AACF"}
package/dist/i18n.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ import { CatalogParams, Locale } from "@skaile/forge-editor/core";
2
+ declare const de: {
3
+ readonly 'audio.tts.label': "Als Sprache vorlesen";
4
+ readonly 'audio.tts.running': "Sprache wird erzeugt …";
5
+ readonly 'audio.tts.done': "Sprachaufnahme erzeugt";
6
+ readonly 'audio.tts.failed': "Sprachausgabe fehlgeschlagen";
7
+ readonly 'audio.tts.noVoice': "Der Sprachdienst bietet keine Stimme an";
8
+ readonly 'audio.mixdown.label': "Mixdown erzeugen";
9
+ readonly 'audio.mixdown.running': "Mixdown läuft …";
10
+ readonly 'audio.mixdown.done': "Mixdown erzeugt";
11
+ readonly 'audio.mixdown.failed': "Mixdown fehlgeschlagen";
12
+ readonly 'audio.title.tts': "Sprache: {title}";
13
+ readonly 'audio.title.mixdown': "Mixdown: {title}";
14
+ readonly 'audio.title.untitled': "Ohne Titel";
15
+ readonly 'audio.gone': "Der Block wurde in der Zwischenzeit gelöscht";
16
+ readonly 'audio.notAccepted': "Hier kann keine Aufnahme eingefügt werden";
17
+ };
18
+ /** Key of an add-on message. */
19
+ export type AudioMessageKey = keyof typeof de;
20
+ /** Renders an add-on message in `locale` (German for a locale without a table); `{name}` is replaced by `params.name`. */
21
+ export type AudioTranslate = (key: AudioMessageKey, params?: CatalogParams) => string;
22
+ /** The translator of `locale` for the add-on's messages. */
23
+ export declare function audioTranslator(locale: Locale): AudioTranslate;
24
+ export {};
package/dist/i18n.js ADDED
@@ -0,0 +1,44 @@
1
+ import { createCatalogTranslator } from "@skaile/forge-editor/core";
2
+ // src/i18n.ts
3
+ const de = {
4
+ "audio.tts.label": "Als Sprache vorlesen",
5
+ "audio.tts.running": "Sprache wird erzeugt …",
6
+ "audio.tts.done": "Sprachaufnahme erzeugt",
7
+ "audio.tts.failed": "Sprachausgabe fehlgeschlagen",
8
+ "audio.tts.noVoice": "Der Sprachdienst bietet keine Stimme an",
9
+ "audio.mixdown.label": "Mixdown erzeugen",
10
+ "audio.mixdown.running": "Mixdown läuft …",
11
+ "audio.mixdown.done": "Mixdown erzeugt",
12
+ "audio.mixdown.failed": "Mixdown fehlgeschlagen",
13
+ "audio.title.tts": "Sprache: {title}",
14
+ "audio.title.mixdown": "Mixdown: {title}",
15
+ "audio.title.untitled": "Ohne Titel",
16
+ "audio.gone": "Der Block wurde in der Zwischenzeit gelöscht",
17
+ "audio.notAccepted": "Hier kann keine Aufnahme eingefügt werden"
18
+ };
19
+ const CATALOGS = {
20
+ de,
21
+ en: {
22
+ "audio.tts.label": "Read aloud as speech",
23
+ "audio.tts.running": "Creating speech …",
24
+ "audio.tts.done": "Speech recording created",
25
+ "audio.tts.failed": "Speech synthesis failed",
26
+ "audio.tts.noVoice": "The speech service offers no voice",
27
+ "audio.mixdown.label": "Create mixdown",
28
+ "audio.mixdown.running": "Mixing down …",
29
+ "audio.mixdown.done": "Mixdown created",
30
+ "audio.mixdown.failed": "Mixdown failed",
31
+ "audio.title.tts": "Speech: {title}",
32
+ "audio.title.mixdown": "Mixdown: {title}",
33
+ "audio.title.untitled": "Untitled",
34
+ "audio.gone": "The block was deleted in the meantime",
35
+ "audio.notAccepted": "A recording cannot be inserted here"
36
+ }
37
+ };
38
+ /** The translator of `locale` for the add-on's messages. */
39
+ function audioTranslator(locale) {
40
+ return createCatalogTranslator(CATALOGS[locale] ?? de);
41
+ }
42
+ export { audioTranslator };
43
+
44
+ //# sourceMappingURL=i18n.js.map