payload-video-streaming 0.0.0-stage → 0.2.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (252) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +658 -2
  3. package/dist/bin/args.d.ts +24 -0
  4. package/dist/bin/args.js +96 -0
  5. package/dist/bin/args.js.map +1 -0
  6. package/dist/bin/cli.d.ts +2 -0
  7. package/dist/bin/cli.js +17 -0
  8. package/dist/bin/cli.js.map +1 -0
  9. package/dist/bin/fake.d.ts +2 -0
  10. package/dist/bin/fake.js +14 -0
  11. package/dist/bin/fake.js.map +1 -0
  12. package/dist/bin/migrate.d.ts +5 -0
  13. package/dist/bin/migrate.js +47 -0
  14. package/dist/bin/migrate.js.map +1 -0
  15. package/dist/bin/runFake.d.ts +2 -0
  16. package/dist/bin/runFake.js +24 -0
  17. package/dist/bin/runFake.js.map +1 -0
  18. package/dist/blocks.d.ts +42 -0
  19. package/dist/blocks.js +150 -0
  20. package/dist/blocks.js.map +1 -0
  21. package/dist/collection.d.ts +10 -0
  22. package/dist/collection.js +550 -0
  23. package/dist/collection.js.map +1 -0
  24. package/dist/components/CaptionsManager.d.ts +9 -0
  25. package/dist/components/CaptionsManager.js +174 -0
  26. package/dist/components/CaptionsManager.js.map +1 -0
  27. package/dist/components/DownloadsPanel.d.ts +9 -0
  28. package/dist/components/DownloadsPanel.js +147 -0
  29. package/dist/components/DownloadsPanel.js.map +1 -0
  30. package/dist/components/ListUploader.d.ts +11 -0
  31. package/dist/components/ListUploader.js +116 -0
  32. package/dist/components/ListUploader.js.map +1 -0
  33. package/dist/components/ThumbnailCell.d.ts +5 -0
  34. package/dist/components/ThumbnailCell.js +28 -0
  35. package/dist/components/ThumbnailCell.js.map +1 -0
  36. package/dist/components/Uploader.d.ts +17 -0
  37. package/dist/components/Uploader.js +162 -0
  38. package/dist/components/Uploader.js.map +1 -0
  39. package/dist/components/VideoBlockLabel.d.ts +11 -0
  40. package/dist/components/VideoBlockLabel.js +86 -0
  41. package/dist/components/VideoBlockLabel.js.map +1 -0
  42. package/dist/components/VideoField.d.ts +17 -0
  43. package/dist/components/VideoField.js +418 -0
  44. package/dist/components/VideoField.js.map +1 -0
  45. package/dist/components/api.d.ts +46 -0
  46. package/dist/components/api.js +74 -0
  47. package/dist/components/api.js.map +1 -0
  48. package/dist/components/chunkedUpload.d.ts +28 -0
  49. package/dist/components/chunkedUpload.js +49 -0
  50. package/dist/components/chunkedUpload.js.map +1 -0
  51. package/dist/components/styles.d.ts +95 -0
  52. package/dist/components/styles.js +148 -0
  53. package/dist/components/styles.js.map +1 -0
  54. package/dist/components/usePluginApi.d.ts +41 -0
  55. package/dist/components/usePluginApi.js +21 -0
  56. package/dist/components/usePluginApi.js.map +1 -0
  57. package/dist/components/useVideoUpload.d.ts +37 -0
  58. package/dist/components/useVideoUpload.js +181 -0
  59. package/dist/components/useVideoUpload.js.map +1 -0
  60. package/dist/core/errors.d.ts +27 -0
  61. package/dist/core/errors.js +29 -0
  62. package/dist/core/errors.js.map +1 -0
  63. package/dist/core/provider.d.ts +331 -0
  64. package/dist/core/provider.js +13 -0
  65. package/dist/core/provider.js.map +1 -0
  66. package/dist/core/registry.d.ts +17 -0
  67. package/dist/core/registry.js +110 -0
  68. package/dist/core/registry.js.map +1 -0
  69. package/dist/core/status.d.ts +15 -0
  70. package/dist/core/status.js +29 -0
  71. package/dist/core/status.js.map +1 -0
  72. package/dist/endpoints/index.d.ts +3 -0
  73. package/dist/endpoints/index.js +464 -0
  74. package/dist/endpoints/index.js.map +1 -0
  75. package/dist/env.d.ts +40 -0
  76. package/dist/env.js +105 -0
  77. package/dist/env.js.map +1 -0
  78. package/dist/exports/bunny.d.ts +16 -0
  79. package/dist/exports/bunny.js +13 -0
  80. package/dist/exports/bunny.js.map +1 -0
  81. package/dist/exports/client.d.ts +13 -0
  82. package/dist/exports/client.js +13 -0
  83. package/dist/exports/client.js.map +1 -0
  84. package/dist/exports/cloudflare.d.ts +18 -0
  85. package/dist/exports/cloudflare.js +15 -0
  86. package/dist/exports/cloudflare.js.map +1 -0
  87. package/dist/exports/mux.d.ts +18 -0
  88. package/dist/exports/mux.js +15 -0
  89. package/dist/exports/mux.js.map +1 -0
  90. package/dist/exports/react.d.ts +13 -0
  91. package/dist/exports/react.js +11 -0
  92. package/dist/exports/react.js.map +1 -0
  93. package/dist/exports/rsc.d.ts +1 -0
  94. package/dist/exports/rsc.js +4 -0
  95. package/dist/exports/rsc.js.map +1 -0
  96. package/dist/exports/testing.d.ts +13 -0
  97. package/dist/exports/testing.js +9 -0
  98. package/dist/exports/testing.js.map +1 -0
  99. package/dist/fields.d.ts +13 -0
  100. package/dist/fields.js +13 -0
  101. package/dist/fields.js.map +1 -0
  102. package/dist/frontend/ClientVideo.d.ts +14 -0
  103. package/dist/frontend/ClientVideo.js +43 -0
  104. package/dist/frontend/ClientVideo.js.map +1 -0
  105. package/dist/frontend/Video.d.ts +32 -0
  106. package/dist/frontend/Video.js +73 -0
  107. package/dist/frontend/Video.js.map +1 -0
  108. package/dist/frontend/VideoIframe.d.ts +35 -0
  109. package/dist/frontend/VideoIframe.js +60 -0
  110. package/dist/frontend/VideoIframe.js.map +1 -0
  111. package/dist/frontend/constants.d.ts +10 -0
  112. package/dist/frontend/constants.js +10 -0
  113. package/dist/frontend/constants.js.map +1 -0
  114. package/dist/frontend/converters.d.ts +25 -0
  115. package/dist/frontend/converters.js +24 -0
  116. package/dist/frontend/converters.js.map +1 -0
  117. package/dist/frontend/source.d.ts +80 -0
  118. package/dist/frontend/source.js +159 -0
  119. package/dist/frontend/source.js.map +1 -0
  120. package/dist/frontend/useVideoSource.d.ts +27 -0
  121. package/dist/frontend/useVideoSource.js +108 -0
  122. package/dist/frontend/useVideoSource.js.map +1 -0
  123. package/dist/index.d.ts +20 -0
  124. package/dist/index.js +14 -0
  125. package/dist/index.js.map +1 -0
  126. package/dist/migrate/cfStream.d.ts +108 -0
  127. package/dist/migrate/cfStream.js +418 -0
  128. package/dist/migrate/cfStream.js.map +1 -0
  129. package/dist/options.d.ts +4 -0
  130. package/dist/options.js +90 -0
  131. package/dist/options.js.map +1 -0
  132. package/dist/plugin.d.ts +9 -0
  133. package/dist/plugin.js +98 -0
  134. package/dist/plugin.js.map +1 -0
  135. package/dist/providers/bunny/client.d.ts +78 -0
  136. package/dist/providers/bunny/client.js +231 -0
  137. package/dist/providers/bunny/client.js.map +1 -0
  138. package/dist/providers/bunny/env.d.ts +18 -0
  139. package/dist/providers/bunny/env.js +31 -0
  140. package/dist/providers/bunny/env.js.map +1 -0
  141. package/dist/providers/bunny/mapping.d.ts +39 -0
  142. package/dist/providers/bunny/mapping.js +123 -0
  143. package/dist/providers/bunny/mapping.js.map +1 -0
  144. package/dist/providers/bunny/options.d.ts +92 -0
  145. package/dist/providers/bunny/options.js +85 -0
  146. package/dist/providers/bunny/options.js.map +1 -0
  147. package/dist/providers/bunny/provider.d.ts +69 -0
  148. package/dist/providers/bunny/provider.js +472 -0
  149. package/dist/providers/bunny/provider.js.map +1 -0
  150. package/dist/providers/bunny/signing.d.ts +61 -0
  151. package/dist/providers/bunny/signing.js +144 -0
  152. package/dist/providers/bunny/signing.js.map +1 -0
  153. package/dist/providers/bunny/types.d.ts +153 -0
  154. package/dist/providers/bunny/types.js +64 -0
  155. package/dist/providers/bunny/types.js.map +1 -0
  156. package/dist/providers/bunny/urls.d.ts +49 -0
  157. package/dist/providers/bunny/urls.js +70 -0
  158. package/dist/providers/bunny/urls.js.map +1 -0
  159. package/dist/providers/bunny/webhook.d.ts +32 -0
  160. package/dist/providers/bunny/webhook.js +75 -0
  161. package/dist/providers/bunny/webhook.js.map +1 -0
  162. package/dist/providers/cloudflare/client.d.ts +93 -0
  163. package/dist/providers/cloudflare/client.js +436 -0
  164. package/dist/providers/cloudflare/client.js.map +1 -0
  165. package/dist/providers/cloudflare/env.d.ts +22 -0
  166. package/dist/providers/cloudflare/env.js +57 -0
  167. package/dist/providers/cloudflare/env.js.map +1 -0
  168. package/dist/providers/cloudflare/mapping.d.ts +15 -0
  169. package/dist/providers/cloudflare/mapping.js +95 -0
  170. package/dist/providers/cloudflare/mapping.js.map +1 -0
  171. package/dist/providers/cloudflare/options.d.ts +104 -0
  172. package/dist/providers/cloudflare/options.js +91 -0
  173. package/dist/providers/cloudflare/options.js.map +1 -0
  174. package/dist/providers/cloudflare/provider.d.ts +62 -0
  175. package/dist/providers/cloudflare/provider.js +434 -0
  176. package/dist/providers/cloudflare/provider.js.map +1 -0
  177. package/dist/providers/cloudflare/signing.d.ts +41 -0
  178. package/dist/providers/cloudflare/signing.js +97 -0
  179. package/dist/providers/cloudflare/signing.js.map +1 -0
  180. package/dist/providers/cloudflare/tus.d.ts +24 -0
  181. package/dist/providers/cloudflare/tus.js +55 -0
  182. package/dist/providers/cloudflare/tus.js.map +1 -0
  183. package/dist/providers/cloudflare/types.d.ts +156 -0
  184. package/dist/providers/cloudflare/types.js +14 -0
  185. package/dist/providers/cloudflare/types.js.map +1 -0
  186. package/dist/providers/cloudflare/urls.d.ts +55 -0
  187. package/dist/providers/cloudflare/urls.js +87 -0
  188. package/dist/providers/cloudflare/urls.js.map +1 -0
  189. package/dist/providers/cloudflare/webhook.d.ts +36 -0
  190. package/dist/providers/cloudflare/webhook.js +83 -0
  191. package/dist/providers/cloudflare/webhook.js.map +1 -0
  192. package/dist/providers/mux/client.d.ts +82 -0
  193. package/dist/providers/mux/client.js +283 -0
  194. package/dist/providers/mux/client.js.map +1 -0
  195. package/dist/providers/mux/env.d.ts +21 -0
  196. package/dist/providers/mux/env.js +61 -0
  197. package/dist/providers/mux/env.js.map +1 -0
  198. package/dist/providers/mux/mapping.d.ts +38 -0
  199. package/dist/providers/mux/mapping.js +111 -0
  200. package/dist/providers/mux/mapping.js.map +1 -0
  201. package/dist/providers/mux/options.d.ts +96 -0
  202. package/dist/providers/mux/options.js +83 -0
  203. package/dist/providers/mux/options.js.map +1 -0
  204. package/dist/providers/mux/provider.d.ts +62 -0
  205. package/dist/providers/mux/provider.js +546 -0
  206. package/dist/providers/mux/provider.js.map +1 -0
  207. package/dist/providers/mux/signing.d.ts +45 -0
  208. package/dist/providers/mux/signing.js +84 -0
  209. package/dist/providers/mux/signing.js.map +1 -0
  210. package/dist/providers/mux/types.d.ts +173 -0
  211. package/dist/providers/mux/types.js +42 -0
  212. package/dist/providers/mux/types.js.map +1 -0
  213. package/dist/providers/mux/urls.d.ts +58 -0
  214. package/dist/providers/mux/urls.js +59 -0
  215. package/dist/providers/mux/urls.js.map +1 -0
  216. package/dist/providers/mux/webhook.d.ts +38 -0
  217. package/dist/providers/mux/webhook.js +115 -0
  218. package/dist/providers/mux/webhook.js.map +1 -0
  219. package/dist/service.d.ts +166 -0
  220. package/dist/service.js +857 -0
  221. package/dist/service.js.map +1 -0
  222. package/dist/testing/bunny.d.ts +113 -0
  223. package/dist/testing/bunny.js +776 -0
  224. package/dist/testing/bunny.js.map +1 -0
  225. package/dist/testing/cloudflare.d.ts +101 -0
  226. package/dist/testing/cloudflare.js +913 -0
  227. package/dist/testing/cloudflare.js.map +1 -0
  228. package/dist/testing/index.d.ts +45 -0
  229. package/dist/testing/index.js +42 -0
  230. package/dist/testing/index.js.map +1 -0
  231. package/dist/testing/mux.d.ts +139 -0
  232. package/dist/testing/mux.js +1053 -0
  233. package/dist/testing/mux.js.map +1 -0
  234. package/dist/testing/types.d.ts +90 -0
  235. package/dist/testing/types.js +9 -0
  236. package/dist/testing/types.js.map +1 -0
  237. package/dist/types.d.ts +250 -0
  238. package/dist/types.js +3 -0
  239. package/dist/types.js.map +1 -0
  240. package/dist/utils/access.d.ts +22 -0
  241. package/dist/utils/access.js +66 -0
  242. package/dist/utils/access.js.map +1 -0
  243. package/dist/utils/localReq.d.ts +11 -0
  244. package/dist/utils/localReq.js +23 -0
  245. package/dist/utils/localReq.js.map +1 -0
  246. package/dist/utils/request.d.ts +12 -0
  247. package/dist/utils/request.js +55 -0
  248. package/dist/utils/request.js.map +1 -0
  249. package/dist/utils/version.d.ts +5 -0
  250. package/dist/utils/version.js +7 -0
  251. package/dist/utils/version.js.map +1 -0
  252. package/package.json +174 -4
