@canvakit/showreel-replicate 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/LICENSE +105 -0
- package/README.md +16 -2
- package/dist/index.d.ts +311 -0
- package/dist/index.mjs +434 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +59 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# Functional Source License, Version 1.1, ALv2 Future License
|
|
2
|
+
|
|
3
|
+
## Abbreviation
|
|
4
|
+
|
|
5
|
+
FSL-1.1-ALv2
|
|
6
|
+
|
|
7
|
+
## Notice
|
|
8
|
+
|
|
9
|
+
Copyright 2026 AGENTIK SAS
|
|
10
|
+
|
|
11
|
+
## Terms and Conditions
|
|
12
|
+
|
|
13
|
+
### Licensor ("We")
|
|
14
|
+
|
|
15
|
+
The party offering the Software under these Terms and Conditions.
|
|
16
|
+
|
|
17
|
+
### The Software
|
|
18
|
+
|
|
19
|
+
The "Software" is each version of the software that we make available under
|
|
20
|
+
these Terms and Conditions, as indicated by our inclusion of these Terms and
|
|
21
|
+
Conditions with the Software.
|
|
22
|
+
|
|
23
|
+
### License Grant
|
|
24
|
+
|
|
25
|
+
Subject to your compliance with this License Grant and the Patents,
|
|
26
|
+
Redistribution and Trademark clauses below, we hereby grant you the right to
|
|
27
|
+
use, copy, modify, create derivative works, publicly perform, publicly display
|
|
28
|
+
and redistribute the Software for any Permitted Purpose identified below.
|
|
29
|
+
|
|
30
|
+
### Permitted Purpose
|
|
31
|
+
|
|
32
|
+
A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
|
|
33
|
+
means making the Software available to others in a commercial product or
|
|
34
|
+
service that:
|
|
35
|
+
|
|
36
|
+
1. substitutes for the Software;
|
|
37
|
+
|
|
38
|
+
2. substitutes for any other product or service we offer using the Software
|
|
39
|
+
that exists as of the date we make the Software available; or
|
|
40
|
+
|
|
41
|
+
3. offers the same or substantially similar functionality as the Software.
|
|
42
|
+
|
|
43
|
+
Permitted Purposes specifically include using the Software:
|
|
44
|
+
|
|
45
|
+
1. for your internal use and access;
|
|
46
|
+
|
|
47
|
+
2. for non-commercial education;
|
|
48
|
+
|
|
49
|
+
3. for non-commercial research; and
|
|
50
|
+
|
|
51
|
+
4. in connection with professional services that you provide to a licensee
|
|
52
|
+
using the Software in accordance with these Terms and Conditions.
|
|
53
|
+
|
|
54
|
+
### Patents
|
|
55
|
+
|
|
56
|
+
To the extent your use for a Permitted Purpose would necessarily infringe our
|
|
57
|
+
patents, the license grant above includes a license under our patents. If you
|
|
58
|
+
make a claim against any party that the Software infringes or contributes to
|
|
59
|
+
the infringement of any patent, then your patent license to the Software ends
|
|
60
|
+
immediately.
|
|
61
|
+
|
|
62
|
+
### Redistribution
|
|
63
|
+
|
|
64
|
+
The Terms and Conditions apply to all copies, modifications and derivatives of
|
|
65
|
+
the Software.
|
|
66
|
+
|
|
67
|
+
If you redistribute any copies, modifications or derivatives of the Software,
|
|
68
|
+
you must include a copy of or a link to these Terms and Conditions and not
|
|
69
|
+
remove any copyright notices provided in or with the Software.
|
|
70
|
+
|
|
71
|
+
### Disclaimer
|
|
72
|
+
|
|
73
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
|
|
74
|
+
IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
|
|
75
|
+
PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
|
|
76
|
+
|
|
77
|
+
IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
|
|
78
|
+
SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
|
|
79
|
+
EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
|
|
80
|
+
|
|
81
|
+
### Trademarks
|
|
82
|
+
|
|
83
|
+
Except for displaying the License Details and identifying us as the origin of
|
|
84
|
+
the Software, you have no right under these Terms and Conditions to use our
|
|
85
|
+
trademarks, trade names, service marks or product names.
|
|
86
|
+
|
|
87
|
+
## Grant of Future License
|
|
88
|
+
|
|
89
|
+
We hereby irrevocably grant you an additional license to use the Software under
|
|
90
|
+
the Apache License, Version 2.0 that is effective on the second anniversary of
|
|
91
|
+
the date we make the Software available. On or after that date, you may use the
|
|
92
|
+
Software under the Apache License, Version 2.0, in which case the following
|
|
93
|
+
will apply:
|
|
94
|
+
|
|
95
|
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
|
96
|
+
this file except in compliance with the License.
|
|
97
|
+
|
|
98
|
+
You may obtain a copy of the License at
|
|
99
|
+
|
|
100
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
101
|
+
|
|
102
|
+
Unless required by applicable law or agreed to in writing, software distributed
|
|
103
|
+
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
|
104
|
+
CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
|
105
|
+
specific language governing permissions and limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,17 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @canvakit/showreel-replicate
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Replicate-backed VisualRenderer bridge for @canvakit/showreel: genImage (gpt-image-2) → uploadAnchor (Files API) → genVideo (seedance) as a pluggable 'replicate-anime' reel style, plus a RendererRegistry vending it alongside the built-in html-still and agentic styles by name.
|
|
4
|
+
|
|
5
|
+
Part of [canvakit](https://github.com/openagentik/canvakit).
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @canvakit/showreel-replicate
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## License
|
|
14
|
+
|
|
15
|
+
[FSL-1.1-ALv2](./LICENSE), the Functional Source License with an Apache 2.0 future
|
|
16
|
+
license: free for any use except offering a competing product or service, and
|
|
17
|
+
each version becomes Apache-2.0 two years after its release. Copyright AGENTIK SAS.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
import { SceneCacheOptions, VisualRenderer } from '@canvakit/showreel';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @canvakit/showreel-replicate — the Replicate provider primitives.
|
|
5
|
+
*
|
|
6
|
+
* Ports `.claude/skills/agentik-pitch-video/gen.mjs`'s `gen` / `video` /
|
|
7
|
+
* `upload` verbs to plain in-process async functions: `genImage`
|
|
8
|
+
* (openai/gpt-image-2, 16:9/high/png, `input_images` for cast/face
|
|
9
|
+
* coherence), `uploadAnchor` (Replicate Files API — `replicate.delivery`
|
|
10
|
+
* output URLs expire ~1h, so a cast/face anchor is re-hosted to survive a
|
|
11
|
+
* multi-beat run), `genVideo` (bytedance/seedance-2.0, image→video,
|
|
12
|
+
* `generate_audio:false`). The gen.mjs nohup/detached/logfile choreography
|
|
13
|
+
* existed only because the cowork Bash sandbox blocks outbound network
|
|
14
|
+
* (`gen.mjs:5-12`); this runs in the host node process, so it's dropped.
|
|
15
|
+
* The `poll()` loop stays — Replicate predictions are inherently async.
|
|
16
|
+
*/
|
|
17
|
+
interface ReplicateProviderConfig {
|
|
18
|
+
/** Overrides REPLICATE_API_TOKEN / REPLICATE_AI_API_KEY / .envrc resolution. */
|
|
19
|
+
apiKey?: string;
|
|
20
|
+
pollIntervalMs?: number;
|
|
21
|
+
imageTimeoutMs?: number;
|
|
22
|
+
videoTimeoutMs?: number;
|
|
23
|
+
}
|
|
24
|
+
interface GenImageInput {
|
|
25
|
+
prompt: string;
|
|
26
|
+
/** stable anchor URLs (cast/face lock) — passed as `input_images`. */
|
|
27
|
+
refs?: string[];
|
|
28
|
+
}
|
|
29
|
+
interface GenImageResult {
|
|
30
|
+
/** the generated image bytes (png). */
|
|
31
|
+
buffer: Buffer;
|
|
32
|
+
/** replicate.delivery output URL — expires ~1h, re-host via `uploadAnchor`. */
|
|
33
|
+
url: string;
|
|
34
|
+
}
|
|
35
|
+
interface UploadAnchorResult {
|
|
36
|
+
/** stable Files API URL, usable as `input_images` / `image` across beats. */
|
|
37
|
+
url: string;
|
|
38
|
+
}
|
|
39
|
+
interface GenVideoInput {
|
|
40
|
+
/** the anchor image URL (from `uploadAnchor`) driving the animation. */
|
|
41
|
+
imageUrl: string;
|
|
42
|
+
prompt: string;
|
|
43
|
+
resolution?: string;
|
|
44
|
+
}
|
|
45
|
+
interface GenVideoResult {
|
|
46
|
+
/** the generated clip bytes (mp4). */
|
|
47
|
+
buffer: Buffer;
|
|
48
|
+
url: string;
|
|
49
|
+
}
|
|
50
|
+
/** The provider surface `replicateAnimeVisualRenderer` depends on — injectable for tests. */
|
|
51
|
+
interface ReplicateProvider {
|
|
52
|
+
genImage(input: GenImageInput, config?: ReplicateProviderConfig): Promise<GenImageResult>;
|
|
53
|
+
uploadAnchor(buffer: Buffer, filename: string, config?: ReplicateProviderConfig): Promise<UploadAnchorResult>;
|
|
54
|
+
genVideo(input: GenVideoInput, config?: ReplicateProviderConfig): Promise<GenVideoResult>;
|
|
55
|
+
}
|
|
56
|
+
/** Raised when a Replicate prediction fails, is canceled, or times out. */
|
|
57
|
+
declare class ReplicatePredictionError extends Error {
|
|
58
|
+
constructor(message: string);
|
|
59
|
+
}
|
|
60
|
+
/** Resolution order: explicit config → env vars → the nearest `.envrc` walking up from cwd. */
|
|
61
|
+
declare function resolveReplicateApiKey(config?: ReplicateProviderConfig): string;
|
|
62
|
+
/** `genImage` — openai/gpt-image-2, 16:9/high/png, `input_images` for cast/face coherence. */
|
|
63
|
+
declare function genImage(input: GenImageInput, config?: ReplicateProviderConfig): Promise<GenImageResult>;
|
|
64
|
+
/** `uploadAnchor` — Replicate Files API (multipart), re-hosts a local image to a stable URL. */
|
|
65
|
+
declare function uploadAnchor(buffer: Buffer, filename: string, config?: ReplicateProviderConfig): Promise<UploadAnchorResult>;
|
|
66
|
+
/** `genVideo` — bytedance/seedance-2.0, image→video, `duration:5`, `generate_audio:false`. */
|
|
67
|
+
declare function genVideo(input: GenVideoInput, config?: ReplicateProviderConfig): Promise<GenVideoResult>;
|
|
68
|
+
/** The real Replicate provider — `genImage`/`uploadAnchor`/`genVideo` bound together. */
|
|
69
|
+
declare const replicateProvider: ReplicateProvider;
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* @canvakit/showreel-replicate — the ID'd asset manifest.
|
|
73
|
+
*
|
|
74
|
+
* A human-addressable index (`<projectDir>/assets.json`) over the
|
|
75
|
+
* content-addressed Replicate images this package generates: a stable id
|
|
76
|
+
* (e.g. "beat-03", or "beat-03-panel2" for a sub-asset) maps to
|
|
77
|
+
* `{ prompt, refs, model, filePath, sourceHash, ... }`. `resolveImageAsset`
|
|
78
|
+
* is the reuse gate every `genImage` call goes through — a Replicate call
|
|
79
|
+
* only happens when no entry exists for the id, or its `sourceHash`
|
|
80
|
+
* (prompt+refs+model) no longer matches what's stored. `editAsset` lets a
|
|
81
|
+
* human regenerate exactly one entry by id, without touching any other
|
|
82
|
+
* asset, and marks it `stale` so the render pipeline knows a clip produced
|
|
83
|
+
* from the pre-edit image needs redoing.
|
|
84
|
+
*
|
|
85
|
+
* This is the NAMED index; `cachingVisualRenderer` (`@canvakit/showreel`'s
|
|
86
|
+
* `renderer/cache.js`) stays the underlying content-addressed BYTE store
|
|
87
|
+
* for whole rendered clips — the two are independent, complementary layers.
|
|
88
|
+
*/
|
|
89
|
+
|
|
90
|
+
/** The image model `resolveImageAsset`/`editAsset` assume when the caller doesn't say otherwise. */
|
|
91
|
+
declare const DEFAULT_IMAGE_MODEL = "openai/gpt-image-2";
|
|
92
|
+
interface AssetManifestEntry {
|
|
93
|
+
/** stable, human-addressable id — e.g. "beat-03" or "beat-03-panel2". Never an opaque hash. */
|
|
94
|
+
id: string;
|
|
95
|
+
/** the ShowreelConfig timeline item this asset belongs to. */
|
|
96
|
+
beatId: string;
|
|
97
|
+
kind: "image";
|
|
98
|
+
prompt: string;
|
|
99
|
+
refs: string[];
|
|
100
|
+
model: string;
|
|
101
|
+
/** absolute path to the generated PNG on disk. */
|
|
102
|
+
filePath: string;
|
|
103
|
+
/** the Replicate output URL from the generating prediction (expires ~1h — `filePath` is the durable copy). */
|
|
104
|
+
replicateUrl?: string;
|
|
105
|
+
createdAt: string;
|
|
106
|
+
/** content hash over prompt+refs+model — the reuse/invalidation key. */
|
|
107
|
+
sourceHash: string;
|
|
108
|
+
/** set by `editAsset` — the image itself is current, but a clip rendered before this edit is not. */
|
|
109
|
+
stale?: boolean;
|
|
110
|
+
}
|
|
111
|
+
interface AssetManifest {
|
|
112
|
+
version: 1;
|
|
113
|
+
assets: Record<string, AssetManifestEntry>;
|
|
114
|
+
}
|
|
115
|
+
declare function createEmptyManifest(): AssetManifest;
|
|
116
|
+
/** Read a manifest from disk. A missing file yields a fresh empty manifest — never throws on ENOENT. */
|
|
117
|
+
declare function loadManifest(path: string): AssetManifest;
|
|
118
|
+
/** Persist a manifest to disk, creating its parent directory as needed. */
|
|
119
|
+
declare function saveManifest(path: string, manifest: AssetManifest): void;
|
|
120
|
+
/** Content hash over exactly what determines an image's pixels — prompt + refs + model. */
|
|
121
|
+
declare function computeSourceHash(input: {
|
|
122
|
+
prompt: string;
|
|
123
|
+
refs: string[];
|
|
124
|
+
model: string;
|
|
125
|
+
}): string;
|
|
126
|
+
interface ResolveImageAssetInput {
|
|
127
|
+
manifest: AssetManifest;
|
|
128
|
+
/** stable, human-addressable id — e.g. "beat-03" or "beat-03-panel2". */
|
|
129
|
+
id: string;
|
|
130
|
+
beatId: string;
|
|
131
|
+
prompt: string;
|
|
132
|
+
refs?: string[];
|
|
133
|
+
model?: string;
|
|
134
|
+
provider: Pick<ReplicateProvider, "genImage">;
|
|
135
|
+
providerConfig?: ReplicateProviderConfig;
|
|
136
|
+
/** directory a freshly generated PNG is written to. */
|
|
137
|
+
outDir: string;
|
|
138
|
+
}
|
|
139
|
+
interface ResolveImageAssetResult {
|
|
140
|
+
entry: AssetManifestEntry;
|
|
141
|
+
buffer: Buffer;
|
|
142
|
+
/** true when an existing manifest entry's `sourceHash` matched — zero `genImage` calls were made. */
|
|
143
|
+
reused: boolean;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* The manifest-aware reuse gate `genImage` calls go through: an id whose
|
|
147
|
+
* stored `sourceHash` still matches (and whose file still exists) is served
|
|
148
|
+
* straight off disk — zero Replicate calls. Anything else generates once
|
|
149
|
+
* and upserts the entry.
|
|
150
|
+
*/
|
|
151
|
+
declare function resolveImageAsset(input: ResolveImageAssetInput): Promise<ResolveImageAssetResult>;
|
|
152
|
+
interface EditAssetOverrides {
|
|
153
|
+
imagePrompt?: string;
|
|
154
|
+
refs?: string[];
|
|
155
|
+
}
|
|
156
|
+
interface EditAssetOptions {
|
|
157
|
+
provider: Pick<ReplicateProvider, "genImage">;
|
|
158
|
+
providerConfig?: ReplicateProviderConfig;
|
|
159
|
+
/** directory the regenerated PNG is written to. Defaults to the existing entry's own directory. */
|
|
160
|
+
outDir?: string;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Regenerate exactly ONE asset by id — the only `genImage` call this makes
|
|
164
|
+
* — and upsert its entry (new prompt/refs/sourceHash/file). Every other
|
|
165
|
+
* manifest entry is left untouched. Marks the entry `stale: true`: the
|
|
166
|
+
* image is now current, but a clip rendered from the pre-edit image is not,
|
|
167
|
+
* so the render pipeline should redo that beat's clip on its next pass.
|
|
168
|
+
*/
|
|
169
|
+
declare function editAsset(manifest: AssetManifest, id: string, overrides: EditAssetOverrides, opts: EditAssetOptions): Promise<AssetManifestEntry>;
|
|
170
|
+
/** Clear an entry's `stale` marker once its downstream clip has been redone. */
|
|
171
|
+
declare function clearAssetStale(manifest: AssetManifest, id: string): void;
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* @canvakit/showreel-replicate — shared scene→image resolution.
|
|
175
|
+
*
|
|
176
|
+
* Both reel styles (`replicateAnimeVisualRenderer` video,
|
|
177
|
+
* `replicateAnimeStillVisualRenderer` still) turn a `SceneItem.data` into an
|
|
178
|
+
* image the exact same way: build the (possibly multi-panel) `imagePrompt`,
|
|
179
|
+
* then resolve the bytes either directly via `provider.genImage` or, when a
|
|
180
|
+
* `ManifestStoreConfig` is supplied, through `resolveImageAsset` so a
|
|
181
|
+
* storyboard render, a still render, and a video render of the same beat
|
|
182
|
+
* all reuse the identical generated image. Written once here so neither
|
|
183
|
+
* renderer duplicates the Replicate call / split-screen prompt logic.
|
|
184
|
+
*/
|
|
185
|
+
|
|
186
|
+
/** `SceneItem.data` shape the replicate-anime styles read — renderer-agnostic (video and still share it). */
|
|
187
|
+
interface ReplicateAnimeSceneData {
|
|
188
|
+
imagePrompt?: string;
|
|
189
|
+
motionPrompt: string;
|
|
190
|
+
/** cast/face-lock anchor URLs, passed to `genImage` as `input_images`. */
|
|
191
|
+
refs?: string[];
|
|
192
|
+
/** when "split-screen", `imagePrompt` is built from `panels` instead of used directly. */
|
|
193
|
+
layout?: "split-screen";
|
|
194
|
+
panels?: string[];
|
|
195
|
+
}
|
|
196
|
+
/** Where a `VisualRenderer` persists/reuses generated images by human-addressable id — see `manifest.ts`. */
|
|
197
|
+
interface ManifestStoreConfig {
|
|
198
|
+
manifest: AssetManifest;
|
|
199
|
+
/** directory freshly generated PNGs are written to. Defaults to a fresh tmp dir per renderer instance. */
|
|
200
|
+
outDir?: string;
|
|
201
|
+
/** when set, the manifest is written back to disk after every resolve. */
|
|
202
|
+
manifestPath?: string;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Compose a single multi-panel `imagePrompt` from `data.panels` — a
|
|
206
|
+
* mechanical, brand-agnostic triptych/split-screen instruction gpt-image-2
|
|
207
|
+
* can render as one 16:9 frame. Falls back to `data.imagePrompt` when no
|
|
208
|
+
* panels are given (so a `layout:"split-screen"` beat with a pre-composed
|
|
209
|
+
* prompt still works without change).
|
|
210
|
+
*/
|
|
211
|
+
declare function buildSplitScreenImagePrompt(data: Pick<ReplicateAnimeSceneData, "imagePrompt" | "panels">): string;
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* @canvakit/showreel-replicate — `replicateAnimeVisualRenderer`.
|
|
215
|
+
*
|
|
216
|
+
* Installs the Replicate pipeline as a `VisualRenderer` for
|
|
217
|
+
* `@canvakit/showreel` (see `renderer/index.ts` in that package):
|
|
218
|
+
* `renderScene` resolves the scene's image via `resolveSceneImage` (direct
|
|
219
|
+
* `genImage`, or manifest-store-mediated — see `scene-image.ts`), then runs
|
|
220
|
+
* `uploadAnchor → genVideo` (the anchor re-host beats the ~1h
|
|
221
|
+
* `replicate.delivery` expiry across a multi-beat run) and returns
|
|
222
|
+
* `{ clipPath, durationMs: item.duration }` — assembly conforms the real
|
|
223
|
+
* ~5s clip to the declared slot, same contract the html-still and agentic
|
|
224
|
+
* renderers honor. Wrapped in `cachingVisualRenderer` by default (unless a
|
|
225
|
+
* manifest `store` is configured, in which case the store's per-image reuse
|
|
226
|
+
* is the primary cache and the clip is re-encoded fresh each render) so a
|
|
227
|
+
* re-run only regenerates beats whose prompt/data actually changed.
|
|
228
|
+
*/
|
|
229
|
+
|
|
230
|
+
interface ReplicateAnimeVisualRendererConfig extends ReplicateProviderConfig {
|
|
231
|
+
/** Injectable provider — the real Replicate one by default, a fake in tests. */
|
|
232
|
+
provider?: ReplicateProvider;
|
|
233
|
+
/** Per-beat retry count on a transient Replicate/network failure. Default 2. */
|
|
234
|
+
maxRetries?: number;
|
|
235
|
+
/** seedance output resolution. Default "480p" (mirrors gen.mjs). */
|
|
236
|
+
resolution?: string;
|
|
237
|
+
/** Where rendered clips land; defaults to a fresh tmp dir. */
|
|
238
|
+
outDir?: string;
|
|
239
|
+
/** Content-addressed cache wrapping (see `cachingVisualRenderer`). `false` disables it. Defaults to `false` when `store` is set — the manifest is the reuse layer then. */
|
|
240
|
+
cache?: SceneCacheOptions | false;
|
|
241
|
+
/** ID'd asset manifest — reuses the same generated image a storyboard/still render already produced for this beat. */
|
|
242
|
+
store?: ManifestStoreConfig;
|
|
243
|
+
}
|
|
244
|
+
/** A `VisualRenderer` where each scene clip is produced via Replicate (image → anchor → video). */
|
|
245
|
+
declare function replicateAnimeVisualRenderer(config?: ReplicateAnimeVisualRendererConfig): VisualRenderer;
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* @canvakit/showreel-replicate — `replicateAnimeStillVisualRenderer`.
|
|
249
|
+
*
|
|
250
|
+
* The still/pre-render counterpart to `replicateAnimeVisualRenderer`:
|
|
251
|
+
* resolves the SAME `SceneItem.data → imagePrompt` (split-screen included)
|
|
252
|
+
* through `resolveSceneImage` — reusing `genImage` + the manifest-aware
|
|
253
|
+
* asset store, so a still render and a video render of the same beat share
|
|
254
|
+
* the identical generated image — then encodes the still directly to an
|
|
255
|
+
* exact-duration mp4 via ffmpeg (`-loop 1 -t <durationMs/1000>`, mirroring
|
|
256
|
+
* `@canvakit/showreel`'s own `encodeStillToMp4`). No `genVideo` call — a
|
|
257
|
+
* still beat never animates.
|
|
258
|
+
*/
|
|
259
|
+
|
|
260
|
+
interface ReplicateAnimeStillVisualRendererConfig extends ReplicateProviderConfig {
|
|
261
|
+
/** Injectable provider — only `genImage` is called. The real Replicate one by default, a fake in tests. */
|
|
262
|
+
provider?: Pick<ReplicateProvider, "genImage">;
|
|
263
|
+
/** Per-beat retry count on a transient Replicate/network failure. Default 2. */
|
|
264
|
+
maxRetries?: number;
|
|
265
|
+
/** ffmpeg output framerate. Default 30 (mirrors `@canvakit/showreel`'s html-still renderer). */
|
|
266
|
+
fps?: number;
|
|
267
|
+
/** Where rendered clips land; defaults to a fresh tmp dir. */
|
|
268
|
+
outDir?: string;
|
|
269
|
+
/** Content-addressed cache wrapping (see `cachingVisualRenderer`). `false` disables it. Defaults to `false` when `store` is set — the manifest is the reuse layer then. */
|
|
270
|
+
cache?: SceneCacheOptions | false;
|
|
271
|
+
/** ID'd asset manifest — shared with `replicateAnimeVisualRenderer` so a still and a video render of the same beat reuse the same generated image. */
|
|
272
|
+
store?: ManifestStoreConfig;
|
|
273
|
+
}
|
|
274
|
+
/** A `VisualRenderer` where each scene clip is a still (image → exact-duration mp4, no animation). */
|
|
275
|
+
declare function replicateAnimeStillVisualRenderer(config?: ReplicateAnimeStillVisualRendererConfig): VisualRenderer;
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* `RendererRegistry` — a reel style is a `VisualRenderer`, picked by name.
|
|
279
|
+
*
|
|
280
|
+
* Mirrors `@canvakit/showreel`'s `SceneTemplateRegistry`
|
|
281
|
+
* (`templates/registry.ts:98-181`) in shape: `register()` / `resolve()` /
|
|
282
|
+
* `list()`, never-throw (an unknown name warns + returns `null`), plus a
|
|
283
|
+
* `createDefault…()` + default-singleton pair. `resolveVisualRenderer({
|
|
284
|
+
* renderer })` (`renderer/index.ts:73-78`) is already the injection hook
|
|
285
|
+
* into `@canvakit/showreel` — this registry only produces that `renderer`
|
|
286
|
+
* argument by name, so a new style plugs in via `register()` with ZERO
|
|
287
|
+
* `@canvakit/showreel` change.
|
|
288
|
+
*/
|
|
289
|
+
|
|
290
|
+
/** One reel style: a name, and a factory producing its `VisualRenderer`. */
|
|
291
|
+
interface ReelStyle {
|
|
292
|
+
name: string;
|
|
293
|
+
makeRenderer(config?: unknown): VisualRenderer;
|
|
294
|
+
}
|
|
295
|
+
declare class RendererRegistry {
|
|
296
|
+
#private;
|
|
297
|
+
register(style: ReelStyle): void;
|
|
298
|
+
has(name: string): boolean;
|
|
299
|
+
/** Resolve a style name to a fresh `VisualRenderer` instance. Never throws — an unknown name warns and returns `null`. */
|
|
300
|
+
resolve(name: string, config?: unknown): VisualRenderer | null;
|
|
301
|
+
/** Every registered style name, sorted. */
|
|
302
|
+
list(): string[];
|
|
303
|
+
}
|
|
304
|
+
/** Build a registry pre-populated with the built-in styles. */
|
|
305
|
+
declare function createDefaultRendererRegistry(): RendererRegistry;
|
|
306
|
+
/** Default singleton — `resolveReelStyle` and host storyboard helpers use this. */
|
|
307
|
+
declare const defaultRendererRegistry: RendererRegistry;
|
|
308
|
+
/** Resolve a style name against the default registry. Never throws. */
|
|
309
|
+
declare function resolveReelStyle(name: string, config?: unknown): VisualRenderer | null;
|
|
310
|
+
|
|
311
|
+
export { type AssetManifest, type AssetManifestEntry, DEFAULT_IMAGE_MODEL, type EditAssetOptions, type EditAssetOverrides, type GenImageInput, type GenImageResult, type GenVideoInput, type GenVideoResult, type ManifestStoreConfig, type ReelStyle, RendererRegistry, type ReplicateAnimeSceneData, type ReplicateAnimeStillVisualRendererConfig, type ReplicateAnimeVisualRendererConfig, ReplicatePredictionError, type ReplicateProvider, type ReplicateProviderConfig, type ResolveImageAssetInput, type ResolveImageAssetResult, type UploadAnchorResult, buildSplitScreenImagePrompt, clearAssetStale, computeSourceHash, createDefaultRendererRegistry, createEmptyManifest, defaultRendererRegistry, editAsset, genImage, genVideo, loadManifest, replicateAnimeStillVisualRenderer, replicateAnimeVisualRenderer, replicateProvider, resolveImageAsset, resolveReelStyle, resolveReplicateApiKey, saveManifest, uploadAnchor };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
import { mkdtempSync, readFileSync, mkdirSync, writeFileSync, existsSync } from 'fs';
|
|
2
|
+
import { join, dirname } from 'path';
|
|
3
|
+
import { tmpdir } from 'os';
|
|
4
|
+
import { htmlStillVisualRenderer, cachingVisualRenderer } from '@canvakit/showreel';
|
|
5
|
+
import { createHash } from 'crypto';
|
|
6
|
+
import { spawn } from 'child_process';
|
|
7
|
+
import { agenticVisualRenderer } from '@canvakit/showreel-agentic';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @canvakit/showreel-replicate v0.1.0
|
|
11
|
+
* Replicate-backed VisualRenderer bridge for @canvakit/showreel.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
var DEFAULT_POLL_INTERVAL_MS = 3500;
|
|
15
|
+
var DEFAULT_IMAGE_TIMEOUT_MS = 18e4;
|
|
16
|
+
var DEFAULT_VIDEO_TIMEOUT_MS = 6e5;
|
|
17
|
+
var IMAGE_MODEL = "openai/gpt-image-2";
|
|
18
|
+
var VIDEO_MODEL = "bytedance/seedance-2.0";
|
|
19
|
+
var ReplicatePredictionError = class extends Error {
|
|
20
|
+
constructor(message) {
|
|
21
|
+
super(message);
|
|
22
|
+
this.name = "ReplicatePredictionError";
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
function resolveReplicateApiKey(config) {
|
|
26
|
+
if (config?.apiKey) return config.apiKey;
|
|
27
|
+
if (process.env.REPLICATE_API_TOKEN) return process.env.REPLICATE_API_TOKEN;
|
|
28
|
+
if (process.env.REPLICATE_AI_API_KEY) return process.env.REPLICATE_AI_API_KEY;
|
|
29
|
+
const envrc = findEnvrc(process.cwd());
|
|
30
|
+
if (envrc) {
|
|
31
|
+
const text = readFileSync(envrc, "utf8");
|
|
32
|
+
const match = /REPLICATE(?:_AI)?_API_(?:TOKEN|KEY)[=: ]+['"]?([A-Za-z0-9_]+)/.exec(text);
|
|
33
|
+
if (match?.[1]) return match[1];
|
|
34
|
+
}
|
|
35
|
+
throw new Error(
|
|
36
|
+
"resolveReplicateApiKey: no Replicate key \u2014 set REPLICATE_API_TOKEN / REPLICATE_AI_API_KEY, pass config.apiKey, or add one to a .envrc."
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
function findEnvrc(start) {
|
|
40
|
+
let dir = start;
|
|
41
|
+
for (let i = 0; i < 8; i++) {
|
|
42
|
+
const candidate = join(dir, ".envrc");
|
|
43
|
+
try {
|
|
44
|
+
readFileSync(candidate, "utf8");
|
|
45
|
+
return candidate;
|
|
46
|
+
} catch {
|
|
47
|
+
}
|
|
48
|
+
const up = dirname(dir);
|
|
49
|
+
if (up === dir) break;
|
|
50
|
+
dir = up;
|
|
51
|
+
}
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
async function poll(getUrl, apiKey, maxMs, pollIntervalMs) {
|
|
55
|
+
const deadline = Date.now() + maxMs;
|
|
56
|
+
for (; ; ) {
|
|
57
|
+
if (Date.now() > deadline) {
|
|
58
|
+
throw new ReplicatePredictionError(`poll: timed out after ${String(maxMs)}ms waiting on ${getUrl}`);
|
|
59
|
+
}
|
|
60
|
+
await sleep(pollIntervalMs);
|
|
61
|
+
const response = await fetch(getUrl, { headers: { Authorization: `Bearer ${apiKey}` } });
|
|
62
|
+
const pred = await response.json();
|
|
63
|
+
if (pred.status === "succeeded" || pred.status === "failed" || pred.status === "canceled") {
|
|
64
|
+
return pred;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function sleep(ms) {
|
|
69
|
+
return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
|
|
70
|
+
}
|
|
71
|
+
async function runPrediction(model, input, apiKey, maxMs, pollIntervalMs) {
|
|
72
|
+
const createResponse = await fetch(`https://api.replicate.com/v1/models/${model}/predictions`, {
|
|
73
|
+
method: "POST",
|
|
74
|
+
headers: {
|
|
75
|
+
Authorization: `Bearer ${apiKey}`,
|
|
76
|
+
"content-type": "application/json"
|
|
77
|
+
},
|
|
78
|
+
body: JSON.stringify({ input })
|
|
79
|
+
});
|
|
80
|
+
if (!createResponse.ok) {
|
|
81
|
+
const body = await createResponse.text().catch(() => "");
|
|
82
|
+
throw new ReplicatePredictionError(
|
|
83
|
+
`runPrediction: ${model} create failed (${String(createResponse.status)}): ${body.slice(0, 1e3)}`
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
const created = await createResponse.json();
|
|
87
|
+
const pred = await poll(created.urls.get, apiKey, maxMs, pollIntervalMs);
|
|
88
|
+
if (pred.status !== "succeeded") {
|
|
89
|
+
throw new ReplicatePredictionError(
|
|
90
|
+
`runPrediction: ${model} prediction ${pred.status} \u2014 ${JSON.stringify(pred.error ?? pred).slice(0, 1e3)}`
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
const url = Array.isArray(pred.output) ? pred.output[0] : pred.output;
|
|
94
|
+
const download = await fetch(url);
|
|
95
|
+
if (!download.ok) {
|
|
96
|
+
throw new ReplicatePredictionError(
|
|
97
|
+
`runPrediction: downloading ${model} output failed (${String(download.status)})`
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
const buffer = Buffer.from(await download.arrayBuffer());
|
|
101
|
+
return { buffer, url };
|
|
102
|
+
}
|
|
103
|
+
async function genImage(input, config = {}) {
|
|
104
|
+
const apiKey = resolveReplicateApiKey(config);
|
|
105
|
+
const modelInput = {
|
|
106
|
+
prompt: input.prompt,
|
|
107
|
+
aspect_ratio: "16:9",
|
|
108
|
+
quality: "high",
|
|
109
|
+
output_format: "png"
|
|
110
|
+
};
|
|
111
|
+
if (input.refs?.length) modelInput.input_images = input.refs;
|
|
112
|
+
const { buffer, url } = await runPrediction(
|
|
113
|
+
IMAGE_MODEL,
|
|
114
|
+
modelInput,
|
|
115
|
+
apiKey,
|
|
116
|
+
config.imageTimeoutMs ?? DEFAULT_IMAGE_TIMEOUT_MS,
|
|
117
|
+
config.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS
|
|
118
|
+
);
|
|
119
|
+
return { buffer, url };
|
|
120
|
+
}
|
|
121
|
+
async function uploadAnchor(buffer, filename, config = {}) {
|
|
122
|
+
const apiKey = resolveReplicateApiKey(config);
|
|
123
|
+
const mime = filename.endsWith(".png") ? "image/png" : filename.endsWith(".jpg") || filename.endsWith(".jpeg") ? "image/jpeg" : "application/octet-stream";
|
|
124
|
+
const form = new FormData();
|
|
125
|
+
form.append("content", new Blob([new Uint8Array(buffer)], { type: mime }), filename);
|
|
126
|
+
const response = await fetch("https://api.replicate.com/v1/files", {
|
|
127
|
+
method: "POST",
|
|
128
|
+
headers: { Authorization: `Bearer ${apiKey}` },
|
|
129
|
+
body: form
|
|
130
|
+
});
|
|
131
|
+
if (!response.ok) {
|
|
132
|
+
const body = await response.text().catch(() => "");
|
|
133
|
+
throw new ReplicatePredictionError(`uploadAnchor: upload failed (${String(response.status)}): ${body.slice(0, 800)}`);
|
|
134
|
+
}
|
|
135
|
+
const parsed = await response.json();
|
|
136
|
+
const url = parsed.urls?.get;
|
|
137
|
+
if (!url) {
|
|
138
|
+
throw new ReplicatePredictionError("uploadAnchor: response had no urls.get");
|
|
139
|
+
}
|
|
140
|
+
return { url };
|
|
141
|
+
}
|
|
142
|
+
async function genVideo(input, config = {}) {
|
|
143
|
+
const apiKey = resolveReplicateApiKey(config);
|
|
144
|
+
const modelInput = {
|
|
145
|
+
image: input.imageUrl,
|
|
146
|
+
prompt: input.prompt,
|
|
147
|
+
duration: 5,
|
|
148
|
+
resolution: input.resolution ?? "480p",
|
|
149
|
+
aspect_ratio: "adaptive",
|
|
150
|
+
generate_audio: false
|
|
151
|
+
};
|
|
152
|
+
const { buffer, url } = await runPrediction(
|
|
153
|
+
VIDEO_MODEL,
|
|
154
|
+
modelInput,
|
|
155
|
+
apiKey,
|
|
156
|
+
config.videoTimeoutMs ?? DEFAULT_VIDEO_TIMEOUT_MS,
|
|
157
|
+
config.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS
|
|
158
|
+
);
|
|
159
|
+
return { buffer, url };
|
|
160
|
+
}
|
|
161
|
+
var replicateProvider = { genImage, uploadAnchor, genVideo };
|
|
162
|
+
var DEFAULT_IMAGE_MODEL = "openai/gpt-image-2";
|
|
163
|
+
function createEmptyManifest() {
|
|
164
|
+
return { version: 1, assets: {} };
|
|
165
|
+
}
|
|
166
|
+
function loadManifest(path) {
|
|
167
|
+
try {
|
|
168
|
+
const raw = readFileSync(path, "utf8");
|
|
169
|
+
const parsed = JSON.parse(raw);
|
|
170
|
+
return { version: 1, assets: parsed.assets ?? {} };
|
|
171
|
+
} catch (err) {
|
|
172
|
+
if (isEnoent(err)) return createEmptyManifest();
|
|
173
|
+
throw err;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
function saveManifest(path, manifest) {
|
|
177
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
178
|
+
writeFileSync(path, `${JSON.stringify(manifest, null, 2)}
|
|
179
|
+
`);
|
|
180
|
+
}
|
|
181
|
+
function isEnoent(err) {
|
|
182
|
+
return err instanceof Error && err.code === "ENOENT";
|
|
183
|
+
}
|
|
184
|
+
function computeSourceHash(input) {
|
|
185
|
+
const payload = JSON.stringify({ prompt: input.prompt, refs: input.refs, model: input.model });
|
|
186
|
+
return createHash("sha256").update(payload).digest("hex");
|
|
187
|
+
}
|
|
188
|
+
async function resolveImageAsset(input) {
|
|
189
|
+
const refs = input.refs ?? [];
|
|
190
|
+
const model = input.model ?? DEFAULT_IMAGE_MODEL;
|
|
191
|
+
const sourceHash = computeSourceHash({ prompt: input.prompt, refs, model });
|
|
192
|
+
const existing = input.manifest.assets[input.id];
|
|
193
|
+
if (existing && existing.sourceHash === sourceHash && existsSync(existing.filePath)) {
|
|
194
|
+
return { entry: existing, buffer: readFileSync(existing.filePath), reused: true };
|
|
195
|
+
}
|
|
196
|
+
const genInput = { prompt: input.prompt, refs: refs.length ? refs : void 0 };
|
|
197
|
+
const image = await input.provider.genImage(genInput, input.providerConfig);
|
|
198
|
+
mkdirSync(input.outDir, { recursive: true });
|
|
199
|
+
const filePath = join(input.outDir, `${input.id}.png`);
|
|
200
|
+
writeFileSync(filePath, image.buffer);
|
|
201
|
+
const entry = {
|
|
202
|
+
id: input.id,
|
|
203
|
+
beatId: input.beatId,
|
|
204
|
+
kind: "image",
|
|
205
|
+
prompt: input.prompt,
|
|
206
|
+
refs,
|
|
207
|
+
model,
|
|
208
|
+
filePath,
|
|
209
|
+
replicateUrl: image.url,
|
|
210
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
211
|
+
sourceHash,
|
|
212
|
+
stale: false
|
|
213
|
+
};
|
|
214
|
+
input.manifest.assets[input.id] = entry;
|
|
215
|
+
return { entry, buffer: image.buffer, reused: false };
|
|
216
|
+
}
|
|
217
|
+
async function editAsset(manifest, id, overrides, opts) {
|
|
218
|
+
const existing = manifest.assets[id];
|
|
219
|
+
if (!existing) {
|
|
220
|
+
throw new Error(`editAsset: no asset "${id}" in the manifest \u2014 resolveImageAsset it at least once first.`);
|
|
221
|
+
}
|
|
222
|
+
const prompt = overrides.imagePrompt ?? existing.prompt;
|
|
223
|
+
const refs = overrides.refs ?? existing.refs;
|
|
224
|
+
const sourceHash = computeSourceHash({ prompt, refs, model: existing.model });
|
|
225
|
+
const genInput = { prompt, refs: refs.length ? refs : void 0 };
|
|
226
|
+
const image = await opts.provider.genImage(genInput, opts.providerConfig);
|
|
227
|
+
const outDir = opts.outDir ?? dirname(existing.filePath);
|
|
228
|
+
mkdirSync(outDir, { recursive: true });
|
|
229
|
+
const filePath = join(outDir, `${id}.png`);
|
|
230
|
+
writeFileSync(filePath, image.buffer);
|
|
231
|
+
const entry = {
|
|
232
|
+
...existing,
|
|
233
|
+
prompt,
|
|
234
|
+
refs,
|
|
235
|
+
filePath,
|
|
236
|
+
replicateUrl: image.url,
|
|
237
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
238
|
+
sourceHash,
|
|
239
|
+
stale: true
|
|
240
|
+
};
|
|
241
|
+
manifest.assets[id] = entry;
|
|
242
|
+
return entry;
|
|
243
|
+
}
|
|
244
|
+
function clearAssetStale(manifest, id) {
|
|
245
|
+
const existing = manifest.assets[id];
|
|
246
|
+
if (existing) existing.stale = false;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// src/scene-image.ts
|
|
250
|
+
function buildSplitScreenImagePrompt(data) {
|
|
251
|
+
const panels = data.panels ?? [];
|
|
252
|
+
if (panels.length === 0) return data.imagePrompt ?? "";
|
|
253
|
+
const panelLines = panels.map((panel, index) => `${String(index + 1)}) ${panel}`).join("; ");
|
|
254
|
+
const intro = data.imagePrompt ? `${data.imagePrompt} \u2014 ` : "";
|
|
255
|
+
return `${intro}a single 16:9 frame split into ${String(panels.length)} vertical panels, each rendered in the same consistent art style: ${panelLines}.`;
|
|
256
|
+
}
|
|
257
|
+
function requireString(value, sceneId, field) {
|
|
258
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
259
|
+
throw new Error(`showreel-replicate: scene "${sceneId}" is missing data.${field}`);
|
|
260
|
+
}
|
|
261
|
+
return value;
|
|
262
|
+
}
|
|
263
|
+
async function withRetry(maxRetries, fn) {
|
|
264
|
+
let lastError;
|
|
265
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
266
|
+
try {
|
|
267
|
+
return await fn();
|
|
268
|
+
} catch (err) {
|
|
269
|
+
lastError = err;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
273
|
+
}
|
|
274
|
+
function defaultStoreOutDir(store) {
|
|
275
|
+
if (!store) return void 0;
|
|
276
|
+
return store.outDir ?? mkdtempSync(join(tmpdir(), "showreel-replicate-assets-"));
|
|
277
|
+
}
|
|
278
|
+
async function resolveSceneImage(provider, providerConfig, store, storeOutDir, item) {
|
|
279
|
+
const data = item.data;
|
|
280
|
+
const imagePrompt = data.layout === "split-screen" ? buildSplitScreenImagePrompt(data) : requireString(data.imagePrompt, item.id, "imagePrompt");
|
|
281
|
+
const refs = Array.isArray(data.refs) ? data.refs.filter((ref) => typeof ref === "string") : void 0;
|
|
282
|
+
if (store) {
|
|
283
|
+
const result = await resolveImageAsset({
|
|
284
|
+
manifest: store.manifest,
|
|
285
|
+
id: item.id,
|
|
286
|
+
beatId: item.id,
|
|
287
|
+
prompt: imagePrompt,
|
|
288
|
+
refs,
|
|
289
|
+
provider,
|
|
290
|
+
providerConfig,
|
|
291
|
+
outDir: storeOutDir ?? mkdtempSync(join(tmpdir(), "showreel-replicate-assets-"))
|
|
292
|
+
});
|
|
293
|
+
return { buffer: result.buffer, imagePrompt };
|
|
294
|
+
}
|
|
295
|
+
const image = await provider.genImage({ prompt: imagePrompt, refs }, providerConfig);
|
|
296
|
+
return { buffer: image.buffer, imagePrompt };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// src/renderer.ts
|
|
300
|
+
function replicateAnimeVisualRenderer(config = {}) {
|
|
301
|
+
const provider = config.provider ?? replicateProvider;
|
|
302
|
+
const maxRetries = config.maxRetries ?? 2;
|
|
303
|
+
const storeOutDir = defaultStoreOutDir(config.store);
|
|
304
|
+
const raw = {
|
|
305
|
+
async renderScene(item, brand) {
|
|
306
|
+
return withRetry(maxRetries, () => renderOneScene(provider, config, storeOutDir, item, brand));
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
const cacheOpt = config.cache ?? (config.store ? false : {});
|
|
310
|
+
return cacheOpt === false ? raw : cachingVisualRenderer(raw, cacheOpt);
|
|
311
|
+
}
|
|
312
|
+
async function renderOneScene(provider, config, storeOutDir, item, _brand) {
|
|
313
|
+
const data = item.data;
|
|
314
|
+
const motionPrompt = requireString(data.motionPrompt, item.id, "motionPrompt");
|
|
315
|
+
const { buffer: imageBuffer } = await resolveSceneImage(provider, config, config.store, storeOutDir, item);
|
|
316
|
+
const anchor = await provider.uploadAnchor(imageBuffer, `${item.id}.png`, config);
|
|
317
|
+
const video = await provider.genVideo(
|
|
318
|
+
{ imageUrl: anchor.url, prompt: motionPrompt, resolution: config.resolution },
|
|
319
|
+
config
|
|
320
|
+
);
|
|
321
|
+
const outDir = config.outDir ?? mkdtempSync(join(tmpdir(), "showreel-replicate-"));
|
|
322
|
+
const clipPath = join(outDir, `${item.id}.mp4`);
|
|
323
|
+
writeFileSync(clipPath, video.buffer);
|
|
324
|
+
return { clipPath, durationMs: item.duration };
|
|
325
|
+
}
|
|
326
|
+
var DEFAULT_FPS = 30;
|
|
327
|
+
function replicateAnimeStillVisualRenderer(config = {}) {
|
|
328
|
+
const provider = config.provider ?? replicateProvider;
|
|
329
|
+
const maxRetries = config.maxRetries ?? 2;
|
|
330
|
+
const storeOutDir = defaultStoreOutDir(config.store);
|
|
331
|
+
const raw = {
|
|
332
|
+
async renderScene(item, brand) {
|
|
333
|
+
return withRetry(maxRetries, () => renderOneStillScene(provider, config, storeOutDir, item, brand));
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
const cacheOpt = config.cache ?? (config.store ? false : {});
|
|
337
|
+
return cacheOpt === false ? raw : cachingVisualRenderer(raw, cacheOpt);
|
|
338
|
+
}
|
|
339
|
+
async function renderOneStillScene(provider, config, storeOutDir, item, _brand) {
|
|
340
|
+
const { buffer: imageBuffer } = await resolveSceneImage(provider, config, config.store, storeOutDir, item);
|
|
341
|
+
const outDir = config.outDir ?? mkdtempSync(join(tmpdir(), "showreel-replicate-still-"));
|
|
342
|
+
const stillPath = join(outDir, `${item.id}-still.png`);
|
|
343
|
+
writeFileSync(stillPath, imageBuffer);
|
|
344
|
+
const clipPath = join(outDir, `${item.id}.mp4`);
|
|
345
|
+
await encodeStillToMp4(stillPath, item.duration, config.fps ?? DEFAULT_FPS, clipPath);
|
|
346
|
+
return { clipPath, durationMs: item.duration };
|
|
347
|
+
}
|
|
348
|
+
function encodeStillToMp4(stillPath, durationMs, fps, outPath) {
|
|
349
|
+
return new Promise((resolvePromise, reject) => {
|
|
350
|
+
const ff = spawn(
|
|
351
|
+
"ffmpeg",
|
|
352
|
+
[
|
|
353
|
+
"-y",
|
|
354
|
+
"-loop",
|
|
355
|
+
"1",
|
|
356
|
+
"-i",
|
|
357
|
+
stillPath,
|
|
358
|
+
"-t",
|
|
359
|
+
String(durationMs / 1e3),
|
|
360
|
+
"-r",
|
|
361
|
+
String(fps),
|
|
362
|
+
"-pix_fmt",
|
|
363
|
+
"yuv420p",
|
|
364
|
+
// even dimensions — a generated PNG's size may be odd, and
|
|
365
|
+
// yuv420p requires width/height divisible by 2
|
|
366
|
+
"-vf",
|
|
367
|
+
"scale=trunc(iw/2)*2:trunc(ih/2)*2",
|
|
368
|
+
outPath
|
|
369
|
+
],
|
|
370
|
+
{ stdio: ["ignore", "ignore", "pipe"] }
|
|
371
|
+
);
|
|
372
|
+
let stderr = "";
|
|
373
|
+
ff.stderr.on("data", (chunk) => {
|
|
374
|
+
stderr += chunk.toString();
|
|
375
|
+
});
|
|
376
|
+
ff.on("error", reject);
|
|
377
|
+
ff.on("close", (code) => {
|
|
378
|
+
if (code === 0) resolvePromise();
|
|
379
|
+
else reject(new Error(`encodeStillToMp4: ffmpeg exited ${String(code)}: ${stderr.slice(-500)}`));
|
|
380
|
+
});
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
var RendererRegistry = class {
|
|
384
|
+
#styles = /* @__PURE__ */ new Map();
|
|
385
|
+
register(style) {
|
|
386
|
+
this.#styles.set(style.name, style);
|
|
387
|
+
}
|
|
388
|
+
has(name) {
|
|
389
|
+
return this.#styles.has(name);
|
|
390
|
+
}
|
|
391
|
+
/** Resolve a style name to a fresh `VisualRenderer` instance. Never throws — an unknown name warns and returns `null`. */
|
|
392
|
+
resolve(name, config) {
|
|
393
|
+
const style = this.#styles.get(name);
|
|
394
|
+
if (!style) {
|
|
395
|
+
console.warn(
|
|
396
|
+
`[canvakit-showreel-replicate] No reel style registered for "${name}". Register one via RendererRegistry.register() or use a built-in (replicate-anime, html-still, agentic).`
|
|
397
|
+
);
|
|
398
|
+
return null;
|
|
399
|
+
}
|
|
400
|
+
return style.makeRenderer(config);
|
|
401
|
+
}
|
|
402
|
+
/** Every registered style name, sorted. */
|
|
403
|
+
list() {
|
|
404
|
+
return [...this.#styles.keys()].sort();
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
function createDefaultRendererRegistry() {
|
|
408
|
+
const registry = new RendererRegistry();
|
|
409
|
+
registry.register({
|
|
410
|
+
name: "replicate-anime",
|
|
411
|
+
makeRenderer: (config) => replicateAnimeVisualRenderer(config)
|
|
412
|
+
});
|
|
413
|
+
registry.register({
|
|
414
|
+
name: "replicate-anime-still",
|
|
415
|
+
makeRenderer: (config) => replicateAnimeStillVisualRenderer(config)
|
|
416
|
+
});
|
|
417
|
+
registry.register({
|
|
418
|
+
name: "html-still",
|
|
419
|
+
makeRenderer: () => htmlStillVisualRenderer
|
|
420
|
+
});
|
|
421
|
+
registry.register({
|
|
422
|
+
name: "agentic",
|
|
423
|
+
makeRenderer: (config) => agenticVisualRenderer(config)
|
|
424
|
+
});
|
|
425
|
+
return registry;
|
|
426
|
+
}
|
|
427
|
+
var defaultRendererRegistry = createDefaultRendererRegistry();
|
|
428
|
+
function resolveReelStyle(name, config) {
|
|
429
|
+
return defaultRendererRegistry.resolve(name, config);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
export { DEFAULT_IMAGE_MODEL, RendererRegistry, ReplicatePredictionError, buildSplitScreenImagePrompt, clearAssetStale, computeSourceHash, createDefaultRendererRegistry, createEmptyManifest, defaultRendererRegistry, editAsset, genImage, genVideo, loadManifest, replicateAnimeStillVisualRenderer, replicateAnimeVisualRenderer, replicateProvider, resolveImageAsset, resolveReelStyle, resolveReplicateApiKey, saveManifest, uploadAnchor };
|
|
433
|
+
//# sourceMappingURL=index.mjs.map
|
|
434
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/provider.ts","../src/manifest.ts","../src/scene-image.ts","../src/renderer.ts","../src/still-renderer.ts","../src/registry.ts"],"names":["readFileSync","dirname","join","mkdtempSync","tmpdir","writeFileSync","cachingVisualRenderer"],"mappings":";;;;;;;;;;;;;AAkBA,IAAM,wBAAA,GAA2B,IAAA;AACjC,IAAM,wBAAA,GAA2B,IAAA;AACjC,IAAM,wBAAA,GAA2B,GAAA;AACjC,IAAM,WAAA,GAAc,oBAAA;AACpB,IAAM,WAAA,GAAc,wBAAA;AAiDb,IAAM,wBAAA,GAAN,cAAuC,KAAA,CAAM;AAAA,EAClD,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,0BAAA;AAAA,EACd;AACF;AAGO,SAAS,uBAAuB,MAAA,EAA0C;AAC/E,EAAA,IAAI,MAAA,EAAQ,MAAA,EAAQ,OAAO,MAAA,CAAO,MAAA;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wD;AAAA,GAC9G,CAAA;AACD,EAAA,QAAA,CAAS,QAAA,CAAS;AAAA,IAChB,IAAA,EAAM,uBAAA;AAAA,IACN,YAAA,EAAc,CAAA,MAAA,KACZ,iCAAA,CAAkC,MAA6D;AAAA,GAClG,CAAA;AACD,EAAA,QAAA,CAAS,QAAA,CAAS;AAAA,IAChB,IAAA,EAAM,YAAA;AAAA,IACN,cAAc,MAAM;AAAA,GACrB,CAAA;AACD,EAAA,QAAA,CAAS,QAAA,CAAS;AAAA,IAChB,IAAA,EAAM,SAAA;AAAA,IACN,YAAA,EAAc,CAAA,MAAA,KAAU,qBAAA,CAAsB,MAAiD;AAAA,GAChG,CAAA;AACD,EAAA,OAAO,QAAA;AACT;AAGO,IAAM,0BAA4C,6BAAA;AAGlD,SAAS,gBAAA,CAAiB,MAAc,MAAA,EAAyC;AACtF,EAAA,OAAO,uBAAA,CAAwB,OAAA,CAAQ,IAAA,EAAM,MAAM,CAAA;AACrD","file":"index.mjs","sourcesContent":["/**\n * @canvakit/showreel-replicate — the Replicate provider primitives.\n *\n * Ports `.claude/skills/agentik-pitch-video/gen.mjs`'s `gen` / `video` /\n * `upload` verbs to plain in-process async functions: `genImage`\n * (openai/gpt-image-2, 16:9/high/png, `input_images` for cast/face\n * coherence), `uploadAnchor` (Replicate Files API — `replicate.delivery`\n * output URLs expire ~1h, so a cast/face anchor is re-hosted to survive a\n * multi-beat run), `genVideo` (bytedance/seedance-2.0, image→video,\n * `generate_audio:false`). The gen.mjs nohup/detached/logfile choreography\n * existed only because the cowork Bash sandbox blocks outbound network\n * (`gen.mjs:5-12`); this runs in the host node process, so it's dropped.\n * The `poll()` loop stays — Replicate predictions are inherently async.\n */\n\nimport { readFileSync } from \"node:fs\"\nimport { dirname, join } from \"node:path\"\n\nconst DEFAULT_POLL_INTERVAL_MS = 3500\nconst DEFAULT_IMAGE_TIMEOUT_MS = 180_000\nconst DEFAULT_VIDEO_TIMEOUT_MS = 600_000\nconst IMAGE_MODEL = \"openai/gpt-image-2\"\nconst VIDEO_MODEL = \"bytedance/seedance-2.0\"\n\nexport interface ReplicateProviderConfig {\n /** Overrides REPLICATE_API_TOKEN / REPLICATE_AI_API_KEY / .envrc resolution. */\n apiKey?: string\n pollIntervalMs?: number\n imageTimeoutMs?: number\n videoTimeoutMs?: number\n}\n\nexport interface GenImageInput {\n prompt: string\n /** stable anchor URLs (cast/face lock) — passed as `input_images`. */\n refs?: string[]\n}\n\nexport interface GenImageResult {\n /** the generated image bytes (png). */\n buffer: Buffer\n /** replicate.delivery output URL — expires ~1h, re-host via `uploadAnchor`. */\n url: string\n}\n\nexport interface UploadAnchorResult {\n /** stable Files API URL, usable as `input_images` / `image` across beats. */\n url: string\n}\n\nexport interface GenVideoInput {\n /** the anchor image URL (from `uploadAnchor`) driving the animation. */\n imageUrl: string\n prompt: string\n resolution?: string\n}\n\nexport interface GenVideoResult {\n /** the generated clip bytes (mp4). */\n buffer: Buffer\n url: string\n}\n\n/** The provider surface `replicateAnimeVisualRenderer` depends on — injectable for tests. */\nexport interface ReplicateProvider {\n genImage(input: GenImageInput, config?: ReplicateProviderConfig): Promise<GenImageResult>\n uploadAnchor(buffer: Buffer, filename: string, config?: ReplicateProviderConfig): Promise<UploadAnchorResult>\n genVideo(input: GenVideoInput, config?: ReplicateProviderConfig): Promise<GenVideoResult>\n}\n\n/** Raised when a Replicate prediction fails, is canceled, or times out. */\nexport class ReplicatePredictionError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"ReplicatePredictionError\"\n }\n}\n\n/** Resolution order: explicit config → env vars → the nearest `.envrc` walking up from cwd. */\nexport function resolveReplicateApiKey(config?: ReplicateProviderConfig): string {\n if (config?.apiKey) return config.apiKey\n if (process.env.REPLICATE_API_TOKEN) return process.env.REPLICATE_API_TOKEN\n if (process.env.REPLICATE_AI_API_KEY) return process.env.REPLICATE_AI_API_KEY\n\n const envrc = findEnvrc(process.cwd())\n if (envrc) {\n const text = readFileSync(envrc, \"utf8\")\n const match = /REPLICATE(?:_AI)?_API_(?:TOKEN|KEY)[=: ]+['\"]?([A-Za-z0-9_]+)/.exec(text)\n if (match?.[1]) return match[1]\n }\n\n throw new Error(\n \"resolveReplicateApiKey: no Replicate key — set REPLICATE_API_TOKEN / REPLICATE_AI_API_KEY, \" +\n \"pass config.apiKey, or add one to a .envrc.\"\n )\n}\n\nfunction findEnvrc(start: string): string | null {\n let dir = start\n for (let i = 0; i < 8; i++) {\n const candidate = join(dir, \".envrc\")\n try {\n readFileSync(candidate, \"utf8\")\n return candidate\n } catch {\n // not found at this level — keep walking up\n }\n const up = dirname(dir)\n if (up === dir) break\n dir = up\n }\n return null\n}\n\ninterface ReplicatePrediction {\n id: string\n status: \"starting\" | \"processing\" | \"succeeded\" | \"failed\" | \"canceled\"\n output?: unknown\n error?: unknown\n urls: { get: string }\n}\n\nasync function poll(\n getUrl: string,\n apiKey: string,\n maxMs: number,\n pollIntervalMs: number\n): Promise<ReplicatePrediction> {\n const deadline = Date.now() + maxMs\n for (;;) {\n if (Date.now() > deadline) {\n throw new ReplicatePredictionError(`poll: timed out after ${String(maxMs)}ms waiting on ${getUrl}`)\n }\n await sleep(pollIntervalMs)\n const response = await fetch(getUrl, { headers: { Authorization: `Bearer ${apiKey}` } })\n const pred = (await response.json()) as ReplicatePrediction\n if (pred.status === \"succeeded\" || pred.status === \"failed\" || pred.status === \"canceled\") {\n return pred\n }\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise(resolvePromise => setTimeout(resolvePromise, ms))\n}\n\n/** Create a prediction, poll it to completion, and download its output bytes. */\nasync function runPrediction(\n model: string,\n input: Record<string, unknown>,\n apiKey: string,\n maxMs: number,\n pollIntervalMs: number\n): Promise<{ buffer: Buffer; url: string }> {\n const createResponse = await fetch(`https://api.replicate.com/v1/models/${model}/predictions`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({ input }),\n })\n if (!createResponse.ok) {\n const body = await createResponse.text().catch(() => \"\")\n throw new ReplicatePredictionError(\n `runPrediction: ${model} create failed (${String(createResponse.status)}): ${body.slice(0, 1000)}`\n )\n }\n const created = (await createResponse.json()) as ReplicatePrediction\n const pred = await poll(created.urls.get, apiKey, maxMs, pollIntervalMs)\n\n if (pred.status !== \"succeeded\") {\n throw new ReplicatePredictionError(\n `runPrediction: ${model} prediction ${pred.status} — ${JSON.stringify(pred.error ?? pred).slice(0, 1000)}`\n )\n }\n\n const url = Array.isArray(pred.output) ? (pred.output[0] as string) : (pred.output as string)\n const download = await fetch(url)\n if (!download.ok) {\n throw new ReplicatePredictionError(\n `runPrediction: downloading ${model} output failed (${String(download.status)})`\n )\n }\n const buffer = Buffer.from(await download.arrayBuffer())\n return { buffer, url }\n}\n\n/** `genImage` — openai/gpt-image-2, 16:9/high/png, `input_images` for cast/face coherence. */\nexport async function genImage(\n input: GenImageInput,\n config: ReplicateProviderConfig = {}\n): Promise<GenImageResult> {\n const apiKey = resolveReplicateApiKey(config)\n const modelInput: Record<string, unknown> = {\n prompt: input.prompt,\n aspect_ratio: \"16:9\",\n quality: \"high\",\n output_format: \"png\",\n }\n if (input.refs?.length) modelInput.input_images = input.refs\n\n const { buffer, url } = await runPrediction(\n IMAGE_MODEL,\n modelInput,\n apiKey,\n config.imageTimeoutMs ?? DEFAULT_IMAGE_TIMEOUT_MS,\n config.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS\n )\n return { buffer, url }\n}\n\n/** `uploadAnchor` — Replicate Files API (multipart), re-hosts a local image to a stable URL. */\nexport async function uploadAnchor(\n buffer: Buffer,\n filename: string,\n config: ReplicateProviderConfig = {}\n): Promise<UploadAnchorResult> {\n const apiKey = resolveReplicateApiKey(config)\n const mime = filename.endsWith(\".png\")\n ? \"image/png\"\n : filename.endsWith(\".jpg\") || filename.endsWith(\".jpeg\")\n ? \"image/jpeg\"\n : \"application/octet-stream\"\n\n const form = new FormData()\n form.append(\"content\", new Blob([new Uint8Array(buffer)], { type: mime }), filename)\n\n const response = await fetch(\"https://api.replicate.com/v1/files\", {\n method: \"POST\",\n headers: { Authorization: `Bearer ${apiKey}` },\n body: form,\n })\n if (!response.ok) {\n const body = await response.text().catch(() => \"\")\n throw new ReplicatePredictionError(`uploadAnchor: upload failed (${String(response.status)}): ${body.slice(0, 800)}`)\n }\n const parsed = (await response.json()) as { urls?: { get?: string } }\n const url = parsed.urls?.get\n if (!url) {\n throw new ReplicatePredictionError(\"uploadAnchor: response had no urls.get\")\n }\n return { url }\n}\n\n/** `genVideo` — bytedance/seedance-2.0, image→video, `duration:5`, `generate_audio:false`. */\nexport async function genVideo(\n input: GenVideoInput,\n config: ReplicateProviderConfig = {}\n): Promise<GenVideoResult> {\n const apiKey = resolveReplicateApiKey(config)\n const modelInput: Record<string, unknown> = {\n image: input.imageUrl,\n prompt: input.prompt,\n duration: 5,\n resolution: input.resolution ?? \"480p\",\n aspect_ratio: \"adaptive\",\n generate_audio: false,\n }\n\n const { buffer, url } = await runPrediction(\n VIDEO_MODEL,\n modelInput,\n apiKey,\n config.videoTimeoutMs ?? DEFAULT_VIDEO_TIMEOUT_MS,\n config.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS\n )\n return { buffer, url }\n}\n\n/** The real Replicate provider — `genImage`/`uploadAnchor`/`genVideo` bound together. */\nexport const replicateProvider: ReplicateProvider = { genImage, uploadAnchor, genVideo }\n","/**\n * @canvakit/showreel-replicate — the ID'd asset manifest.\n *\n * A human-addressable index (`<projectDir>/assets.json`) over the\n * content-addressed Replicate images this package generates: a stable id\n * (e.g. \"beat-03\", or \"beat-03-panel2\" for a sub-asset) maps to\n * `{ prompt, refs, model, filePath, sourceHash, ... }`. `resolveImageAsset`\n * is the reuse gate every `genImage` call goes through — a Replicate call\n * only happens when no entry exists for the id, or its `sourceHash`\n * (prompt+refs+model) no longer matches what's stored. `editAsset` lets a\n * human regenerate exactly one entry by id, without touching any other\n * asset, and marks it `stale` so the render pipeline knows a clip produced\n * from the pre-edit image needs redoing.\n *\n * This is the NAMED index; `cachingVisualRenderer` (`@canvakit/showreel`'s\n * `renderer/cache.js`) stays the underlying content-addressed BYTE store\n * for whole rendered clips — the two are independent, complementary layers.\n */\n\nimport { createHash } from \"node:crypto\"\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\"\nimport { dirname, join } from \"node:path\"\n\nimport type { GenImageInput, ReplicateProvider, ReplicateProviderConfig } from \"./provider.js\"\n\n/** The image model `resolveImageAsset`/`editAsset` assume when the caller doesn't say otherwise. */\nexport const DEFAULT_IMAGE_MODEL = \"openai/gpt-image-2\"\n\nexport interface AssetManifestEntry {\n /** stable, human-addressable id — e.g. \"beat-03\" or \"beat-03-panel2\". Never an opaque hash. */\n id: string\n /** the ShowreelConfig timeline item this asset belongs to. */\n beatId: string\n kind: \"image\"\n prompt: string\n refs: string[]\n model: string\n /** absolute path to the generated PNG on disk. */\n filePath: string\n /** the Replicate output URL from the generating prediction (expires ~1h — `filePath` is the durable copy). */\n replicateUrl?: string\n createdAt: string\n /** content hash over prompt+refs+model — the reuse/invalidation key. */\n sourceHash: string\n /** set by `editAsset` — the image itself is current, but a clip rendered before this edit is not. */\n stale?: boolean\n}\n\nexport interface AssetManifest {\n version: 1\n assets: Record<string, AssetManifestEntry>\n}\n\nexport function createEmptyManifest(): AssetManifest {\n return { version: 1, assets: {} }\n}\n\n/** Read a manifest from disk. A missing file yields a fresh empty manifest — never throws on ENOENT. */\nexport function loadManifest(path: string): AssetManifest {\n try {\n const raw = readFileSync(path, \"utf8\")\n const parsed = JSON.parse(raw) as Partial<AssetManifest>\n return { version: 1, assets: parsed.assets ?? {} }\n } catch (err) {\n if (isEnoent(err)) return createEmptyManifest()\n throw err\n }\n}\n\n/** Persist a manifest to disk, creating its parent directory as needed. */\nexport function saveManifest(path: string, manifest: AssetManifest): void {\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, `${JSON.stringify(manifest, null, 2)}\\n`)\n}\n\nfunction isEnoent(err: unknown): boolean {\n return err instanceof Error && (err as NodeJS.ErrnoException).code === \"ENOENT\"\n}\n\n/** Content hash over exactly what determines an image's pixels — prompt + refs + model. */\nexport function computeSourceHash(input: { prompt: string; refs: string[]; model: string }): string {\n const payload = JSON.stringify({ prompt: input.prompt, refs: input.refs, model: input.model })\n return createHash(\"sha256\").update(payload).digest(\"hex\")\n}\n\nexport interface ResolveImageAssetInput {\n manifest: AssetManifest\n /** stable, human-addressable id — e.g. \"beat-03\" or \"beat-03-panel2\". */\n id: string\n beatId: string\n prompt: string\n refs?: string[]\n model?: string\n provider: Pick<ReplicateProvider, \"genImage\">\n providerConfig?: ReplicateProviderConfig\n /** directory a freshly generated PNG is written to. */\n outDir: string\n}\n\nexport interface ResolveImageAssetResult {\n entry: AssetManifestEntry\n buffer: Buffer\n /** true when an existing manifest entry's `sourceHash` matched — zero `genImage` calls were made. */\n reused: boolean\n}\n\n/**\n * The manifest-aware reuse gate `genImage` calls go through: an id whose\n * stored `sourceHash` still matches (and whose file still exists) is served\n * straight off disk — zero Replicate calls. Anything else generates once\n * and upserts the entry.\n */\nexport async function resolveImageAsset(input: ResolveImageAssetInput): Promise<ResolveImageAssetResult> {\n const refs = input.refs ?? []\n const model = input.model ?? DEFAULT_IMAGE_MODEL\n const sourceHash = computeSourceHash({ prompt: input.prompt, refs, model })\n\n const existing = input.manifest.assets[input.id]\n if (existing && existing.sourceHash === sourceHash && existsSync(existing.filePath)) {\n return { entry: existing, buffer: readFileSync(existing.filePath), reused: true }\n }\n\n const genInput: GenImageInput = { prompt: input.prompt, refs: refs.length ? refs : undefined }\n const image = await input.provider.genImage(genInput, input.providerConfig)\n\n mkdirSync(input.outDir, { recursive: true })\n const filePath = join(input.outDir, `${input.id}.png`)\n writeFileSync(filePath, image.buffer)\n\n const entry: AssetManifestEntry = {\n id: input.id,\n beatId: input.beatId,\n kind: \"image\",\n prompt: input.prompt,\n refs,\n model,\n filePath,\n replicateUrl: image.url,\n createdAt: new Date().toISOString(),\n sourceHash,\n stale: false,\n }\n input.manifest.assets[input.id] = entry\n return { entry, buffer: image.buffer, reused: false }\n}\n\nexport interface EditAssetOverrides {\n imagePrompt?: string\n refs?: string[]\n}\n\nexport interface EditAssetOptions {\n provider: Pick<ReplicateProvider, \"genImage\">\n providerConfig?: ReplicateProviderConfig\n /** directory the regenerated PNG is written to. Defaults to the existing entry's own directory. */\n outDir?: string\n}\n\n/**\n * Regenerate exactly ONE asset by id — the only `genImage` call this makes\n * — and upsert its entry (new prompt/refs/sourceHash/file). Every other\n * manifest entry is left untouched. Marks the entry `stale: true`: the\n * image is now current, but a clip rendered from the pre-edit image is not,\n * so the render pipeline should redo that beat's clip on its next pass.\n */\nexport async function editAsset(\n manifest: AssetManifest,\n id: string,\n overrides: EditAssetOverrides,\n opts: EditAssetOptions\n): Promise<AssetManifestEntry> {\n const existing = manifest.assets[id]\n if (!existing) {\n throw new Error(`editAsset: no asset \"${id}\" in the manifest — resolveImageAsset it at least once first.`)\n }\n\n const prompt = overrides.imagePrompt ?? existing.prompt\n const refs = overrides.refs ?? existing.refs\n const sourceHash = computeSourceHash({ prompt, refs, model: existing.model })\n\n const genInput: GenImageInput = { prompt, refs: refs.length ? refs : undefined }\n const image = await opts.provider.genImage(genInput, opts.providerConfig)\n\n const outDir = opts.outDir ?? dirname(existing.filePath)\n mkdirSync(outDir, { recursive: true })\n const filePath = join(outDir, `${id}.png`)\n writeFileSync(filePath, image.buffer)\n\n const entry: AssetManifestEntry = {\n ...existing,\n prompt,\n refs,\n filePath,\n replicateUrl: image.url,\n createdAt: new Date().toISOString(),\n sourceHash,\n stale: true,\n }\n manifest.assets[id] = entry\n return entry\n}\n\n/** Clear an entry's `stale` marker once its downstream clip has been redone. */\nexport function clearAssetStale(manifest: AssetManifest, id: string): void {\n const existing = manifest.assets[id]\n if (existing) existing.stale = false\n}\n","/**\n * @canvakit/showreel-replicate — shared scene→image resolution.\n *\n * Both reel styles (`replicateAnimeVisualRenderer` video,\n * `replicateAnimeStillVisualRenderer` still) turn a `SceneItem.data` into an\n * image the exact same way: build the (possibly multi-panel) `imagePrompt`,\n * then resolve the bytes either directly via `provider.genImage` or, when a\n * `ManifestStoreConfig` is supplied, through `resolveImageAsset` so a\n * storyboard render, a still render, and a video render of the same beat\n * all reuse the identical generated image. Written once here so neither\n * renderer duplicates the Replicate call / split-screen prompt logic.\n */\n\nimport { mkdtempSync } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport { join } from \"node:path\"\n\nimport type { SceneItem } from \"@canvakit/showreel\"\n\nimport { resolveImageAsset } from \"./manifest.js\"\nimport type { AssetManifest } from \"./manifest.js\"\nimport type { ReplicateProvider, ReplicateProviderConfig } from \"./provider.js\"\n\n/** `SceneItem.data` shape the replicate-anime styles read — renderer-agnostic (video and still share it). */\nexport interface ReplicateAnimeSceneData {\n imagePrompt?: string\n motionPrompt: string\n /** cast/face-lock anchor URLs, passed to `genImage` as `input_images`. */\n refs?: string[]\n /** when \"split-screen\", `imagePrompt` is built from `panels` instead of used directly. */\n layout?: \"split-screen\"\n panels?: string[]\n}\n\n/** Where a `VisualRenderer` persists/reuses generated images by human-addressable id — see `manifest.ts`. */\nexport interface ManifestStoreConfig {\n manifest: AssetManifest\n /** directory freshly generated PNGs are written to. Defaults to a fresh tmp dir per renderer instance. */\n outDir?: string\n /** when set, the manifest is written back to disk after every resolve. */\n manifestPath?: string\n}\n\n/**\n * Compose a single multi-panel `imagePrompt` from `data.panels` — a\n * mechanical, brand-agnostic triptych/split-screen instruction gpt-image-2\n * can render as one 16:9 frame. Falls back to `data.imagePrompt` when no\n * panels are given (so a `layout:\"split-screen\"` beat with a pre-composed\n * prompt still works without change).\n */\nexport function buildSplitScreenImagePrompt(\n data: Pick<ReplicateAnimeSceneData, \"imagePrompt\" | \"panels\">\n): string {\n const panels = data.panels ?? []\n if (panels.length === 0) return data.imagePrompt ?? \"\"\n\n const panelLines = panels.map((panel, index) => `${String(index + 1)}) ${panel}`).join(\"; \")\n const intro = data.imagePrompt ? `${data.imagePrompt} — ` : \"\"\n return (\n `${intro}a single 16:9 frame split into ${String(panels.length)} vertical panels, ` +\n `each rendered in the same consistent art style: ${panelLines}.`\n )\n}\n\nexport function requireString(value: unknown, sceneId: string, field: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new Error(`showreel-replicate: scene \"${sceneId}\" is missing data.${field}`)\n }\n return value\n}\n\nexport async function withRetry<T>(maxRetries: number, fn: () => Promise<T>): Promise<T> {\n let lastError: unknown\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await fn()\n } catch (err) {\n lastError = err\n }\n }\n throw lastError instanceof Error ? lastError : new Error(String(lastError))\n}\n\nexport interface ResolvedSceneImage {\n buffer: Buffer\n imagePrompt: string\n}\n\n/** Default lazily-created output dir for a renderer instance's manifest-store images. */\nexport function defaultStoreOutDir(store: ManifestStoreConfig | undefined): string | undefined {\n if (!store) return undefined\n return store.outDir ?? mkdtempSync(join(tmpdir(), \"showreel-replicate-assets-\"))\n}\n\n/** Build the scene's imagePrompt and resolve its image bytes — direct `genImage`, or manifest-store-mediated. */\nexport async function resolveSceneImage(\n provider: Pick<ReplicateProvider, \"genImage\">,\n providerConfig: ReplicateProviderConfig | undefined,\n store: ManifestStoreConfig | undefined,\n storeOutDir: string | undefined,\n item: SceneItem\n): Promise<ResolvedSceneImage> {\n const data = item.data as unknown as ReplicateAnimeSceneData\n const imagePrompt =\n data.layout === \"split-screen\"\n ? buildSplitScreenImagePrompt(data)\n : requireString(data.imagePrompt, item.id, \"imagePrompt\")\n const refs = Array.isArray(data.refs) ? data.refs.filter((ref): ref is string => typeof ref === \"string\") : undefined\n\n if (store) {\n const result = await resolveImageAsset({\n manifest: store.manifest,\n id: item.id,\n beatId: item.id,\n prompt: imagePrompt,\n refs,\n provider,\n providerConfig,\n outDir: storeOutDir ?? mkdtempSync(join(tmpdir(), \"showreel-replicate-assets-\")),\n })\n return { buffer: result.buffer, imagePrompt }\n }\n\n const image = await provider.genImage({ prompt: imagePrompt, refs }, providerConfig)\n return { buffer: image.buffer, imagePrompt }\n}\n","/**\n * @canvakit/showreel-replicate — `replicateAnimeVisualRenderer`.\n *\n * Installs the Replicate pipeline as a `VisualRenderer` for\n * `@canvakit/showreel` (see `renderer/index.ts` in that package):\n * `renderScene` resolves the scene's image via `resolveSceneImage` (direct\n * `genImage`, or manifest-store-mediated — see `scene-image.ts`), then runs\n * `uploadAnchor → genVideo` (the anchor re-host beats the ~1h\n * `replicate.delivery` expiry across a multi-beat run) and returns\n * `{ clipPath, durationMs: item.duration }` — assembly conforms the real\n * ~5s clip to the declared slot, same contract the html-still and agentic\n * renderers honor. Wrapped in `cachingVisualRenderer` by default (unless a\n * manifest `store` is configured, in which case the store's per-image reuse\n * is the primary cache and the clip is re-encoded fresh each render) so a\n * re-run only regenerates beats whose prompt/data actually changed.\n */\n\nimport { mkdtempSync, writeFileSync } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport { join } from \"node:path\"\n\nimport { cachingVisualRenderer } from \"@canvakit/showreel\"\nimport type { Brand, RenderedClip, SceneCacheOptions, SceneItem, VisualRenderer } from \"@canvakit/showreel\"\n\nimport { replicateProvider } from \"./provider.js\"\nimport type { ReplicateProvider, ReplicateProviderConfig } from \"./provider.js\"\nimport { defaultStoreOutDir, requireString, resolveSceneImage, withRetry } from \"./scene-image.js\"\nimport type { ManifestStoreConfig, ReplicateAnimeSceneData } from \"./scene-image.js\"\n\nexport { buildSplitScreenImagePrompt } from \"./scene-image.js\"\nexport type { ManifestStoreConfig, ReplicateAnimeSceneData } from \"./scene-image.js\"\n\nexport interface ReplicateAnimeVisualRendererConfig extends ReplicateProviderConfig {\n /** Injectable provider — the real Replicate one by default, a fake in tests. */\n provider?: ReplicateProvider\n /** Per-beat retry count on a transient Replicate/network failure. Default 2. */\n maxRetries?: number\n /** seedance output resolution. Default \"480p\" (mirrors gen.mjs). */\n resolution?: string\n /** Where rendered clips land; defaults to a fresh tmp dir. */\n outDir?: string\n /** Content-addressed cache wrapping (see `cachingVisualRenderer`). `false` disables it. Defaults to `false` when `store` is set — the manifest is the reuse layer then. */\n cache?: SceneCacheOptions | false\n /** ID'd asset manifest — reuses the same generated image a storyboard/still render already produced for this beat. */\n store?: ManifestStoreConfig\n}\n\n/** A `VisualRenderer` where each scene clip is produced via Replicate (image → anchor → video). */\nexport function replicateAnimeVisualRenderer(\n config: ReplicateAnimeVisualRendererConfig = {}\n): VisualRenderer {\n const provider = config.provider ?? replicateProvider\n const maxRetries = config.maxRetries ?? 2\n const storeOutDir = defaultStoreOutDir(config.store)\n\n const raw: VisualRenderer = {\n async renderScene(item: SceneItem, brand: Brand): Promise<RenderedClip> {\n return withRetry(maxRetries, () => renderOneScene(provider, config, storeOutDir, item, brand))\n },\n }\n\n const cacheOpt = config.cache ?? (config.store ? false : {})\n return cacheOpt === false ? raw : cachingVisualRenderer(raw, cacheOpt)\n}\n\nasync function renderOneScene(\n provider: ReplicateProvider,\n config: ReplicateAnimeVisualRendererConfig,\n storeOutDir: string | undefined,\n item: SceneItem,\n _brand: Brand\n): Promise<RenderedClip> {\n const data = item.data as unknown as ReplicateAnimeSceneData\n const motionPrompt = requireString(data.motionPrompt, item.id, \"motionPrompt\")\n\n const { buffer: imageBuffer } = await resolveSceneImage(provider, config, config.store, storeOutDir, item)\n\n const anchor = await provider.uploadAnchor(imageBuffer, `${item.id}.png`, config)\n const video = await provider.genVideo(\n { imageUrl: anchor.url, prompt: motionPrompt, resolution: config.resolution },\n config\n )\n\n const outDir = config.outDir ?? mkdtempSync(join(tmpdir(), \"showreel-replicate-\"))\n const clipPath = join(outDir, `${item.id}.mp4`)\n writeFileSync(clipPath, video.buffer)\n\n return { clipPath, durationMs: item.duration }\n}\n","/**\n * @canvakit/showreel-replicate — `replicateAnimeStillVisualRenderer`.\n *\n * The still/pre-render counterpart to `replicateAnimeVisualRenderer`:\n * resolves the SAME `SceneItem.data → imagePrompt` (split-screen included)\n * through `resolveSceneImage` — reusing `genImage` + the manifest-aware\n * asset store, so a still render and a video render of the same beat share\n * the identical generated image — then encodes the still directly to an\n * exact-duration mp4 via ffmpeg (`-loop 1 -t <durationMs/1000>`, mirroring\n * `@canvakit/showreel`'s own `encodeStillToMp4`). No `genVideo` call — a\n * still beat never animates.\n */\n\nimport { spawn } from \"node:child_process\"\nimport { mkdtempSync, writeFileSync } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport { join } from \"node:path\"\n\nimport { cachingVisualRenderer } from \"@canvakit/showreel\"\nimport type { Brand, RenderedClip, SceneCacheOptions, SceneItem, VisualRenderer } from \"@canvakit/showreel\"\n\nimport { replicateProvider } from \"./provider.js\"\nimport type { ReplicateProvider, ReplicateProviderConfig } from \"./provider.js\"\nimport { defaultStoreOutDir, resolveSceneImage, withRetry } from \"./scene-image.js\"\nimport type { ManifestStoreConfig } from \"./scene-image.js\"\n\nexport interface ReplicateAnimeStillVisualRendererConfig extends ReplicateProviderConfig {\n /** Injectable provider — only `genImage` is called. The real Replicate one by default, a fake in tests. */\n provider?: Pick<ReplicateProvider, \"genImage\">\n /** Per-beat retry count on a transient Replicate/network failure. Default 2. */\n maxRetries?: number\n /** ffmpeg output framerate. Default 30 (mirrors `@canvakit/showreel`'s html-still renderer). */\n fps?: number\n /** Where rendered clips land; defaults to a fresh tmp dir. */\n outDir?: string\n /** Content-addressed cache wrapping (see `cachingVisualRenderer`). `false` disables it. Defaults to `false` when `store` is set — the manifest is the reuse layer then. */\n cache?: SceneCacheOptions | false\n /** ID'd asset manifest — shared with `replicateAnimeVisualRenderer` so a still and a video render of the same beat reuse the same generated image. */\n store?: ManifestStoreConfig\n}\n\nconst DEFAULT_FPS = 30\n\n/** A `VisualRenderer` where each scene clip is a still (image → exact-duration mp4, no animation). */\nexport function replicateAnimeStillVisualRenderer(\n config: ReplicateAnimeStillVisualRendererConfig = {}\n): VisualRenderer {\n const provider = config.provider ?? replicateProvider\n const maxRetries = config.maxRetries ?? 2\n const storeOutDir = defaultStoreOutDir(config.store)\n\n const raw: VisualRenderer = {\n async renderScene(item: SceneItem, brand: Brand): Promise<RenderedClip> {\n return withRetry(maxRetries, () => renderOneStillScene(provider, config, storeOutDir, item, brand))\n },\n }\n\n const cacheOpt = config.cache ?? (config.store ? false : {})\n return cacheOpt === false ? raw : cachingVisualRenderer(raw, cacheOpt)\n}\n\nasync function renderOneStillScene(\n provider: Pick<ReplicateProvider, \"genImage\">,\n config: ReplicateAnimeStillVisualRendererConfig,\n storeOutDir: string | undefined,\n item: SceneItem,\n _brand: Brand\n): Promise<RenderedClip> {\n const { buffer: imageBuffer } = await resolveSceneImage(provider, config, config.store, storeOutDir, item)\n\n const outDir = config.outDir ?? mkdtempSync(join(tmpdir(), \"showreel-replicate-still-\"))\n const stillPath = join(outDir, `${item.id}-still.png`)\n writeFileSync(stillPath, imageBuffer)\n\n const clipPath = join(outDir, `${item.id}.mp4`)\n await encodeStillToMp4(stillPath, item.duration, config.fps ?? DEFAULT_FPS, clipPath)\n\n return { clipPath, durationMs: item.duration }\n}\n\n/**\n * Encode a single still image into an exact-duration mp4 — mirrors\n * `@canvakit/showreel`'s `renderer/index.ts` `encodeStillToMp4` (the\n * shipped html-still renderer's own last step): `ffmpeg -loop 1 -t\n * <durationMs/1000>`.\n */\nfunction encodeStillToMp4(stillPath: string, durationMs: number, fps: number, outPath: string): Promise<void> {\n return new Promise((resolvePromise, reject) => {\n const ff = spawn(\n \"ffmpeg\",\n [\n \"-y\",\n \"-loop\",\n \"1\",\n \"-i\",\n stillPath,\n \"-t\",\n String(durationMs / 1000),\n \"-r\",\n String(fps),\n \"-pix_fmt\",\n \"yuv420p\",\n // even dimensions — a generated PNG's size may be odd, and\n // yuv420p requires width/height divisible by 2\n \"-vf\",\n \"scale=trunc(iw/2)*2:trunc(ih/2)*2\",\n outPath,\n ],\n { stdio: [\"ignore\", \"ignore\", \"pipe\"] }\n )\n let stderr = \"\"\n ff.stderr.on(\"data\", (chunk: Buffer) => {\n stderr += chunk.toString()\n })\n ff.on(\"error\", reject)\n ff.on(\"close\", code => {\n if (code === 0) resolvePromise()\n else reject(new Error(`encodeStillToMp4: ffmpeg exited ${String(code)}: ${stderr.slice(-500)}`))\n })\n })\n}\n","/**\n * `RendererRegistry` — a reel style is a `VisualRenderer`, picked by name.\n *\n * Mirrors `@canvakit/showreel`'s `SceneTemplateRegistry`\n * (`templates/registry.ts:98-181`) in shape: `register()` / `resolve()` /\n * `list()`, never-throw (an unknown name warns + returns `null`), plus a\n * `createDefault…()` + default-singleton pair. `resolveVisualRenderer({\n * renderer })` (`renderer/index.ts:73-78`) is already the injection hook\n * into `@canvakit/showreel` — this registry only produces that `renderer`\n * argument by name, so a new style plugs in via `register()` with ZERO\n * `@canvakit/showreel` change.\n */\n\nimport { agenticVisualRenderer } from \"@canvakit/showreel-agentic\"\nimport type { AgenticVisualRendererConfig } from \"@canvakit/showreel-agentic\"\nimport { htmlStillVisualRenderer } from \"@canvakit/showreel\"\nimport type { VisualRenderer } from \"@canvakit/showreel\"\n\nimport { replicateAnimeVisualRenderer } from \"./renderer.js\"\nimport type { ReplicateAnimeVisualRendererConfig } from \"./renderer.js\"\nimport { replicateAnimeStillVisualRenderer } from \"./still-renderer.js\"\nimport type { ReplicateAnimeStillVisualRendererConfig } from \"./still-renderer.js\"\n\n/** One reel style: a name, and a factory producing its `VisualRenderer`. */\nexport interface ReelStyle {\n name: string\n makeRenderer(config?: unknown): VisualRenderer\n}\n\nexport class RendererRegistry {\n #styles = new Map<string, ReelStyle>()\n\n register(style: ReelStyle): void {\n this.#styles.set(style.name, style)\n }\n\n has(name: string): boolean {\n return this.#styles.has(name)\n }\n\n /** Resolve a style name to a fresh `VisualRenderer` instance. Never throws — an unknown name warns and returns `null`. */\n resolve(name: string, config?: unknown): VisualRenderer | null {\n const style = this.#styles.get(name)\n if (!style) {\n console.warn(\n `[canvakit-showreel-replicate] No reel style registered for \"${name}\". ` +\n `Register one via RendererRegistry.register() or use a built-in ` +\n `(replicate-anime, html-still, agentic).`\n )\n return null\n }\n return style.makeRenderer(config)\n }\n\n /** Every registered style name, sorted. */\n list(): string[] {\n return [...this.#styles.keys()].sort()\n }\n}\n\n/** Build a registry pre-populated with the built-in styles. */\nexport function createDefaultRendererRegistry(): RendererRegistry {\n const registry = new RendererRegistry()\n registry.register({\n name: \"replicate-anime\",\n makeRenderer: config => replicateAnimeVisualRenderer(config as ReplicateAnimeVisualRendererConfig | undefined),\n })\n registry.register({\n name: \"replicate-anime-still\",\n makeRenderer: config =>\n replicateAnimeStillVisualRenderer(config as ReplicateAnimeStillVisualRendererConfig | undefined),\n })\n registry.register({\n name: \"html-still\",\n makeRenderer: () => htmlStillVisualRenderer,\n })\n registry.register({\n name: \"agentic\",\n makeRenderer: config => agenticVisualRenderer(config as AgenticVisualRendererConfig | undefined),\n })\n return registry\n}\n\n/** Default singleton — `resolveReelStyle` and host storyboard helpers use this. */\nexport const defaultRendererRegistry: RendererRegistry = createDefaultRendererRegistry()\n\n/** Resolve a style name against the default registry. Never throws. */\nexport function resolveReelStyle(name: string, config?: unknown): VisualRenderer | null {\n return defaultRendererRegistry.resolve(name, config)\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,62 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@canvakit/showreel-replicate",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Replicate-backed VisualRenderer bridge for @canvakit/showreel — genImage (gpt-image-2) → uploadAnchor (Files API) → genVideo (seedance) as a pluggable 'replicate-anime' reel style, plus a RendererRegistry vending it alongside the built-in html-still and agentic styles by name.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"canvakit",
|
|
7
|
+
"showreel",
|
|
8
|
+
"replicate",
|
|
9
|
+
"bridge",
|
|
10
|
+
"extension"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://canvakit.sh",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "https://github.com/openagentik/canvakit",
|
|
16
|
+
"directory": "packages/showreel-replicate"
|
|
17
|
+
},
|
|
18
|
+
"bugs": {
|
|
19
|
+
"url": "https://github.com/openagentik/canvakit/issues"
|
|
20
|
+
},
|
|
21
|
+
"license": "FSL-1.1-ALv2",
|
|
22
|
+
"type": "module",
|
|
23
|
+
"main": "dist/index.mjs",
|
|
24
|
+
"module": "dist/index.mjs",
|
|
25
|
+
"types": "dist/index.d.ts",
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"import": "./dist/index.mjs",
|
|
30
|
+
"default": "./dist/index.mjs"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist",
|
|
35
|
+
"README.md",
|
|
36
|
+
"LICENSE"
|
|
37
|
+
],
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"@canvakit/showreel": "^0.2.0",
|
|
43
|
+
"@canvakit/showreel-agentic": "^0.2.0",
|
|
44
|
+
"zod": "^4.4.3"
|
|
45
|
+
},
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"@types/node": "^25.6.2",
|
|
48
|
+
"tsup": "^8.5.1",
|
|
49
|
+
"typescript": "^5.9.3",
|
|
50
|
+
"vitest": "^3.2.4",
|
|
51
|
+
"@canvakit/tooling": "0.0.0"
|
|
52
|
+
},
|
|
53
|
+
"scripts": {
|
|
54
|
+
"dev": "tsup --watch",
|
|
55
|
+
"build": "tsup",
|
|
56
|
+
"clean": "rm -rf dist",
|
|
57
|
+
"check-types": "tsc --noEmit",
|
|
58
|
+
"typecheck": "tsc --noEmit",
|
|
59
|
+
"test": "vitest run",
|
|
60
|
+
"test:watch": "vitest"
|
|
61
|
+
}
|
|
6
62
|
}
|