@@ -0,0 +1,472 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { BunnyStreamClient, BunnyStreamError } from './client.js';
3
+ import { captionToNeutral, metaTag, mp4FallbackFile, toMetaTags, videoToAsset } from './mapping.js';
4
+ import { resolveBunnyOptions } from './options.js';
5
+ import { cdnToken, tusUploadSignature } from './signing.js';
6
+ import { cdnFileUrl, embedUrl, hlsUrl, signedEmbedUrl, videoFileSigner } from './urls.js';
7
+ import { isBunnyWebhookPayload, parseBunnyDate, verifyBunnyWebhook } from './webhook.js';
8
+ export const BUNNY_CAPABILITIES = {
9
+ adoptExisting: true,
10
+ // Embedding is restricted per library (allowed referrers), not per video.
11
+ allowedOrigins: false,
12
+ captions: {
13
+ generate: true,
14
+ upload: true
15
+ },
16
+ dash: false,
17
+ // MP4 fallback is a library setting (EnableMP4Fallback) that applies to new uploads.
18
+ downloads: {
19
+ managed: 'library',
20
+ types: [
21
+ 'default'
22
+ ]
23
+ },
24
+ importFromUrl: true,
25
+ progress: true,
26
+ serverUpload: true,
27
+ // Token authentication (embed and CDN) is a library setting.
28
+ signedPlayback: 'library',
29
+ // The poster position is applied when a video is created; Bunny has no API to move it afterwards.
30
+ thumbnailTime: false,
31
+ uploadProtocols: [
32
+ 'tus'
33
+ ],
34
+ webhooks: true
35
+ };
36
+ const LIST_PAGE_SIZE = 1000;
37
+ /** How long a requested transcription is listed as `processing` before Bunny reports the track. */ const PENDING_CAPTION_TTL_MS = 60 * 60 * 1000;
38
+ const requireGuid = (ref)=>{
39
+ if (!ref.assetId) {
40
+ throw new Error('[payload-video-streaming] bunny: this video has no Bunny Stream video id');
41
+ }
42
+ return ref.assetId;
43
+ };
44
+ /** Bunny Stream as a video provider. Create it with `bunnyStream({ … })`. */ export class BunnyStreamProvider {
45
+ capabilities = BUNNY_CAPABILITIES;
46
+ captions;
47
+ client;
48
+ id;
49
+ label;
50
+ options;
51
+ webhook;
52
+ /** Transcriptions requested from this process, by video and language, until Bunny lists the track. */ pendingCaptions = new Map();
53
+ constructor(options){
54
+ this.options = resolveBunnyOptions(options);
55
+ this.id = this.options.id;
56
+ this.label = this.options.label;
57
+ this.client = new BunnyStreamClient({
58
+ apiBaseUrl: this.options.apiBaseUrl,
59
+ apiKey: this.options.apiKey,
60
+ fetch: this.options.fetch,
61
+ libraryId: this.options.libraryId
62
+ });
63
+ this.captions = {
64
+ generate: (ref, language)=>this.generateCaption(requireGuid(ref), language),
65
+ list: (ref)=>this.listCaptions(requireGuid(ref)),
66
+ remove: async (ref, language)=>{
67
+ const guid = requireGuid(ref);
68
+ this.pendingCaptions.get(guid)?.delete(language.replace(/-auto$/i, ''));
69
+ await this.client.deleteCaption(guid, language);
70
+ },
71
+ upload: async (ref, language, vtt)=>{
72
+ await this.client.addCaption(requireGuid(ref), language, vtt);
73
+ return {
74
+ generated: false,
75
+ label: language,
76
+ language,
77
+ status: 'ready'
78
+ };
79
+ }
80
+ };
81
+ if (this.options.webhook.secret) {
82
+ this.webhook = {
83
+ handle: (input)=>this.handleWebhook(input)
84
+ };
85
+ }
86
+ }
87
+ /** True when the library uses token authentication, i.e. a token key is configured. */ get signsPlayback() {
88
+ return Boolean(this.options.embedTokenKey || this.options.cdnTokenKey);
89
+ }
90
+ asset(video) {
91
+ return videoToAsset(video, {
92
+ signedPlayback: this.signsPlayback
93
+ });
94
+ }
95
+ // ---------------------------------------------------------------------------
96
+ // Uploads
97
+ // ---------------------------------------------------------------------------
98
+ /** Creates a video, then stores meta tags (plugin `meta` and the creator) when there are any. */ async createVideo(input) {
99
+ const video = await this.client.createVideo({
100
+ ...this.options.collectionId ? {
101
+ collectionId: this.options.collectionId
102
+ } : {},
103
+ ...typeof input.thumbnailTime === 'number' ? {
104
+ thumbnailTime: Math.round(input.thumbnailTime * 1000)
105
+ } : {},
106
+ title: input.title
107
+ });
108
+ const metaTags = toMetaTags(input.meta, input.creator);
109
+ if (metaTags.length) {
110
+ try {
111
+ await this.client.updateVideo(video.guid, {
112
+ metaTags
113
+ });
114
+ } catch (err) {
115
+ await this.client.deleteVideo(video.guid).catch(()=>undefined);
116
+ throw err;
117
+ }
118
+ video.metaTags = metaTags;
119
+ }
120
+ return video;
121
+ }
122
+ /**
123
+ * Creates the video, then signs a tus upload the browser sends straight to Bunny
124
+ * (`AuthorizationSignature` = SHA256(libraryId + apiKey + expires + videoId)). The API key itself
125
+ * never leaves the server.
126
+ */ async createDirectUpload(input) {
127
+ const video = await this.createVideo(input);
128
+ const expires = Math.floor(Date.now() / 1000) + this.options.upload.tusSignatureTtlSeconds;
129
+ const { libraryId } = this.options;
130
+ return {
131
+ ...this.options.upload.tusChunkSize ? {
132
+ chunkSize: this.options.upload.tusChunkSize
133
+ } : {},
134
+ endpoint: this.options.upload.tusEndpoint,
135
+ headers: {
136
+ AuthorizationExpire: String(expires),
137
+ AuthorizationSignature: tusUploadSignature({
138
+ apiKey: this.options.apiKey,
139
+ expires,
140
+ libraryId,
141
+ videoId: video.guid
142
+ }),
143
+ LibraryId: libraryId,
144
+ VideoId: video.guid
145
+ },
146
+ metadata: {
147
+ title: input.title,
148
+ ...this.options.collectionId ? {
149
+ collection: this.options.collectionId
150
+ } : {},
151
+ ...typeof input.thumbnailTime === 'number' ? {
152
+ thumbnailTime: String(Math.round(input.thumbnailTime * 1000))
153
+ } : {}
154
+ },
155
+ protocol: 'tus',
156
+ ref: {
157
+ assetId: video.guid
158
+ }
159
+ };
160
+ }
161
+ /**
162
+ * Has Bunny fetch the video. Bunny documents no video id in the response, so when it doesn't send
163
+ * one the video is found by a unique temporary title, which is then replaced by the real one.
164
+ */ async importFromUrl(input) {
165
+ const marker = `pvs-import-${randomBytes(8).toString('hex')}`;
166
+ const query = {
167
+ ...this.options.collectionId ? {
168
+ collectionId: this.options.collectionId
169
+ } : {},
170
+ ...typeof input.thumbnailTime === 'number' ? {
171
+ thumbnailTime: Math.round(input.thumbnailTime * 1000)
172
+ } : {}
173
+ };
174
+ const result = await this.client.fetchVideo({
175
+ title: marker,
176
+ url: input.url
177
+ }, query);
178
+ let guid = result.guid;
179
+ if (!guid) {
180
+ const found = await this.client.listVideos({
181
+ itemsPerPage: 100,
182
+ orderBy: 'date',
183
+ page: 1,
184
+ search: marker
185
+ });
186
+ guid = (found.items ?? []).find((v)=>v.title === marker)?.guid;
187
+ }
188
+ if (!guid) {
189
+ throw new BunnyStreamError('Bunny Stream accepted the import, but the new video could not be found', 502);
190
+ }
191
+ await this.client.updateVideo(guid, {
192
+ metaTags: toMetaTags(input.meta, input.creator),
193
+ title: input.title
194
+ }).catch(async (err)=>{
195
+ await this.client.deleteVideo(guid).catch(()=>undefined);
196
+ throw err;
197
+ });
198
+ const asset = this.asset(await this.client.getVideo(guid));
199
+ // Bunny is fetching the file, so the video isn't waiting for an upload from us.
200
+ return asset.status === 'waiting' ? {
201
+ ...asset,
202
+ status: 'queued'
203
+ } : asset;
204
+ }
205
+ async uploadFile(input) {
206
+ const video = await this.createVideo(input);
207
+ try {
208
+ await this.client.uploadVideo(video.guid, input.file);
209
+ } catch (err) {
210
+ await this.client.deleteVideo(video.guid).catch(()=>undefined);
211
+ throw err;
212
+ }
213
+ return this.asset(await this.client.getVideo(video.guid));
214
+ }
215
+ // ---------------------------------------------------------------------------
216
+ // Assets
217
+ // ---------------------------------------------------------------------------
218
+ async getAsset(ref) {
219
+ try {
220
+ return this.asset(await this.client.getVideo(requireGuid(ref)));
221
+ } catch (err) {
222
+ if (err instanceof BunnyStreamError && err.isNotFound) {
223
+ return null;
224
+ }
225
+ throw err;
226
+ }
227
+ }
228
+ /** Pages through the library, newest first; the cursor is the next page number. */ async listAssets({ creator, cursor } = {}) {
229
+ const page = Math.max(1, Number.parseInt(cursor ?? '1', 10) || 1);
230
+ const list = await this.client.listVideos({
231
+ itemsPerPage: LIST_PAGE_SIZE,
232
+ orderBy: 'date',
233
+ page,
234
+ ...this.options.collectionId ? {
235
+ collection: this.options.collectionId
236
+ } : {}
237
+ });
238
+ const items = list.items ?? [];
239
+ const perPage = list.itemsPerPage || LIST_PAGE_SIZE;
240
+ const total = list.totalItems ?? 0;
241
+ const next = items.length > 0 && page * perPage < total ? String(page + 1) : undefined;
242
+ const assets = items.filter((v)=>!creator || metaTag(v.metaTags, 'creator') === creator).map((v)=>this.asset(v));
243
+ return {
244
+ assets,
245
+ next
246
+ };
247
+ }
248
+ /** Pushes the title and meta tags. Signing, origins and the poster are library or creation settings. */ async updateAsset(ref, patch) {
249
+ if (patch.title === undefined && patch.meta === undefined) {
250
+ return null;
251
+ }
252
+ const guid = requireGuid(ref);
253
+ const current = await this.client.getVideo(guid);
254
+ await this.client.updateVideo(guid, {
255
+ ...patch.meta !== undefined ? {
256
+ metaTags: toMetaTags(patch.meta, metaTag(current.metaTags, 'creator') ?? undefined)
257
+ } : {},
258
+ ...patch.title ? {
259
+ title: patch.title
260
+ } : {}
261
+ });
262
+ return this.asset(await this.client.getVideo(guid));
263
+ }
264
+ async deleteAsset(ref) {
265
+ await this.client.deleteVideo(requireGuid(ref));
266
+ }
267
+ // ---------------------------------------------------------------------------
268
+ // Playback
269
+ // ---------------------------------------------------------------------------
270
+ /**
271
+ * Playback URLs. Token authentication is library-wide, so whether URLs are signed follows the
272
+ * configured keys (not the document): the embed URL gets a view token (`embedTokenKey`), the CDN
273
+ * files a directory token (`cdnTokenKey`) that also covers HLS renditions and segments.
274
+ */ async playback(asset, options) {
275
+ const { cdnBaseUrl, cdnTokenKey, embedBaseUrl, embedTokenKey, libraryId, playback } = this.options;
276
+ const guid = asset.assetId;
277
+ const signed = this.signsPlayback;
278
+ if (signed && !options.sign) {
279
+ return {
280
+ signed: false,
281
+ urls: null
282
+ };
283
+ }
284
+ const video = asset.providerData ?? null;
285
+ const thumbnailFile = video?.thumbnailFileName || 'thumbnail.jpg';
286
+ const mp4File = video?.hasMP4Fallback ? mp4FallbackFile(video) : undefined;
287
+ const expires = Math.floor(Date.now() / 1000) + options.expiresIn;
288
+ const iframeOptions = {
289
+ ...playback.iframe,
290
+ ...options.providerOptions?.iframe
291
+ };
292
+ const iframe = embedTokenKey ? signedEmbedUrl({
293
+ embedBaseUrl,
294
+ expires,
295
+ libraryId,
296
+ tokenKey: embedTokenKey,
297
+ videoId: guid
298
+ }, iframeOptions) : embedUrl(embedBaseUrl, libraryId, guid, iframeOptions);
299
+ let urls;
300
+ let token;
301
+ if (cdnTokenKey) {
302
+ const sign = videoFileSigner(cdnBaseUrl, guid, {
303
+ countries: playback.tokenCountries,
304
+ expires,
305
+ key: cdnTokenKey
306
+ });
307
+ urls = {
308
+ animated: sign('preview.webp'),
309
+ hls: sign('playlist.m3u8', {
310
+ directory: true
311
+ }),
312
+ iframe,
313
+ thumbnail: sign(thumbnailFile),
314
+ ...mp4File ? {
315
+ downloadMp4: sign(mp4File)
316
+ } : {}
317
+ };
318
+ token = cdnToken(cdnTokenKey, '', {
319
+ countriesAllowed: playback.tokenCountries,
320
+ expires,
321
+ tokenPath: new URL(cdnFileUrl(cdnBaseUrl, guid, '')).pathname
322
+ }).token;
323
+ } else {
324
+ urls = {
325
+ animated: cdnFileUrl(cdnBaseUrl, guid, 'preview.webp'),
326
+ hls: hlsUrl(cdnBaseUrl, guid),
327
+ iframe,
328
+ thumbnail: cdnFileUrl(cdnBaseUrl, guid, thumbnailFile),
329
+ ...mp4File ? {
330
+ downloadMp4: cdnFileUrl(cdnBaseUrl, guid, mp4File)
331
+ } : {}
332
+ };
333
+ token = embedTokenKey ? new URL(iframe).searchParams.get('token') ?? undefined : undefined;
334
+ }
335
+ return signed ? {
336
+ expiresAt: new Date(expires * 1000).toISOString(),
337
+ signed: true,
338
+ token,
339
+ urls
340
+ } : {
341
+ signed: false,
342
+ urls
343
+ };
344
+ }
345
+ // ---------------------------------------------------------------------------
346
+ // Captions
347
+ // ---------------------------------------------------------------------------
348
+ async listCaptions(guid) {
349
+ const video = await this.client.getVideo(guid);
350
+ const tracks = (video.captions ?? []).map(captionToNeutral).filter((c)=>c !== null);
351
+ const pending = this.pendingCaptions.get(guid);
352
+ if (pending) {
353
+ const now = Date.now();
354
+ for (const [language, requestedAt] of pending){
355
+ const done = tracks.some((t)=>t.language.replace(/-auto$/i, '') === language && t.generated);
356
+ if (done || now - requestedAt > PENDING_CAPTION_TTL_MS) {
357
+ pending.delete(language);
358
+ } else {
359
+ tracks.push({
360
+ generated: true,
361
+ label: `${language} (auto-generated)`,
362
+ language: `${language}-auto`,
363
+ status: 'processing'
364
+ });
365
+ }
366
+ }
367
+ if (!pending.size) {
368
+ this.pendingCaptions.delete(guid);
369
+ }
370
+ }
371
+ return tracks;
372
+ }
373
+ /** Starts AI transcription (Bunny auto-detects the spoken language). The track appears as `<lang>-auto`. */ async generateCaption(guid, language) {
374
+ const target = language.replace(/-auto$/i, '').split('-')[0].toLowerCase();
375
+ if (!/^[a-z]{2}$/.test(target)) {
376
+ // A request error (HTTP 400), not a provider failure.
377
+ throw Object.assign(new Error(`Bunny transcribes into ISO 639-1 languages (two letters, e.g. "en"), not "${language}"`), {
378
+ status: 400
379
+ });
380
+ }
381
+ await this.client.transcribe(guid, {
382
+ targetLanguages: [
383
+ target
384
+ ]
385
+ });
386
+ const pending = this.pendingCaptions.get(guid) ?? new Map();
387
+ pending.set(target, Date.now());
388
+ this.pendingCaptions.set(guid, pending);
389
+ return {
390
+ generated: true,
391
+ label: `${target} (auto-generated)`,
392
+ language: `${target}-auto`,
393
+ status: 'processing'
394
+ };
395
+ }
396
+ // ---------------------------------------------------------------------------
397
+ // Webhooks
398
+ // ---------------------------------------------------------------------------
399
+ /**
400
+ * Verifies a notification and asks the core to re-fetch the video. Bunny's notifications carry only
401
+ * a status code, so the current state is read from the API: that is robust to retries and to events
402
+ * arriving out of order. Duplicates are dropped by `EventId`; very old events are rejected.
403
+ */ async handleWebhook({ headers, rawBody }) {
404
+ const verification = verifyBunnyWebhook({
405
+ headers,
406
+ rawBody,
407
+ secret: this.options.webhook.secret ?? ''
408
+ });
409
+ if (!verification.ok) {
410
+ return {
411
+ ok: false,
412
+ reason: `invalid signature (${verification.reason})`,
413
+ status: 401
414
+ };
415
+ }
416
+ let payload;
417
+ try {
418
+ payload = JSON.parse(rawBody);
419
+ } catch {
420
+ return {
421
+ ok: false,
422
+ reason: 'Invalid JSON body',
423
+ status: 400
424
+ };
425
+ }
426
+ if (!isBunnyWebhookPayload(payload)) {
427
+ return {
428
+ ok: false,
429
+ reason: 'Webhook payload has no VideoGuid/Status',
430
+ status: 400
431
+ };
432
+ }
433
+ const event = payload;
434
+ if (event.IsLiveStreamWebhook || String(event.VideoLibraryId) !== this.options.libraryId) {
435
+ return {
436
+ events: [],
437
+ ok: true
438
+ };
439
+ }
440
+ const tolerance = this.options.webhook.toleranceSeconds;
441
+ const at = parseBunnyDate(event.Timestamp);
442
+ if (tolerance > 0 && at !== null && Date.now() - at > tolerance * 1000) {
443
+ return {
444
+ ok: false,
445
+ reason: 'stale notification',
446
+ status: 400
447
+ };
448
+ }
449
+ return {
450
+ events: [
451
+ {
452
+ ...event.EventId ? {
453
+ eventId: String(event.EventId)
454
+ } : {},
455
+ ref: {
456
+ assetId: event.VideoGuid
457
+ }
458
+ }
459
+ ],
460
+ ok: true
461
+ };
462
+ }
463
+ }
464
+ /**
465
+ * Bunny Stream as a video provider:
466
+ *
467
+ * ```ts
468
+ * videoPlugin({ providers: [bunnyStream({ libraryId, apiKey, cdnHostname })] })
469
+ * ```
470
+ */ export const bunnyStream = (options)=>new BunnyStreamProvider(options);
471
+
472
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/providers/bunny/provider.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto'\n\nimport type {\n AssetPatch,\n CaptionTrack,\n DirectUpload,\n ImportInput,\n NeutralAsset,\n PlaybackOptions,\n PlaybackResult,\n PlaybackUrls,\n ProviderCapabilities,\n ProviderRef,\n ProviderWebhook,\n ServerUploadInput,\n StoredAsset,\n UploadInput,\n VideoProvider,\n} from '../../core/provider.js'\nimport type { BunnyStreamOptions, ResolvedBunnyStreamOptions } from './options.js'\nimport type { BunnyVideo, BunnyWebhookPayload } from './types.js'\n\nimport { BunnyStreamClient, BunnyStreamError } from './client.js'\nimport { captionToNeutral, metaTag, mp4FallbackFile, toMetaTags, videoToAsset } from './mapping.js'\nimport { resolveBunnyOptions } from './options.js'\nimport { cdnToken, tusUploadSignature } from './signing.js'\nimport { cdnFileUrl, embedUrl, hlsUrl, signedEmbedUrl, videoFileSigner } from './urls.js'\nimport { isBunnyWebhookPayload, parseBunnyDate, verifyBunnyWebhook } from './webhook.js'\n\nexport const BUNNY_CAPABILITIES: ProviderCapabilities = {\n adoptExisting: true,\n // Embedding is restricted per library (allowed referrers), not per video.\n allowedOrigins: false,\n captions: { generate: true, upload: true },\n dash: false,\n // MP4 fallback is a library setting (EnableMP4Fallback) that applies to new uploads.\n downloads: { managed: 'library', types: ['default'] },\n importFromUrl: true,\n progress: true,\n serverUpload: true,\n // Token authentication (embed and CDN) is a library setting.\n signedPlayback: 'library',\n // The poster position is applied when a video is created; Bunny has no API to move it afterwards.\n thumbnailTime: false,\n uploadProtocols: ['tus'],\n webhooks: true,\n}\n\nconst LIST_PAGE_SIZE = 1000\n/** How long a requested transcription is listed as `processing` before Bunny reports the track. */\nconst PENDING_CAPTION_TTL_MS = 60 * 60 * 1000\n\nconst requireGuid = (ref: ProviderRef): string => {\n if (!ref.assetId) {\n throw new Error('[payload-video-streaming] bunny: this video has no Bunny Stream video id')\n }\n return ref.assetId\n}\n\n/** Bunny Stream as a video provider. Create it with `bunnyStream({ … })`. */\nexport class BunnyStreamProvider implements VideoProvider {\n readonly capabilities = BUNNY_CAPABILITIES\n readonly captions: NonNullable<VideoProvider['captions']>\n readonly client: BunnyStreamClient\n readonly id: string\n readonly label: string\n readonly options: ResolvedBunnyStreamOptions\n readonly webhook?: ProviderWebhook\n /** Transcriptions requested from this process, by video and language, until Bunny lists the track. */\n private readonly pendingCaptions = new Map<string, Map<string, number>>()\n\n constructor(options: BunnyStreamOptions) {\n this.options = resolveBunnyOptions(options)\n this.id = this.options.id\n this.label = this.options.label\n this.client = new BunnyStreamClient({\n apiBaseUrl: this.options.apiBaseUrl,\n apiKey: this.options.apiKey,\n fetch: this.options.fetch,\n libraryId: this.options.libraryId,\n })\n\n this.captions = {\n generate: (ref, language) => this.generateCaption(requireGuid(ref), language),\n list: (ref) => this.listCaptions(requireGuid(ref)),\n remove: async (ref, language) => {\n const guid = requireGuid(ref)\n this.pendingCaptions.get(guid)?.delete(language.replace(/-auto$/i, ''))\n await this.client.deleteCaption(guid, language)\n },\n upload: async (ref, language, vtt) => {\n await this.client.addCaption(requireGuid(ref), language, vtt)\n return { generated: false, label: language, language, status: 'ready' }\n },\n }\n\n if (this.options.webhook.secret) {\n this.webhook = { handle: (input) => this.handleWebhook(input) }\n }\n }\n\n /** True when the library uses token authentication, i.e. a token key is configured. */\n get signsPlayback(): boolean {\n return Boolean(this.options.embedTokenKey || this.options.cdnTokenKey)\n }\n\n private asset(video: BunnyVideo): NeutralAsset {\n return videoToAsset(video, { signedPlayback: this.signsPlayback })\n }\n\n // ---------------------------------------------------------------------------\n // Uploads\n // ---------------------------------------------------------------------------\n\n /** Creates a video, then stores meta tags (plugin `meta` and the creator) when there are any. */\n private async createVideo(input: Pick<UploadInput, 'creator' | 'meta' | 'thumbnailTime' | 'title'>): Promise<BunnyVideo> {\n const video = await this.client.createVideo({\n ...(this.options.collectionId ? { collectionId: this.options.collectionId } : {}),\n ...(typeof input.thumbnailTime === 'number' ? { thumbnailTime: Math.round(input.thumbnailTime * 1000) } : {}),\n title: input.title,\n })\n const metaTags = toMetaTags(input.meta, input.creator)\n if (metaTags.length) {\n try {\n await this.client.updateVideo(video.guid, { metaTags })\n } catch (err) {\n await this.client.deleteVideo(video.guid).catch(() => undefined)\n throw err\n }\n video.metaTags = metaTags\n }\n return video\n }\n\n /**\n * Creates the video, then signs a tus upload the browser sends straight to Bunny\n * (`AuthorizationSignature` = SHA256(libraryId + apiKey + expires + videoId)). The API key itself\n * never leaves the server.\n */\n async createDirectUpload(input: UploadInput): Promise<DirectUpload> {\n const video = await this.createVideo(input)\n const expires = Math.floor(Date.now() / 1000) + this.options.upload.tusSignatureTtlSeconds\n const { libraryId } = this.options\n return {\n ...(this.options.upload.tusChunkSize ? { chunkSize: this.options.upload.tusChunkSize } : {}),\n endpoint: this.options.upload.tusEndpoint,\n headers: {\n AuthorizationExpire: String(expires),\n AuthorizationSignature: tusUploadSignature({ apiKey: this.options.apiKey, expires, libraryId, videoId: video.guid }),\n LibraryId: libraryId,\n VideoId: video.guid,\n },\n metadata: {\n title: input.title,\n ...(this.options.collectionId ? { collection: this.options.collectionId } : {}),\n ...(typeof input.thumbnailTime === 'number' ? { thumbnailTime: String(Math.round(input.thumbnailTime * 1000)) } : {}),\n },\n protocol: 'tus',\n ref: { assetId: video.guid },\n }\n }\n\n /**\n * Has Bunny fetch the video. Bunny documents no video id in the response, so when it doesn't send\n * one the video is found by a unique temporary title, which is then replaced by the real one.\n */\n async importFromUrl(input: ImportInput): Promise<NeutralAsset> {\n const marker = `pvs-import-${randomBytes(8).toString('hex')}`\n const query = {\n ...(this.options.collectionId ? { collectionId: this.options.collectionId } : {}),\n ...(typeof input.thumbnailTime === 'number' ? { thumbnailTime: Math.round(input.thumbnailTime * 1000) } : {}),\n }\n const result = await this.client.fetchVideo({ title: marker, url: input.url }, query)\n let guid = result.guid\n if (!guid) {\n const found = await this.client.listVideos({ itemsPerPage: 100, orderBy: 'date', page: 1, search: marker })\n guid = (found.items ?? []).find((v) => v.title === marker)?.guid\n }\n if (!guid) {\n throw new BunnyStreamError('Bunny Stream accepted the import, but the new video could not be found', 502)\n }\n await this.client.updateVideo(guid, { metaTags: toMetaTags(input.meta, input.creator), title: input.title }).catch(async (err) => {\n await this.client.deleteVideo(guid).catch(() => undefined)\n throw err\n })\n const asset = this.asset(await this.client.getVideo(guid))\n // Bunny is fetching the file, so the video isn't waiting for an upload from us.\n return asset.status === 'waiting' ? { ...asset, status: 'queued' } : asset\n }\n\n async uploadFile(input: ServerUploadInput): Promise<NeutralAsset> {\n const video = await this.createVideo(input)\n try {\n await this.client.uploadVideo(video.guid, input.file)\n } catch (err) {\n await this.client.deleteVideo(video.guid).catch(() => undefined)\n throw err\n }\n return this.asset(await this.client.getVideo(video.guid))\n }\n\n // ---------------------------------------------------------------------------\n // Assets\n // ---------------------------------------------------------------------------\n\n async getAsset(ref: ProviderRef): Promise<NeutralAsset | null> {\n try {\n return this.asset(await this.client.getVideo(requireGuid(ref)))\n } catch (err) {\n if (err instanceof BunnyStreamError && err.isNotFound) {\n return null\n }\n throw err\n }\n }\n\n /** Pages through the library, newest first; the cursor is the next page number. */\n async listAssets({ creator, cursor }: { creator?: string; cursor?: string } = {}): Promise<{ assets: NeutralAsset[]; next?: string }> {\n const page = Math.max(1, Number.parseInt(cursor ?? '1', 10) || 1)\n const list = await this.client.listVideos({\n itemsPerPage: LIST_PAGE_SIZE,\n orderBy: 'date',\n page,\n ...(this.options.collectionId ? { collection: this.options.collectionId } : {}),\n })\n const items = list.items ?? []\n const perPage = list.itemsPerPage || LIST_PAGE_SIZE\n const total = list.totalItems ?? 0\n const next = items.length > 0 && page * perPage < total ? String(page + 1) : undefined\n const assets = items.filter((v) => !creator || metaTag(v.metaTags, 'creator') === creator).map((v) => this.asset(v))\n return { assets, next }\n }\n\n /** Pushes the title and meta tags. Signing, origins and the poster are library or creation settings. */\n async updateAsset(ref: ProviderRef, patch: AssetPatch): Promise<NeutralAsset | null> {\n if (patch.title === undefined && patch.meta === undefined) {\n return null\n }\n const guid = requireGuid(ref)\n const current = await this.client.getVideo(guid)\n await this.client.updateVideo(guid, {\n ...(patch.meta !== undefined ? { metaTags: toMetaTags(patch.meta, metaTag(current.metaTags, 'creator') ?? undefined) } : {}),\n ...(patch.title ? { title: patch.title } : {}),\n })\n return this.asset(await this.client.getVideo(guid))\n }\n\n async deleteAsset(ref: ProviderRef): Promise<void> {\n await this.client.deleteVideo(requireGuid(ref))\n }\n\n // ---------------------------------------------------------------------------\n // Playback\n // ---------------------------------------------------------------------------\n\n /**\n * Playback URLs. Token authentication is library-wide, so whether URLs are signed follows the\n * configured keys (not the document): the embed URL gets a view token (`embedTokenKey`), the CDN\n * files a directory token (`cdnTokenKey`) that also covers HLS renditions and segments.\n */\n async playback(asset: StoredAsset, options: PlaybackOptions): Promise<PlaybackResult> {\n const { cdnBaseUrl, cdnTokenKey, embedBaseUrl, embedTokenKey, libraryId, playback } = this.options\n const guid = asset.assetId\n const signed = this.signsPlayback\n if (signed && !options.sign) {\n return { signed: false, urls: null }\n }\n const video = (asset.providerData ?? null) as null | Partial<BunnyVideo>\n const thumbnailFile = video?.thumbnailFileName || 'thumbnail.jpg'\n const mp4File = video?.hasMP4Fallback ? mp4FallbackFile(video as BunnyVideo) : undefined\n const expires = Math.floor(Date.now() / 1000) + options.expiresIn\n const iframeOptions = { ...playback.iframe, ...(options.providerOptions?.iframe as object | undefined) }\n\n const iframe = embedTokenKey\n ? signedEmbedUrl({ embedBaseUrl, expires, libraryId, tokenKey: embedTokenKey, videoId: guid }, iframeOptions)\n : embedUrl(embedBaseUrl, libraryId, guid, iframeOptions)\n\n let urls: PlaybackUrls\n let token: string | undefined\n if (cdnTokenKey) {\n const sign = videoFileSigner(cdnBaseUrl, guid, { countries: playback.tokenCountries, expires, key: cdnTokenKey })\n urls = {\n animated: sign('preview.webp'),\n hls: sign('playlist.m3u8', { directory: true }),\n iframe,\n thumbnail: sign(thumbnailFile),\n ...(mp4File ? { downloadMp4: sign(mp4File) } : {}),\n }\n token = cdnToken(cdnTokenKey, '', {\n countriesAllowed: playback.tokenCountries,\n expires,\n tokenPath: new URL(cdnFileUrl(cdnBaseUrl, guid, '')).pathname,\n }).token\n } else {\n urls = {\n animated: cdnFileUrl(cdnBaseUrl, guid, 'preview.webp'),\n hls: hlsUrl(cdnBaseUrl, guid),\n iframe,\n thumbnail: cdnFileUrl(cdnBaseUrl, guid, thumbnailFile),\n ...(mp4File ? { downloadMp4: cdnFileUrl(cdnBaseUrl, guid, mp4File) } : {}),\n }\n token = embedTokenKey ? (new URL(iframe).searchParams.get('token') ?? undefined) : undefined\n }\n return signed ? { expiresAt: new Date(expires * 1000).toISOString(), signed: true, token, urls } : { signed: false, urls }\n }\n\n // ---------------------------------------------------------------------------\n // Captions\n // ---------------------------------------------------------------------------\n\n private async listCaptions(guid: string): Promise<CaptionTrack[]> {\n const video = await this.client.getVideo(guid)\n const tracks = (video.captions ?? []).map(captionToNeutral).filter((c): c is CaptionTrack => c !== null)\n const pending = this.pendingCaptions.get(guid)\n if (pending) {\n const now = Date.now()\n for (const [language, requestedAt] of pending) {\n const done = tracks.some((t) => t.language.replace(/-auto$/i, '') === language && t.generated)\n if (done || now - requestedAt > PENDING_CAPTION_TTL_MS) {\n pending.delete(language)\n } else {\n tracks.push({ generated: true, label: `${language} (auto-generated)`, language: `${language}-auto`, status: 'processing' })\n }\n }\n if (!pending.size) {\n this.pendingCaptions.delete(guid)\n }\n }\n return tracks\n }\n\n /** Starts AI transcription (Bunny auto-detects the spoken language). The track appears as `<lang>-auto`. */\n private async generateCaption(guid: string, language: string): Promise<CaptionTrack> {\n const target = language.replace(/-auto$/i, '').split('-')[0]!.toLowerCase()\n if (!/^[a-z]{2}$/.test(target)) {\n // A request error (HTTP 400), not a provider failure.\n throw Object.assign(new Error(`Bunny transcribes into ISO 639-1 languages (two letters, e.g. \"en\"), not \"${language}\"`), { status: 400 })\n }\n await this.client.transcribe(guid, { targetLanguages: [target] })\n const pending = this.pendingCaptions.get(guid) ?? new Map<string, number>()\n pending.set(target, Date.now())\n this.pendingCaptions.set(guid, pending)\n return { generated: true, label: `${target} (auto-generated)`, language: `${target}-auto`, status: 'processing' }\n }\n\n // ---------------------------------------------------------------------------\n // Webhooks\n // ---------------------------------------------------------------------------\n\n /**\n * Verifies a notification and asks the core to re-fetch the video. Bunny's notifications carry only\n * a status code, so the current state is read from the API: that is robust to retries and to events\n * arriving out of order. Duplicates are dropped by `EventId`; very old events are rejected.\n */\n private async handleWebhook({ headers, rawBody }: { headers: Headers; rawBody: string }) {\n const verification = verifyBunnyWebhook({ headers, rawBody, secret: this.options.webhook.secret ?? '' })\n if (!verification.ok) {\n return { ok: false as const, reason: `invalid signature (${verification.reason})`, status: 401 as const }\n }\n let payload: unknown\n try {\n payload = JSON.parse(rawBody)\n } catch {\n return { ok: false as const, reason: 'Invalid JSON body', status: 400 as const }\n }\n if (!isBunnyWebhookPayload(payload)) {\n return { ok: false as const, reason: 'Webhook payload has no VideoGuid/Status', status: 400 as const }\n }\n const event = payload as BunnyWebhookPayload\n if (event.IsLiveStreamWebhook || String(event.VideoLibraryId) !== this.options.libraryId) {\n return { events: [], ok: true as const }\n }\n const tolerance = this.options.webhook.toleranceSeconds\n const at = parseBunnyDate(event.Timestamp)\n if (tolerance > 0 && at !== null && Date.now() - at > tolerance * 1000) {\n return { ok: false as const, reason: 'stale notification', status: 400 as const }\n }\n return { events: [{ ...(event.EventId ? { eventId: String(event.EventId) } : {}), ref: { assetId: event.VideoGuid } }], ok: true as const }\n }\n}\n\n/**\n * Bunny Stream as a video provider:\n *\n * ```ts\n * videoPlugin({ providers: [bunnyStream({ libraryId, apiKey, cdnHostname })] })\n * ```\n */\nexport const bunnyStream = (options: BunnyStreamOptions): BunnyStreamProvider => new BunnyStreamProvider(options)\n"],"names":["randomBytes","BunnyStreamClient","BunnyStreamError","captionToNeutral","metaTag","mp4FallbackFile","toMetaTags","videoToAsset","resolveBunnyOptions","cdnToken","tusUploadSignature","cdnFileUrl","embedUrl","hlsUrl","signedEmbedUrl","videoFileSigner","isBunnyWebhookPayload","parseBunnyDate","verifyBunnyWebhook","BUNNY_CAPABILITIES","adoptExisting","allowedOrigins","captions","generate","upload","dash","downloads","managed","types","importFromUrl","progress","serverUpload","signedPlayback","thumbnailTime","uploadProtocols","webhooks","LIST_PAGE_SIZE","PENDING_CAPTION_TTL_MS","requireGuid","ref","assetId","Error","BunnyStreamProvider","capabilities","client","id","label","options","webhook","pendingCaptions","Map","apiBaseUrl","apiKey","fetch","libraryId","language","generateCaption","list","listCaptions","remove","guid","get","delete","replace","deleteCaption","vtt","addCaption","generated","status","secret","handle","input","handleWebhook","signsPlayback","Boolean","embedTokenKey","cdnTokenKey","asset","video","createVideo","collectionId","Math","round","title","metaTags","meta","creator","length","updateVideo","err","deleteVideo","catch","undefined","createDirectUpload","expires","floor","Date","now","tusSignatureTtlSeconds","tusChunkSize","chunkSize","endpoint","tusEndpoint","headers","AuthorizationExpire","String","AuthorizationSignature","videoId","LibraryId","VideoId","metadata","collection","protocol","marker","toString","query","result","fetchVideo","url","found","listVideos","itemsPerPage","orderBy","page","search","items","find","v","getVideo","uploadFile","uploadVideo","file","getAsset","isNotFound","listAssets","cursor","max","Number","parseInt","perPage","total","totalItems","next","assets","filter","map","updateAsset","patch","current","deleteAsset","playback","cdnBaseUrl","embedBaseUrl","signed","sign","urls","providerData","thumbnailFile","thumbnailFileName","mp4File","hasMP4Fallback","expiresIn","iframeOptions","iframe","providerOptions","tokenKey","token","countries","tokenCountries","key","animated","hls","directory","thumbnail","downloadMp4","countriesAllowed","tokenPath","URL","pathname","searchParams","expiresAt","toISOString","tracks","c","pending","requestedAt","done","some","t","push","size","target","split","toLowerCase","test","Object","assign","transcribe","targetLanguages","set","rawBody","verification","ok","reason","payload","JSON","parse","event","IsLiveStreamWebhook","VideoLibraryId","events","tolerance","toleranceSeconds","at","Timestamp","EventId","eventId","VideoGuid","bunnyStream"],"mappings":"AAAA,SAASA,WAAW,QAAQ,cAAa;AAsBzC,SAASC,iBAAiB,EAAEC,gBAAgB,QAAQ,cAAa;AACjE,SAASC,gBAAgB,EAAEC,OAAO,EAAEC,eAAe,EAAEC,UAAU,EAAEC,YAAY,QAAQ,eAAc;AACnG,SAASC,mBAAmB,QAAQ,eAAc;AAClD,SAASC,QAAQ,EAAEC,kBAAkB,QAAQ,eAAc;AAC3D,SAASC,UAAU,EAA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AACO,SAAS,EAAE;YACxF,OAAO;gBAAE4J,QAAQ,EAAE;gBAAER,IAAI;YAAc;QACzC;QACA,MAAMS,YAAY,IAAI,CAACpK,OAAO,CAACC,OAAO,CAACoK,gBAAgB;QACvD,MAAMC,KAAKpM,eAAe8L,MAAMO,SAAS;QACzC,IAAIH,YAAY,KAAKE,OAAO,QAAQrH,KAAKC,GAAG,KAAKoH,KAAKF,YAAY,MAAM;YACtE,OAAO;gBAAET,IAAI;gBAAgBC,QAAQ;gBAAsBvI,QAAQ;YAAa;QAClF;QACA,OAAO;YAAE8I,QAAQ;gBAAC;oBAAE,GAAIH,MAAMQ,OAAO,GAAG;wBAAEC,SAAS/G,OAAOsG,MAAMQ,OAAO;oBAAE,IAAI,CAAC,CAAC;oBAAGhL,KAAK;wBAAEC,SAASuK,MAAMU,SAAS;oBAAC;gBAAE;aAAE;YAAEf,IAAI;QAAc;IAC5I;AACF;AAEA;;;;;;CAMC,GACD,OAAO,MAAMgB,cAAc,CAAC3K,UAAqD,IAAIL,oBAAoBK,SAAQ"}
@@ -0,0 +1,61 @@
1
+ /** `AuthorizationSignature` for a tus upload: hex SHA256 of `libraryId + apiKey + expires + videoId`. */
2
+ export declare const tusUploadSignature: (args: {
3
+ apiKey: string;
4
+ expires: number;
5
+ libraryId: number | string;
6
+ videoId: string;
7
+ }) => string;
8
+ /** Embed view token: hex SHA256 of `tokenKey + videoId + expires` (the library's token authentication key). */
9
+ export declare const embedViewToken: (args: {
10
+ expires: number;
11
+ tokenKey: string;
12
+ videoId: string;
13
+ }) => string;
14
+ /** Constant-time comparison of two hex strings (case-insensitive). */
15
+ export declare const hexEquals: (a: string, b: string) => boolean;
16
+ /** The IP address as bytes for the CDN token: 4 bytes for IPv4, IPv6 masked to its /64 prefix. */
17
+ export declare const ipToTokenBytes: (ip: string) => Buffer;
18
+ export type CdnTokenOptions = {
19
+ /** Comma-separated ISO country codes allowed to use the token. */
20
+ countriesAllowed?: string;
21
+ /** Comma-separated ISO country codes blocked from using the token. */
22
+ countriesBlocked?: string;
23
+ /** Unix time (seconds) when the token expires. */
24
+ expires: number;
25
+ /** Signs a directory: every file whose path starts with this (e.g. `/{guid}/`) is covered. */
26
+ tokenPath?: string;
27
+ /** Lock the token to this IP (IPv6 is locked to its /64). */
28
+ userIp?: string;
29
+ };
30
+ /** Computes an advanced CDN token (`HS256-…`) for a URL path. */
31
+ export declare const cdnToken: (key: string, path: string, options: CdnTokenOptions) => {
32
+ params: [string, string][];
33
+ token: string;
34
+ };
35
+ /**
36
+ * Signs a CDN URL with advanced token authentication.
37
+ * - `directory: false`: `…/file?token=HS256-…&expires=…`
38
+ * - `directory: true`: `/bcdn_token=HS256-…&expires=…/file`, so relative URLs inside an HLS playlist
39
+ * (renditions, segments) inherit the token. Pass `tokenPath` to cover the whole directory.
40
+ */
41
+ export declare const signCdnUrl: (url: string, key: string, options: {
42
+ directory?: boolean;
43
+ } & CdnTokenOptions) => string;
44
+ /** Splits a path signed in directory form (`/bcdn_token=…&expires=…/rest`) into its token parameters and real path. */
45
+ export declare const parseDirectoryToken: (pathname: string) => {
46
+ params: URLSearchParams;
47
+ path: string;
48
+ } | null;
49
+ /**
50
+ * Verifies an advanced CDN token, as the CDN does (used by the fake; handy for your own tests).
51
+ * `params` are the request's token parameters (query string or directory segment).
52
+ */
53
+ export declare const verifyCdnToken: (key: string, path: string, params: URLSearchParams, { now, userIp }?: {
54
+ now?: number;
55
+ userIp?: string;
56
+ }) => {
57
+ ok: true;
58
+ } | {
59
+ ok: false;
60
+ reason: "expired" | "invalid" | "missing" | "path";
61
+ };