payload-video-streaming 0.0.0-stage → 0.2.0-beta.1
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 +21 -0
- package/README.md +289 -2
- package/dist/access.d.ts +35 -0
- package/dist/access.js +53 -0
- package/dist/access.js.map +1 -0
- package/dist/bin/args.d.ts +37 -0
- package/dist/bin/args.js +157 -0
- package/dist/bin/args.js.map +1 -0
- package/dist/bin/cli.d.ts +2 -0
- package/dist/bin/cli.js +25 -0
- package/dist/bin/cli.js.map +1 -0
- package/dist/bin/fake.d.ts +2 -0
- package/dist/bin/fake.js +14 -0
- package/dist/bin/fake.js.map +1 -0
- package/dist/bin/migrate.d.ts +5 -0
- package/dist/bin/migrate.js +47 -0
- package/dist/bin/migrate.js.map +1 -0
- package/dist/bin/runFake.d.ts +2 -0
- package/dist/bin/runFake.js +24 -0
- package/dist/bin/runFake.js.map +1 -0
- package/dist/bin/webhooks.d.ts +15 -0
- package/dist/bin/webhooks.js +149 -0
- package/dist/bin/webhooks.js.map +1 -0
- package/dist/blocks.d.ts +42 -0
- package/dist/blocks.js +150 -0
- package/dist/blocks.js.map +1 -0
- package/dist/collection.d.ts +10 -0
- package/dist/collection.js +697 -0
- package/dist/collection.js.map +1 -0
- package/dist/components/BulkUploader.d.ts +16 -0
- package/dist/components/BulkUploader.js +226 -0
- package/dist/components/BulkUploader.js.map +1 -0
- package/dist/components/CaptionsManager.d.ts +9 -0
- package/dist/components/CaptionsManager.js +174 -0
- package/dist/components/CaptionsManager.js.map +1 -0
- package/dist/components/DownloadsPanel.d.ts +9 -0
- package/dist/components/DownloadsPanel.js +147 -0
- package/dist/components/DownloadsPanel.js.map +1 -0
- package/dist/components/ListUploader.d.ts +11 -0
- package/dist/components/ListUploader.js +138 -0
- package/dist/components/ListUploader.js.map +1 -0
- package/dist/components/ThumbnailCell.d.ts +5 -0
- package/dist/components/ThumbnailCell.js +28 -0
- package/dist/components/ThumbnailCell.js.map +1 -0
- package/dist/components/Uploader.d.ts +22 -0
- package/dist/components/Uploader.js +171 -0
- package/dist/components/Uploader.js.map +1 -0
- package/dist/components/VideoBlockLabel.d.ts +11 -0
- package/dist/components/VideoBlockLabel.js +86 -0
- package/dist/components/VideoBlockLabel.js.map +1 -0
- package/dist/components/VideoField.d.ts +17 -0
- package/dist/components/VideoField.js +422 -0
- package/dist/components/VideoField.js.map +1 -0
- package/dist/components/VideoRelationshipField.d.ts +16 -0
- package/dist/components/VideoRelationshipField.js +106 -0
- package/dist/components/VideoRelationshipField.js.map +1 -0
- package/dist/components/WebhookStatusPanel.d.ts +6 -0
- package/dist/components/WebhookStatusPanel.js +143 -0
- package/dist/components/WebhookStatusPanel.js.map +1 -0
- package/dist/components/api.d.ts +52 -0
- package/dist/components/api.js +76 -0
- package/dist/components/api.js.map +1 -0
- package/dist/components/chunkedUpload.d.ts +28 -0
- package/dist/components/chunkedUpload.js +49 -0
- package/dist/components/chunkedUpload.js.map +1 -0
- package/dist/components/styles.d.ts +95 -0
- package/dist/components/styles.js +148 -0
- package/dist/components/styles.js.map +1 -0
- package/dist/components/uploadFile.d.ts +30 -0
- package/dist/components/uploadFile.js +140 -0
- package/dist/components/uploadFile.js.map +1 -0
- package/dist/components/usePluginApi.d.ts +46 -0
- package/dist/components/usePluginApi.js +21 -0
- package/dist/components/usePluginApi.js.map +1 -0
- package/dist/components/useUploadQueue.d.ts +35 -0
- package/dist/components/useUploadQueue.js +135 -0
- package/dist/components/useUploadQueue.js.map +1 -0
- package/dist/components/useVideoUpload.d.ts +33 -0
- package/dist/components/useVideoUpload.js +87 -0
- package/dist/components/useVideoUpload.js.map +1 -0
- package/dist/core/errors.d.ts +27 -0
- package/dist/core/errors.js +29 -0
- package/dist/core/errors.js.map +1 -0
- package/dist/core/provider.d.ts +347 -0
- package/dist/core/provider.js +13 -0
- package/dist/core/provider.js.map +1 -0
- package/dist/core/registry.d.ts +17 -0
- package/dist/core/registry.js +110 -0
- package/dist/core/registry.js.map +1 -0
- package/dist/core/status.d.ts +15 -0
- package/dist/core/status.js +29 -0
- package/dist/core/status.js.map +1 -0
- package/dist/endpoints/index.d.ts +3 -0
- package/dist/endpoints/index.js +500 -0
- package/dist/endpoints/index.js.map +1 -0
- package/dist/env.d.ts +40 -0
- package/dist/env.js +105 -0
- package/dist/env.js.map +1 -0
- package/dist/exports/bunny.d.ts +16 -0
- package/dist/exports/bunny.js +13 -0
- package/dist/exports/bunny.js.map +1 -0
- package/dist/exports/client.d.ts +22 -0
- package/dist/exports/client.js +18 -0
- package/dist/exports/client.js.map +1 -0
- package/dist/exports/cloudflare.d.ts +18 -0
- package/dist/exports/cloudflare.js +15 -0
- package/dist/exports/cloudflare.js.map +1 -0
- package/dist/exports/mux.d.ts +18 -0
- package/dist/exports/mux.js +15 -0
- package/dist/exports/mux.js.map +1 -0
- package/dist/exports/react.d.ts +25 -0
- package/dist/exports/react.js +18 -0
- package/dist/exports/react.js.map +1 -0
- package/dist/exports/rsc.d.ts +1 -0
- package/dist/exports/rsc.js +4 -0
- package/dist/exports/rsc.js.map +1 -0
- package/dist/exports/testing.d.ts +13 -0
- package/dist/exports/testing.js +9 -0
- package/dist/exports/testing.js.map +1 -0
- package/dist/fields.d.ts +22 -0
- package/dist/fields.js +73 -0
- package/dist/fields.js.map +1 -0
- package/dist/frontend/ClientVideo.d.ts +14 -0
- package/dist/frontend/ClientVideo.js +43 -0
- package/dist/frontend/ClientVideo.js.map +1 -0
- package/dist/frontend/Video.d.ts +32 -0
- package/dist/frontend/Video.js +73 -0
- package/dist/frontend/Video.js.map +1 -0
- package/dist/frontend/VideoIframe.d.ts +35 -0
- package/dist/frontend/VideoIframe.js +60 -0
- package/dist/frontend/VideoIframe.js.map +1 -0
- package/dist/frontend/VideoUploader.d.ts +65 -0
- package/dist/frontend/VideoUploader.js +260 -0
- package/dist/frontend/VideoUploader.js.map +1 -0
- package/dist/frontend/constants.d.ts +10 -0
- package/dist/frontend/constants.js +10 -0
- package/dist/frontend/constants.js.map +1 -0
- package/dist/frontend/converters.d.ts +25 -0
- package/dist/frontend/converters.js +24 -0
- package/dist/frontend/converters.js.map +1 -0
- package/dist/frontend/source.d.ts +80 -0
- package/dist/frontend/source.js +159 -0
- package/dist/frontend/source.js.map +1 -0
- package/dist/frontend/useVideoSource.d.ts +27 -0
- package/dist/frontend/useVideoSource.js +108 -0
- package/dist/frontend/useVideoSource.js.map +1 -0
- package/dist/frontend/useVideoStatus.d.ts +26 -0
- package/dist/frontend/useVideoStatus.js +68 -0
- package/dist/frontend/useVideoStatus.js.map +1 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +15 -0
- package/dist/index.js.map +1 -0
- package/dist/migrate/cfStream.d.ts +108 -0
- package/dist/migrate/cfStream.js +418 -0
- package/dist/migrate/cfStream.js.map +1 -0
- package/dist/options.d.ts +9 -0
- package/dist/options.js +153 -0
- package/dist/options.js.map +1 -0
- package/dist/plugin.d.ts +9 -0
- package/dist/plugin.js +177 -0
- package/dist/plugin.js.map +1 -0
- package/dist/providers/bunny/client.d.ts +78 -0
- package/dist/providers/bunny/client.js +231 -0
- package/dist/providers/bunny/client.js.map +1 -0
- package/dist/providers/bunny/env.d.ts +18 -0
- package/dist/providers/bunny/env.js +31 -0
- package/dist/providers/bunny/env.js.map +1 -0
- package/dist/providers/bunny/mapping.d.ts +39 -0
- package/dist/providers/bunny/mapping.js +123 -0
- package/dist/providers/bunny/mapping.js.map +1 -0
- package/dist/providers/bunny/options.d.ts +92 -0
- package/dist/providers/bunny/options.js +85 -0
- package/dist/providers/bunny/options.js.map +1 -0
- package/dist/providers/bunny/provider.d.ts +70 -0
- package/dist/providers/bunny/provider.js +480 -0
- package/dist/providers/bunny/provider.js.map +1 -0
- package/dist/providers/bunny/signing.d.ts +61 -0
- package/dist/providers/bunny/signing.js +144 -0
- package/dist/providers/bunny/signing.js.map +1 -0
- package/dist/providers/bunny/types.d.ts +153 -0
- package/dist/providers/bunny/types.js +64 -0
- package/dist/providers/bunny/types.js.map +1 -0
- package/dist/providers/bunny/urls.d.ts +49 -0
- package/dist/providers/bunny/urls.js +70 -0
- package/dist/providers/bunny/urls.js.map +1 -0
- package/dist/providers/bunny/webhook.d.ts +32 -0
- package/dist/providers/bunny/webhook.js +75 -0
- package/dist/providers/bunny/webhook.js.map +1 -0
- package/dist/providers/cloudflare/client.d.ts +93 -0
- package/dist/providers/cloudflare/client.js +436 -0
- package/dist/providers/cloudflare/client.js.map +1 -0
- package/dist/providers/cloudflare/env.d.ts +22 -0
- package/dist/providers/cloudflare/env.js +57 -0
- package/dist/providers/cloudflare/env.js.map +1 -0
- package/dist/providers/cloudflare/mapping.d.ts +15 -0
- package/dist/providers/cloudflare/mapping.js +95 -0
- package/dist/providers/cloudflare/mapping.js.map +1 -0
- package/dist/providers/cloudflare/options.d.ts +104 -0
- package/dist/providers/cloudflare/options.js +91 -0
- package/dist/providers/cloudflare/options.js.map +1 -0
- package/dist/providers/cloudflare/provider.d.ts +63 -0
- package/dist/providers/cloudflare/provider.js +445 -0
- package/dist/providers/cloudflare/provider.js.map +1 -0
- package/dist/providers/cloudflare/signing.d.ts +41 -0
- package/dist/providers/cloudflare/signing.js +97 -0
- package/dist/providers/cloudflare/signing.js.map +1 -0
- package/dist/providers/cloudflare/tus.d.ts +24 -0
- package/dist/providers/cloudflare/tus.js +55 -0
- package/dist/providers/cloudflare/tus.js.map +1 -0
- package/dist/providers/cloudflare/types.d.ts +156 -0
- package/dist/providers/cloudflare/types.js +14 -0
- package/dist/providers/cloudflare/types.js.map +1 -0
- package/dist/providers/cloudflare/urls.d.ts +55 -0
- package/dist/providers/cloudflare/urls.js +87 -0
- package/dist/providers/cloudflare/urls.js.map +1 -0
- package/dist/providers/cloudflare/webhook.d.ts +36 -0
- package/dist/providers/cloudflare/webhook.js +83 -0
- package/dist/providers/cloudflare/webhook.js.map +1 -0
- package/dist/providers/mux/client.d.ts +82 -0
- package/dist/providers/mux/client.js +283 -0
- package/dist/providers/mux/client.js.map +1 -0
- package/dist/providers/mux/env.d.ts +21 -0
- package/dist/providers/mux/env.js +61 -0
- package/dist/providers/mux/env.js.map +1 -0
- package/dist/providers/mux/mapping.d.ts +38 -0
- package/dist/providers/mux/mapping.js +111 -0
- package/dist/providers/mux/mapping.js.map +1 -0
- package/dist/providers/mux/options.d.ts +96 -0
- package/dist/providers/mux/options.js +83 -0
- package/dist/providers/mux/options.js.map +1 -0
- package/dist/providers/mux/provider.d.ts +63 -0
- package/dist/providers/mux/provider.js +555 -0
- package/dist/providers/mux/provider.js.map +1 -0
- package/dist/providers/mux/signing.d.ts +45 -0
- package/dist/providers/mux/signing.js +84 -0
- package/dist/providers/mux/signing.js.map +1 -0
- package/dist/providers/mux/types.d.ts +173 -0
- package/dist/providers/mux/types.js +42 -0
- package/dist/providers/mux/types.js.map +1 -0
- package/dist/providers/mux/urls.d.ts +58 -0
- package/dist/providers/mux/urls.js +59 -0
- package/dist/providers/mux/urls.js.map +1 -0
- package/dist/providers/mux/webhook.d.ts +38 -0
- package/dist/providers/mux/webhook.js +115 -0
- package/dist/providers/mux/webhook.js.map +1 -0
- package/dist/service.d.ts +193 -0
- package/dist/service.js +967 -0
- package/dist/service.js.map +1 -0
- package/dist/testing/bunny.d.ts +113 -0
- package/dist/testing/bunny.js +776 -0
- package/dist/testing/bunny.js.map +1 -0
- package/dist/testing/cloudflare.d.ts +101 -0
- package/dist/testing/cloudflare.js +913 -0
- package/dist/testing/cloudflare.js.map +1 -0
- package/dist/testing/index.d.ts +45 -0
- package/dist/testing/index.js +42 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/mux.d.ts +139 -0
- package/dist/testing/mux.js +1053 -0
- package/dist/testing/mux.js.map +1 -0
- package/dist/testing/types.d.ts +90 -0
- package/dist/testing/types.js +9 -0
- package/dist/testing/types.js.map +1 -0
- package/dist/types.d.ts +404 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/dist/utils/access.d.ts +22 -0
- package/dist/utils/access.js +66 -0
- package/dist/utils/access.js.map +1 -0
- package/dist/utils/localReq.d.ts +11 -0
- package/dist/utils/localReq.js +23 -0
- package/dist/utils/localReq.js.map +1 -0
- package/dist/utils/request.d.ts +12 -0
- package/dist/utils/request.js +55 -0
- package/dist/utils/request.js.map +1 -0
- package/dist/utils/version.d.ts +5 -0
- package/dist/utils/version.js +7 -0
- package/dist/utils/version.js.map +1 -0
- package/package.json +175 -4
|
@@ -0,0 +1,1053 @@
|
|
|
1
|
+
import { generateKeyPairSync, randomBytes, randomUUID, verify } from 'node:crypto';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { createServer } from 'node:http';
|
|
4
|
+
import nodePath from 'node:path';
|
|
5
|
+
import { MUX_CHUNK_MULTIPLE } from '../providers/mux/client.js';
|
|
6
|
+
import { MUX_AUDIENCES } from '../providers/mux/signing.js';
|
|
7
|
+
import { createMuxSignatureHeader, MUX_SIGNATURE_HEADER } from '../providers/mux/webhook.js';
|
|
8
|
+
const NEUTRAL_TO_MUX = {
|
|
9
|
+
error: 'errored',
|
|
10
|
+
processing: 'preparing',
|
|
11
|
+
queued: 'preparing',
|
|
12
|
+
ready: 'ready',
|
|
13
|
+
waiting: 'preparing'
|
|
14
|
+
};
|
|
15
|
+
const CORS = {
|
|
16
|
+
'access-control-allow-headers': '*',
|
|
17
|
+
'access-control-allow-methods': 'GET,POST,PUT,PATCH,DELETE,OPTIONS',
|
|
18
|
+
'access-control-allow-origin': '*',
|
|
19
|
+
'access-control-expose-headers': 'Range'
|
|
20
|
+
};
|
|
21
|
+
const json = (res, status, body, headers = {})=>{
|
|
22
|
+
res.writeHead(status, {
|
|
23
|
+
'content-type': 'application/json',
|
|
24
|
+
...headers
|
|
25
|
+
});
|
|
26
|
+
res.end(JSON.stringify(body));
|
|
27
|
+
};
|
|
28
|
+
const muxError = (type, ...messages)=>({
|
|
29
|
+
error: {
|
|
30
|
+
messages,
|
|
31
|
+
type
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
const readBody = (req)=>new Promise((resolve, reject)=>{
|
|
35
|
+
const chunks = [];
|
|
36
|
+
req.on('data', (c)=>chunks.push(c));
|
|
37
|
+
req.on('end', ()=>resolve(Buffer.concat(chunks)));
|
|
38
|
+
req.on('error', reject);
|
|
39
|
+
});
|
|
40
|
+
/** Mux-style ids: long, URL-safe, alphanumeric. */ const newId = ()=>randomBytes(18).toString('base64url').replace(/[-_]/g, 'x');
|
|
41
|
+
const placeholderSvg = '<svg xmlns="http://www.w3.org/2000/svg" width="160" height="90"><rect width="160" height="90" fill="#433"/><polygon points="65,30 65,60 95,45" fill="#fff"/></svg>';
|
|
42
|
+
const RENDITION_FILES = {
|
|
43
|
+
'audio-only': 'audio.m4a',
|
|
44
|
+
highest: 'highest.mp4'
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* An in-memory fake of the Mux Video API, its direct-upload URLs (single or chunked `PUT` with
|
|
48
|
+
* `Content-Range`) and delivery (`stream.mux.com`, `image.mux.com`, `player.mux.com`, with signed
|
|
49
|
+
* tokens checked per audience) for local development and tests: no Mux account needed.
|
|
50
|
+
*
|
|
51
|
+
* ```ts
|
|
52
|
+
* const fake = await startFakeMux()
|
|
53
|
+
* videoPlugin({ providers: [muxVideo(fake.providerOptions)] })
|
|
54
|
+
* ```
|
|
55
|
+
*
|
|
56
|
+
* Text tracks are not fetched from their `url` (the fake usually can't reach your server); the URL is
|
|
57
|
+
* recorded in `trackSources` and the track becomes ready after the processing delay.
|
|
58
|
+
*/ export class FakeMux {
|
|
59
|
+
/** The options `muxVideo()` needs to talk to a fake running at `url` (e.g. in another process). */ static optionsForUrl(url, tokenId = 'fake-token-id', tokenSecret = 'fake-token-secret') {
|
|
60
|
+
const base = url.replace(/\/+$/, '');
|
|
61
|
+
return {
|
|
62
|
+
apiBaseUrl: base,
|
|
63
|
+
delivery: {
|
|
64
|
+
image: `${base}/image`,
|
|
65
|
+
player: `${base}/player`,
|
|
66
|
+
stream: `${base}/stream`
|
|
67
|
+
},
|
|
68
|
+
tokenId,
|
|
69
|
+
tokenSecret
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Asks a fake running at `url` (e.g. in another process) for a signing key, as `POST
|
|
74
|
+
* /system/v1/signing-keys` does at Mux, and returns it as provider options.
|
|
75
|
+
*/ static async signingOptionsForUrl(url, tokenId = 'fake-token-id', tokenSecret = 'fake-token-secret') {
|
|
76
|
+
const res = await fetch(`${url.replace(/\/+$/, '')}/system/v1/signing-keys`, {
|
|
77
|
+
headers: {
|
|
78
|
+
authorization: `Basic ${Buffer.from(`${tokenId}:${tokenSecret}`).toString('base64')}`
|
|
79
|
+
},
|
|
80
|
+
method: 'POST'
|
|
81
|
+
});
|
|
82
|
+
if (!res.ok) {
|
|
83
|
+
throw new Error(`FakeMux: could not create a signing key (HTTP ${res.status})`);
|
|
84
|
+
}
|
|
85
|
+
const { data } = await res.json();
|
|
86
|
+
return {
|
|
87
|
+
signingKey: {
|
|
88
|
+
keyId: data.id,
|
|
89
|
+
privateKey: data.private_key
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
assets = new Map();
|
|
94
|
+
provider = 'mux';
|
|
95
|
+
/** Every request received (for assertions). */ requests = [];
|
|
96
|
+
tokenId;
|
|
97
|
+
tokenSecret;
|
|
98
|
+
/** Sources of the text tracks created through the API. */ trackSources = [];
|
|
99
|
+
uploads = new Map();
|
|
100
|
+
/** Where the fake sends webhooks, if anywhere (see `setWebhook`). */ webhook = null;
|
|
101
|
+
baseUrl = '';
|
|
102
|
+
keys = new Map();
|
|
103
|
+
options;
|
|
104
|
+
server = null;
|
|
105
|
+
timers = new Set();
|
|
106
|
+
constructor(options = {}){
|
|
107
|
+
this.tokenId = options.tokenId ?? 'fake-token-id';
|
|
108
|
+
this.tokenSecret = options.tokenSecret ?? 'fake-token-secret';
|
|
109
|
+
this.options = {
|
|
110
|
+
autoProcess: options.autoProcess ?? true,
|
|
111
|
+
enforceChunkMultiple: options.enforceChunkMultiple ?? true,
|
|
112
|
+
hlsFixtureDir: options.hlsFixtureDir,
|
|
113
|
+
port: options.port ?? 0,
|
|
114
|
+
processingDelayMs: options.processingDelayMs ?? 300,
|
|
115
|
+
publicUrl: options.publicUrl?.replace(/\/+$/, '') || undefined
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
get url() {
|
|
119
|
+
return this.baseUrl;
|
|
120
|
+
}
|
|
121
|
+
get providerOptions() {
|
|
122
|
+
return FakeMux.optionsForUrl(this.baseUrl, this.tokenId, this.tokenSecret);
|
|
123
|
+
}
|
|
124
|
+
localSigningOptions() {
|
|
125
|
+
return {
|
|
126
|
+
signingKey: this.createSigningKey()
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
webhookOptions(secret) {
|
|
130
|
+
return {
|
|
131
|
+
webhook: {
|
|
132
|
+
secret
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
/** Sends signed webhooks for upload and asset events to `url` from now on (`null` stops). */ setWebhook(url, secret = 'fake-webhook-secret') {
|
|
137
|
+
this.webhook = url ? {
|
|
138
|
+
secret,
|
|
139
|
+
url
|
|
140
|
+
} : null;
|
|
141
|
+
}
|
|
142
|
+
async start() {
|
|
143
|
+
this.server = createServer((req, res)=>{
|
|
144
|
+
this.route(req, res).catch((err)=>json(res, 500, muxError('internal_error', err.message)));
|
|
145
|
+
});
|
|
146
|
+
await new Promise((resolve, reject)=>{
|
|
147
|
+
this.server.once('error', reject);
|
|
148
|
+
this.server.listen(this.options.port, '127.0.0.1', ()=>{
|
|
149
|
+
this.server.off('error', reject);
|
|
150
|
+
resolve();
|
|
151
|
+
});
|
|
152
|
+
}).catch((err)=>{
|
|
153
|
+
this.server = null;
|
|
154
|
+
throw err;
|
|
155
|
+
});
|
|
156
|
+
const { port } = this.server.address();
|
|
157
|
+
this.baseUrl = this.options.publicUrl ?? `http://127.0.0.1:${port}`;
|
|
158
|
+
return this;
|
|
159
|
+
}
|
|
160
|
+
async stop() {
|
|
161
|
+
for (const t of this.timers){
|
|
162
|
+
clearTimeout(t);
|
|
163
|
+
}
|
|
164
|
+
this.timers.clear();
|
|
165
|
+
if (this.server) {
|
|
166
|
+
await new Promise((resolve)=>this.server.close(()=>resolve()));
|
|
167
|
+
this.server.closeAllConnections?.();
|
|
168
|
+
this.server = null;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
reset() {
|
|
172
|
+
this.assets.clear();
|
|
173
|
+
this.uploads.clear();
|
|
174
|
+
this.requests.length = 0;
|
|
175
|
+
this.trackSources.length = 0;
|
|
176
|
+
this.webhook = null;
|
|
177
|
+
this.keys.clear();
|
|
178
|
+
}
|
|
179
|
+
// ---------------------------------------------------------------------------
|
|
180
|
+
// Test helpers
|
|
181
|
+
// ---------------------------------------------------------------------------
|
|
182
|
+
/** Registers a new signing key and returns it as Mux does (base64 PEM). */ createSigningKey() {
|
|
183
|
+
const { privateKey, publicKey } = generateKeyPairSync('rsa', {
|
|
184
|
+
modulusLength: 2048
|
|
185
|
+
});
|
|
186
|
+
const keyId = newId();
|
|
187
|
+
this.keys.set(keyId, publicKey);
|
|
188
|
+
const pem = privateKey.export({
|
|
189
|
+
format: 'pem',
|
|
190
|
+
type: 'pkcs1'
|
|
191
|
+
}).toString();
|
|
192
|
+
return {
|
|
193
|
+
keyId,
|
|
194
|
+
privateKey: Buffer.from(pem).toString('base64')
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
addAsset(input = {}) {
|
|
198
|
+
const asset = this.newAsset({
|
|
199
|
+
meta: {
|
|
200
|
+
...input.title ? {
|
|
201
|
+
title: input.title
|
|
202
|
+
} : {},
|
|
203
|
+
...input.creator ? {
|
|
204
|
+
creator_id: input.creator
|
|
205
|
+
} : {}
|
|
206
|
+
},
|
|
207
|
+
playback_policies: [
|
|
208
|
+
input.signedPlayback ? 'signed' : 'public'
|
|
209
|
+
]
|
|
210
|
+
});
|
|
211
|
+
if (input.createdAt) {
|
|
212
|
+
asset.created_at = String(Math.floor(Date.parse(input.createdAt) / 1000));
|
|
213
|
+
}
|
|
214
|
+
this.setStatus(asset.id, input.status ?? 'ready');
|
|
215
|
+
return {
|
|
216
|
+
assetId: asset.id,
|
|
217
|
+
playbackId: asset.playback_ids[0].id
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
assetIds() {
|
|
221
|
+
return [
|
|
222
|
+
...this.assets.keys()
|
|
223
|
+
];
|
|
224
|
+
}
|
|
225
|
+
/** True when an asset has this id, or a direct upload that is still waiting for its file. */ hasAsset(id) {
|
|
226
|
+
return this.assets.has(id) || this.uploads.get(id)?.status === 'waiting';
|
|
227
|
+
}
|
|
228
|
+
/** Removes an asset (or a direct upload) as if it vanished at Mux. */ removeAsset(id) {
|
|
229
|
+
this.assets.delete(id);
|
|
230
|
+
this.uploads.delete(id);
|
|
231
|
+
}
|
|
232
|
+
/** Completes a direct upload (as if the browser had sent the file) and resolves the new asset's id. */ simulateUpload(ref) {
|
|
233
|
+
if (ref.assetId) {
|
|
234
|
+
this.mustGet(ref.assetId);
|
|
235
|
+
return {
|
|
236
|
+
assetId: ref.assetId
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
const upload = this.uploads.get(ref.uploadId ?? '');
|
|
240
|
+
if (!upload) {
|
|
241
|
+
throw new Error(`FakeMux: unknown upload ${String(ref.uploadId)}`);
|
|
242
|
+
}
|
|
243
|
+
if (upload.status === 'waiting') {
|
|
244
|
+
this.completeUpload(upload);
|
|
245
|
+
}
|
|
246
|
+
if (!upload.asset_id) {
|
|
247
|
+
throw new Error(`FakeMux: upload ${upload.id} is ${upload.status}`);
|
|
248
|
+
}
|
|
249
|
+
return {
|
|
250
|
+
assetId: upload.asset_id
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
/** Marks an upload as cancelled, timed out or errored (it then never becomes an asset). */ failUpload(uploadId, status = 'timed_out') {
|
|
254
|
+
const upload = this.uploads.get(uploadId);
|
|
255
|
+
if (!upload) {
|
|
256
|
+
throw new Error(`FakeMux: unknown upload ${uploadId}`);
|
|
257
|
+
}
|
|
258
|
+
upload.status = status;
|
|
259
|
+
if (status === 'errored') {
|
|
260
|
+
upload.error = {
|
|
261
|
+
message: 'The file could not be read',
|
|
262
|
+
type: 'invalid_input'
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
setStatus(assetId, status, error) {
|
|
267
|
+
const asset = this.mustGet(assetId);
|
|
268
|
+
const state = NEUTRAL_TO_MUX[status];
|
|
269
|
+
if (state === 'ready') {
|
|
270
|
+
this.markReady(asset);
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
asset.status = state;
|
|
274
|
+
delete asset.errors;
|
|
275
|
+
if (state === 'errored') {
|
|
276
|
+
asset.errors = {
|
|
277
|
+
messages: [
|
|
278
|
+
error?.message ?? 'The video could not be processed'
|
|
279
|
+
],
|
|
280
|
+
type: error?.code ?? 'invalid_input'
|
|
281
|
+
};
|
|
282
|
+
asset.progress = {
|
|
283
|
+
progress: -1,
|
|
284
|
+
state: 'errored'
|
|
285
|
+
};
|
|
286
|
+
} else {
|
|
287
|
+
asset.progress = status === 'processing' ? {
|
|
288
|
+
progress: 50,
|
|
289
|
+
state: 'transcoding'
|
|
290
|
+
} : {
|
|
291
|
+
progress: 0,
|
|
292
|
+
state: 'ingesting'
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
/** A signed webhook for an asset's current state, as Mux would send it. */ buildWebhook(assetId, secret = this.webhook?.secret ?? 'fake-webhook-secret') {
|
|
297
|
+
const asset = this.mustGet(assetId);
|
|
298
|
+
const type = asset.status === 'ready' ? 'video.asset.ready' : asset.status === 'errored' ? 'video.asset.errored' : 'video.asset.updated';
|
|
299
|
+
return this.signedEvent(this.event(type, 'asset', asset.id, asset), secret);
|
|
300
|
+
}
|
|
301
|
+
/** A signed `video.upload.*` webhook for an upload's current state. */ buildUploadWebhook(uploadId, secret = this.webhook?.secret ?? 'fake-webhook-secret') {
|
|
302
|
+
const upload = this.uploads.get(uploadId);
|
|
303
|
+
if (!upload) {
|
|
304
|
+
throw new Error(`FakeMux: unknown upload ${uploadId}`);
|
|
305
|
+
}
|
|
306
|
+
const type = upload.status === 'asset_created' ? 'video.upload.asset_created' : upload.status === 'cancelled' ? 'video.upload.cancelled' : upload.status === 'errored' ? 'video.upload.errored' : 'video.upload.created';
|
|
307
|
+
return this.signedEvent(this.event(type, 'upload', upload.id, this.publicUpload(upload)), secret);
|
|
308
|
+
}
|
|
309
|
+
/** Signs any event body (e.g. a duplicate or a tampered one). */ signedEvent(event, secret, timestamp) {
|
|
310
|
+
const body = JSON.stringify(event);
|
|
311
|
+
return {
|
|
312
|
+
body,
|
|
313
|
+
headers: {
|
|
314
|
+
'content-type': 'application/json',
|
|
315
|
+
[MUX_SIGNATURE_HEADER]: createMuxSignatureHeader(secret, body, timestamp)
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
event(type, objectType, objectId, data) {
|
|
320
|
+
return {
|
|
321
|
+
attempts: [],
|
|
322
|
+
created_at: new Date().toISOString(),
|
|
323
|
+
data: JSON.parse(JSON.stringify(data)),
|
|
324
|
+
environment: {
|
|
325
|
+
id: 'fake-env',
|
|
326
|
+
name: 'Fake'
|
|
327
|
+
},
|
|
328
|
+
id: randomUUID(),
|
|
329
|
+
object: {
|
|
330
|
+
id: objectId,
|
|
331
|
+
type: objectType
|
|
332
|
+
},
|
|
333
|
+
type
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
// ---------------------------------------------------------------------------
|
|
337
|
+
// Internals
|
|
338
|
+
// ---------------------------------------------------------------------------
|
|
339
|
+
mustGet(assetId) {
|
|
340
|
+
const asset = this.assets.get(assetId);
|
|
341
|
+
if (!asset) {
|
|
342
|
+
throw new Error(`FakeMux: unknown asset ${assetId}`);
|
|
343
|
+
}
|
|
344
|
+
return asset;
|
|
345
|
+
}
|
|
346
|
+
newAsset(settings, uploadId) {
|
|
347
|
+
const id = newId();
|
|
348
|
+
const asset = {
|
|
349
|
+
created_at: String(Math.floor(Date.now() / 1000)),
|
|
350
|
+
id,
|
|
351
|
+
...settings.max_resolution_tier ? {
|
|
352
|
+
max_resolution_tier: settings.max_resolution_tier
|
|
353
|
+
} : {},
|
|
354
|
+
...settings.meta && Object.keys(settings.meta).length ? {
|
|
355
|
+
meta: {
|
|
356
|
+
...settings.meta
|
|
357
|
+
}
|
|
358
|
+
} : {},
|
|
359
|
+
...settings.passthrough ? {
|
|
360
|
+
passthrough: settings.passthrough
|
|
361
|
+
} : {},
|
|
362
|
+
playback_ids: (settings.playback_policies ?? []).map((policy)=>({
|
|
363
|
+
id: newId(),
|
|
364
|
+
policy
|
|
365
|
+
})),
|
|
366
|
+
progress: {
|
|
367
|
+
progress: 0,
|
|
368
|
+
state: 'ingesting'
|
|
369
|
+
},
|
|
370
|
+
status: 'preparing',
|
|
371
|
+
...settings.test ? {
|
|
372
|
+
test: true
|
|
373
|
+
} : {},
|
|
374
|
+
tracks: [],
|
|
375
|
+
...uploadId ? {
|
|
376
|
+
upload_id: uploadId
|
|
377
|
+
} : {},
|
|
378
|
+
video_quality: settings.video_quality ?? 'basic'
|
|
379
|
+
};
|
|
380
|
+
this.assets.set(id, asset);
|
|
381
|
+
return asset;
|
|
382
|
+
}
|
|
383
|
+
markReady(asset) {
|
|
384
|
+
asset.status = 'ready';
|
|
385
|
+
delete asset.errors;
|
|
386
|
+
asset.progress = {
|
|
387
|
+
progress: 100,
|
|
388
|
+
state: 'completed'
|
|
389
|
+
};
|
|
390
|
+
asset.duration = asset.duration && asset.duration > 0 ? asset.duration : 5;
|
|
391
|
+
asset.aspect_ratio = '16:9';
|
|
392
|
+
asset.resolution_tier = '720p';
|
|
393
|
+
asset.max_stored_resolution = 'HD';
|
|
394
|
+
const others = (asset.tracks ?? []).filter((t)=>t.type === 'text');
|
|
395
|
+
asset.tracks = [
|
|
396
|
+
{
|
|
397
|
+
duration: asset.duration,
|
|
398
|
+
id: `${asset.id}-video`,
|
|
399
|
+
max_frame_rate: 30,
|
|
400
|
+
max_height: 720,
|
|
401
|
+
max_width: 1280,
|
|
402
|
+
type: 'video'
|
|
403
|
+
},
|
|
404
|
+
{
|
|
405
|
+
duration: asset.duration,
|
|
406
|
+
id: `${asset.id}-audio`,
|
|
407
|
+
language_code: 'en',
|
|
408
|
+
primary: true,
|
|
409
|
+
status: 'ready',
|
|
410
|
+
type: 'audio'
|
|
411
|
+
},
|
|
412
|
+
...others
|
|
413
|
+
];
|
|
414
|
+
}
|
|
415
|
+
schedule(fn, delay) {
|
|
416
|
+
const timer = setTimeout(()=>{
|
|
417
|
+
this.timers.delete(timer);
|
|
418
|
+
fn();
|
|
419
|
+
}, delay);
|
|
420
|
+
this.timers.add(timer);
|
|
421
|
+
}
|
|
422
|
+
/** Moves a new asset through processing to ready (when `autoProcess`), sending webhooks. */ ingest(asset) {
|
|
423
|
+
void this.sendWebhook(this.event('video.asset.created', 'asset', asset.id, asset));
|
|
424
|
+
if (!this.options.autoProcess) {
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
const delay = this.options.processingDelayMs;
|
|
428
|
+
this.schedule(()=>{
|
|
429
|
+
if (this.assets.get(asset.id) !== asset || asset.status !== 'preparing') {
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
asset.progress = {
|
|
433
|
+
progress: 50,
|
|
434
|
+
state: 'transcoding'
|
|
435
|
+
};
|
|
436
|
+
this.schedule(()=>{
|
|
437
|
+
if (this.assets.get(asset.id) !== asset || asset.status !== 'preparing') {
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
this.markReady(asset);
|
|
441
|
+
void this.sendWebhook(this.event('video.asset.ready', 'asset', asset.id, asset));
|
|
442
|
+
}, delay / 2);
|
|
443
|
+
}, delay / 2);
|
|
444
|
+
}
|
|
445
|
+
completeUpload(upload) {
|
|
446
|
+
const asset = this.newAsset(upload.new_asset_settings ?? {}, upload.id);
|
|
447
|
+
upload.status = 'asset_created';
|
|
448
|
+
upload.asset_id = asset.id;
|
|
449
|
+
void this.sendWebhook(this.event('video.upload.asset_created', 'upload', upload.id, this.publicUpload(upload)));
|
|
450
|
+
this.ingest(asset);
|
|
451
|
+
}
|
|
452
|
+
async sendWebhook(event) {
|
|
453
|
+
if (!this.webhook) {
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
const { body, headers } = this.signedEvent(event, this.webhook.secret);
|
|
457
|
+
await fetch(this.webhook.url, {
|
|
458
|
+
body,
|
|
459
|
+
headers,
|
|
460
|
+
method: 'POST'
|
|
461
|
+
}).catch(()=>undefined);
|
|
462
|
+
}
|
|
463
|
+
publicUpload(upload) {
|
|
464
|
+
const { received: _r, ...rest } = upload;
|
|
465
|
+
return rest;
|
|
466
|
+
}
|
|
467
|
+
findByPlaybackId(playbackId) {
|
|
468
|
+
for (const asset of this.assets.values()){
|
|
469
|
+
const playback = asset.playback_ids?.find((p)=>p.id === playbackId);
|
|
470
|
+
if (playback) {
|
|
471
|
+
return {
|
|
472
|
+
asset,
|
|
473
|
+
playback
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
return null;
|
|
478
|
+
}
|
|
479
|
+
/** Verifies a delivery request: public ids need nothing, signed ids a valid token for `audience`. */ authorizeDelivery(playbackId, audience, token) {
|
|
480
|
+
const found = this.findByPlaybackId(playbackId);
|
|
481
|
+
if (!found) {
|
|
482
|
+
return 404;
|
|
483
|
+
}
|
|
484
|
+
if (found.playback.policy === 'public') {
|
|
485
|
+
return {
|
|
486
|
+
asset: found.asset
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
if (!token) {
|
|
490
|
+
return 403;
|
|
491
|
+
}
|
|
492
|
+
const [h, p, s] = token.split('.');
|
|
493
|
+
if (!h || !p || !s) {
|
|
494
|
+
return 403;
|
|
495
|
+
}
|
|
496
|
+
try {
|
|
497
|
+
const header = JSON.parse(Buffer.from(h, 'base64url').toString());
|
|
498
|
+
const payload = JSON.parse(Buffer.from(p, 'base64url').toString());
|
|
499
|
+
const kid = header.kid ?? payload.kid;
|
|
500
|
+
const key = kid ? this.keys.get(kid) : undefined;
|
|
501
|
+
if (header.alg !== 'RS256' || !key || !verify('RSA-SHA256', Buffer.from(`${h}.${p}`), key, Buffer.from(s, 'base64url'))) {
|
|
502
|
+
return 403;
|
|
503
|
+
}
|
|
504
|
+
if (!payload.exp || payload.exp < Date.now() / 1000 || payload.sub !== playbackId || payload.aud !== MUX_AUDIENCES[audience]) {
|
|
505
|
+
return 403;
|
|
506
|
+
}
|
|
507
|
+
return {
|
|
508
|
+
asset: found.asset
|
|
509
|
+
};
|
|
510
|
+
} catch {
|
|
511
|
+
return 403;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
/** Points every URI in a playlist at `${playbackId}/…` and carries the token along. */ rewritePlaylist(text, prefix, token) {
|
|
515
|
+
const rewrite = (uri)=>/^[a-z]+:\/\//i.test(uri) ? uri : `${prefix}${uri}${token ? `?token=${encodeURIComponent(token)}` : ''}`;
|
|
516
|
+
return text.split('\n').map((line)=>line.startsWith('#') ? line.replace(/URI="([^"]+)"/g, (_m, uri)=>`URI="${rewrite(uri)}"`) : line.trim() ? rewrite(line.trim()) : line).join('\n');
|
|
517
|
+
}
|
|
518
|
+
async serveFixture(res, file, transform) {
|
|
519
|
+
if (!this.options.hlsFixtureDir || !/^[\w-]+\.(?:m3u8|m4s|mp4)$/.test(file)) {
|
|
520
|
+
return false;
|
|
521
|
+
}
|
|
522
|
+
try {
|
|
523
|
+
const body = await readFile(nodePath.join(this.options.hlsFixtureDir, file));
|
|
524
|
+
const type = file.endsWith('.m3u8') ? 'application/vnd.apple.mpegurl' : file.endsWith('.m4s') ? 'video/iso.segment' : 'video/mp4';
|
|
525
|
+
res.writeHead(200, {
|
|
526
|
+
...CORS,
|
|
527
|
+
'content-type': type
|
|
528
|
+
});
|
|
529
|
+
res.end(transform && file.endsWith('.m3u8') ? transform(body.toString('utf8')) : body);
|
|
530
|
+
} catch {
|
|
531
|
+
res.writeHead(404, CORS);
|
|
532
|
+
res.end('Not Found');
|
|
533
|
+
}
|
|
534
|
+
return true;
|
|
535
|
+
}
|
|
536
|
+
deny(res, status) {
|
|
537
|
+
res.writeHead(status, {
|
|
538
|
+
...CORS,
|
|
539
|
+
'content-type': 'text/plain'
|
|
540
|
+
});
|
|
541
|
+
res.end(status === 403 ? 'Forbidden' : status === 412 ? 'Not ready' : 'Not Found');
|
|
542
|
+
}
|
|
543
|
+
async routeDelivery(url, res) {
|
|
544
|
+
const token = url.searchParams.get('token');
|
|
545
|
+
// ---- stream.mux.com ----
|
|
546
|
+
const master = /^\/stream\/([^/.]+)\.m3u8$/.exec(url.pathname);
|
|
547
|
+
if (master) {
|
|
548
|
+
const pid = decodeURIComponent(master[1]);
|
|
549
|
+
const auth = this.authorizeDelivery(pid, 'video', token);
|
|
550
|
+
if (typeof auth === 'number') {
|
|
551
|
+
this.deny(res, auth);
|
|
552
|
+
return true;
|
|
553
|
+
}
|
|
554
|
+
if (auth.asset.status !== 'ready') {
|
|
555
|
+
this.deny(res, 412);
|
|
556
|
+
return true;
|
|
557
|
+
}
|
|
558
|
+
if (await this.serveFixture(res, 'video.m3u8', (text)=>this.rewritePlaylist(text, `${encodeURIComponent(pid)}/`, token))) {
|
|
559
|
+
return true;
|
|
560
|
+
}
|
|
561
|
+
res.writeHead(200, {
|
|
562
|
+
...CORS,
|
|
563
|
+
'content-type': 'application/vnd.apple.mpegurl'
|
|
564
|
+
});
|
|
565
|
+
res.end('#EXTM3U\n#EXT-X-VERSION:6\n#EXT-X-ENDLIST\n');
|
|
566
|
+
return true;
|
|
567
|
+
}
|
|
568
|
+
const streamFile = /^\/stream\/([^/]+)\/(.+)$/.exec(url.pathname);
|
|
569
|
+
if (streamFile) {
|
|
570
|
+
const auth = this.authorizeDelivery(decodeURIComponent(streamFile[1]), 'video', token);
|
|
571
|
+
if (typeof auth === 'number') {
|
|
572
|
+
this.deny(res, auth);
|
|
573
|
+
return true;
|
|
574
|
+
}
|
|
575
|
+
const file = streamFile[2];
|
|
576
|
+
const rendition = auth.asset.static_renditions?.files?.find((f)=>f.name === file);
|
|
577
|
+
if (file.endsWith('.mp4') || file.endsWith('.m4a')) {
|
|
578
|
+
if (rendition) {
|
|
579
|
+
res.writeHead(rendition.status === 'ready' ? 200 : 404, {
|
|
580
|
+
...CORS,
|
|
581
|
+
'content-type': file.endsWith('.m4a') ? 'audio/mp4' : 'video/mp4'
|
|
582
|
+
});
|
|
583
|
+
res.end();
|
|
584
|
+
return true;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
if (await this.serveFixture(res, file, (text)=>this.rewritePlaylist(text, '', token))) {
|
|
588
|
+
return true;
|
|
589
|
+
}
|
|
590
|
+
this.deny(res, 404);
|
|
591
|
+
return true;
|
|
592
|
+
}
|
|
593
|
+
// ---- image.mux.com ----
|
|
594
|
+
const image = /^\/image\/([^/]+)\/(thumbnail|animated|storyboard)\.(\w+)$/.exec(url.pathname);
|
|
595
|
+
if (image) {
|
|
596
|
+
const audience = image[2] === 'thumbnail' ? 'thumbnail' : image[2] === 'animated' ? 'gif' : 'storyboard';
|
|
597
|
+
const auth = this.authorizeDelivery(decodeURIComponent(image[1]), audience, token);
|
|
598
|
+
if (typeof auth === 'number') {
|
|
599
|
+
this.deny(res, auth);
|
|
600
|
+
return true;
|
|
601
|
+
}
|
|
602
|
+
if (image[2] === 'storyboard') {
|
|
603
|
+
res.writeHead(200, {
|
|
604
|
+
...CORS,
|
|
605
|
+
'content-type': image[3] === 'vtt' ? 'text/vtt' : 'application/json'
|
|
606
|
+
});
|
|
607
|
+
res.end(image[3] === 'vtt' ? 'WEBVTT\n' : '{}');
|
|
608
|
+
return true;
|
|
609
|
+
}
|
|
610
|
+
res.writeHead(200, {
|
|
611
|
+
...CORS,
|
|
612
|
+
'content-type': 'image/svg+xml'
|
|
613
|
+
});
|
|
614
|
+
res.end(placeholderSvg);
|
|
615
|
+
return true;
|
|
616
|
+
}
|
|
617
|
+
// ---- player.mux.com ----
|
|
618
|
+
const player = /^\/player\/(?:watch\/)?([^/]+)$/.exec(url.pathname);
|
|
619
|
+
if (player) {
|
|
620
|
+
const pid = decodeURIComponent(player[1]);
|
|
621
|
+
const auth = this.authorizeDelivery(pid, 'video', url.searchParams.get('playback-token'));
|
|
622
|
+
if (typeof auth === 'number') {
|
|
623
|
+
this.deny(res, auth);
|
|
624
|
+
return true;
|
|
625
|
+
}
|
|
626
|
+
const thumbToken = url.searchParams.get('thumbnail-token');
|
|
627
|
+
if (thumbToken && typeof this.authorizeDelivery(pid, 'thumbnail', thumbToken) === 'number') {
|
|
628
|
+
this.deny(res, 403);
|
|
629
|
+
return true;
|
|
630
|
+
}
|
|
631
|
+
res.writeHead(200, {
|
|
632
|
+
'content-type': 'text/html'
|
|
633
|
+
});
|
|
634
|
+
res.end(`<!doctype html><html><body style="margin:0;background:#111;color:#eee;font:14px sans-serif;display:grid;place-items:center;height:100vh"><div data-testid="fake-player">Fake Mux player: ${pid}</div></body></html>`);
|
|
635
|
+
return true;
|
|
636
|
+
}
|
|
637
|
+
return false;
|
|
638
|
+
}
|
|
639
|
+
/** `PUT /upload/:id`: the one-time direct upload URL (single PUT, or chunks with Content-Range). */ async routeUpload(id, req, res) {
|
|
640
|
+
const upload = this.uploads.get(id);
|
|
641
|
+
if (!upload || upload.status !== 'waiting') {
|
|
642
|
+
res.writeHead(upload ? 400 : 404, CORS);
|
|
643
|
+
res.end(upload ? `Upload is ${upload.status}` : 'Not Found');
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
const body = await readBody(req);
|
|
647
|
+
const range = req.headers['content-range'];
|
|
648
|
+
if (!range) {
|
|
649
|
+
upload.received = body.length;
|
|
650
|
+
this.completeUpload(upload);
|
|
651
|
+
res.writeHead(200, CORS);
|
|
652
|
+
res.end();
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
const match = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(String(range));
|
|
656
|
+
if (!match) {
|
|
657
|
+
res.writeHead(400, CORS);
|
|
658
|
+
res.end('Invalid Content-Range');
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
const [start, end, total] = [
|
|
662
|
+
Number(match[1]),
|
|
663
|
+
Number(match[2]),
|
|
664
|
+
Number(match[3])
|
|
665
|
+
];
|
|
666
|
+
// A gap is an error; bytes received twice (a chunk resent after a pause) are ignored, as Google
|
|
667
|
+
// Cloud Storage (behind Mux's upload URLs) does.
|
|
668
|
+
if (start > upload.received || end < start || end >= total || end - start + 1 !== body.length) {
|
|
669
|
+
res.writeHead(400, CORS);
|
|
670
|
+
res.end('Content-Range does not match the bytes received so far');
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
const last = end + 1 === total;
|
|
674
|
+
if (this.options.enforceChunkMultiple && !last && body.length % MUX_CHUNK_MULTIPLE !== 0) {
|
|
675
|
+
res.writeHead(400, CORS);
|
|
676
|
+
res.end('Chunks must be a multiple of 256 KiB');
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
upload.received = Math.max(upload.received, end + 1);
|
|
680
|
+
if (upload.received < total) {
|
|
681
|
+
res.writeHead(308, {
|
|
682
|
+
...CORS,
|
|
683
|
+
range: `bytes=0-${upload.received - 1}`
|
|
684
|
+
});
|
|
685
|
+
res.end();
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
this.completeUpload(upload);
|
|
689
|
+
res.writeHead(200, CORS);
|
|
690
|
+
res.end();
|
|
691
|
+
}
|
|
692
|
+
async route(req, res) {
|
|
693
|
+
const url = new URL(req.url ?? '/', this.baseUrl || 'http://127.0.0.1');
|
|
694
|
+
const method = (req.method ?? 'GET').toUpperCase();
|
|
695
|
+
this.requests.push({
|
|
696
|
+
method,
|
|
697
|
+
path: `${url.pathname}${url.search}`
|
|
698
|
+
});
|
|
699
|
+
if (method === 'OPTIONS') {
|
|
700
|
+
res.writeHead(204, CORS);
|
|
701
|
+
res.end();
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
// ---- Test control, the same on every fake: POST /__fake/assets/:id/status { status, error? } ----
|
|
705
|
+
const assetControl = /^\/__fake\/assets\/([^/]+)\/status$/.exec(url.pathname);
|
|
706
|
+
if (assetControl && method === 'POST') {
|
|
707
|
+
const id = decodeURIComponent(assetControl[1]);
|
|
708
|
+
if (!this.assets.has(id)) {
|
|
709
|
+
return json(res, 404, muxError('not_found', 'Asset not found'), CORS);
|
|
710
|
+
}
|
|
711
|
+
const body = JSON.parse((await readBody(req)).toString() || '{}');
|
|
712
|
+
if (!body.status || !(body.status in NEUTRAL_TO_MUX)) {
|
|
713
|
+
return json(res, 400, muxError('invalid_parameters', 'status is required'), CORS);
|
|
714
|
+
}
|
|
715
|
+
this.setStatus(id, body.status, body.error);
|
|
716
|
+
return json(res, 200, {
|
|
717
|
+
data: this.mustGet(id)
|
|
718
|
+
}, CORS);
|
|
719
|
+
}
|
|
720
|
+
// ---- Test control (Mux fake only): POST /__fake/webhook { url, secret } ----
|
|
721
|
+
if (url.pathname === '/__fake/webhook' && method === 'POST') {
|
|
722
|
+
const body = JSON.parse((await readBody(req)).toString() || '{}');
|
|
723
|
+
this.setWebhook(body.url ?? null, body.secret);
|
|
724
|
+
return json(res, 200, {
|
|
725
|
+
data: {
|
|
726
|
+
url: body.url ?? null
|
|
727
|
+
}
|
|
728
|
+
}, CORS);
|
|
729
|
+
}
|
|
730
|
+
const uploadMatch = /^\/upload\/([^/]+)$/.exec(url.pathname);
|
|
731
|
+
if (uploadMatch && method === 'PUT') {
|
|
732
|
+
return this.routeUpload(decodeURIComponent(uploadMatch[1]), req, res);
|
|
733
|
+
}
|
|
734
|
+
if (method === 'GET' && await this.routeDelivery(url, res)) {
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
737
|
+
// ---- API ----
|
|
738
|
+
if (!url.pathname.startsWith('/video/v1/') && !url.pathname.startsWith('/system/v1/')) {
|
|
739
|
+
return json(res, 404, muxError('not_found', 'Not Found'));
|
|
740
|
+
}
|
|
741
|
+
const expected = `Basic ${Buffer.from(`${this.tokenId}:${this.tokenSecret}`).toString('base64')}`;
|
|
742
|
+
if (req.headers.authorization !== expected) {
|
|
743
|
+
return json(res, 401, muxError('unauthorized', 'Unauthorized request'));
|
|
744
|
+
}
|
|
745
|
+
const raw = await readBody(req);
|
|
746
|
+
let body = {};
|
|
747
|
+
if (raw.length) {
|
|
748
|
+
try {
|
|
749
|
+
body = JSON.parse(raw.toString('utf8'));
|
|
750
|
+
} catch {
|
|
751
|
+
return json(res, 400, muxError('invalid_parameters', 'Invalid JSON'));
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
const segments = url.pathname.split('/').filter(Boolean).slice(2) // drop "video|system", "v1"
|
|
755
|
+
;
|
|
756
|
+
const [first, second, third, fourth, fifth] = segments;
|
|
757
|
+
if (url.pathname.startsWith('/system/v1/')) {
|
|
758
|
+
if (first === 'signing-keys') {
|
|
759
|
+
if (method === 'POST' && !second) {
|
|
760
|
+
const { keyId, privateKey } = this.createSigningKey();
|
|
761
|
+
return json(res, 201, {
|
|
762
|
+
data: {
|
|
763
|
+
created_at: String(Math.floor(Date.now() / 1000)),
|
|
764
|
+
id: keyId,
|
|
765
|
+
private_key: privateKey
|
|
766
|
+
}
|
|
767
|
+
});
|
|
768
|
+
}
|
|
769
|
+
if (method === 'GET' && !second) {
|
|
770
|
+
return json(res, 200, {
|
|
771
|
+
data: [
|
|
772
|
+
...this.keys.keys()
|
|
773
|
+
].map((id)=>({
|
|
774
|
+
created_at: '0',
|
|
775
|
+
id
|
|
776
|
+
}))
|
|
777
|
+
});
|
|
778
|
+
}
|
|
779
|
+
if (method === 'DELETE' && second) {
|
|
780
|
+
this.keys.delete(second);
|
|
781
|
+
res.writeHead(204);
|
|
782
|
+
res.end();
|
|
783
|
+
return;
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
return json(res, 404, muxError('not_found', 'Not Found'));
|
|
787
|
+
}
|
|
788
|
+
if (first === 'uploads') {
|
|
789
|
+
if (!second && method === 'POST') {
|
|
790
|
+
if (typeof body.cors_origin !== 'string' || !body.cors_origin) {
|
|
791
|
+
return json(res, 400, muxError('invalid_parameters', 'cors_origin is required'));
|
|
792
|
+
}
|
|
793
|
+
const id = newId();
|
|
794
|
+
const upload = {
|
|
795
|
+
cors_origin: body.cors_origin,
|
|
796
|
+
id,
|
|
797
|
+
new_asset_settings: body.new_asset_settings ?? {},
|
|
798
|
+
received: 0,
|
|
799
|
+
status: 'waiting',
|
|
800
|
+
...body.test ? {
|
|
801
|
+
test: true
|
|
802
|
+
} : {},
|
|
803
|
+
timeout: typeof body.timeout === 'number' ? body.timeout : 3600,
|
|
804
|
+
url: `${this.baseUrl}/upload/${id}`
|
|
805
|
+
};
|
|
806
|
+
this.uploads.set(id, upload);
|
|
807
|
+
return json(res, 201, {
|
|
808
|
+
data: this.publicUpload(upload)
|
|
809
|
+
});
|
|
810
|
+
}
|
|
811
|
+
const upload = second ? this.uploads.get(second) : undefined;
|
|
812
|
+
if (!upload) {
|
|
813
|
+
return json(res, 404, muxError('not_found', 'Upload not found'));
|
|
814
|
+
}
|
|
815
|
+
if (!third && method === 'GET') {
|
|
816
|
+
return json(res, 200, {
|
|
817
|
+
data: this.publicUpload(upload)
|
|
818
|
+
});
|
|
819
|
+
}
|
|
820
|
+
if (third === 'cancel' && method === 'PUT') {
|
|
821
|
+
if (upload.status !== 'waiting') {
|
|
822
|
+
return json(res, 400, muxError('invalid_parameters', `Upload is ${upload.status}`));
|
|
823
|
+
}
|
|
824
|
+
upload.status = 'cancelled';
|
|
825
|
+
return json(res, 200, {
|
|
826
|
+
data: this.publicUpload(upload)
|
|
827
|
+
});
|
|
828
|
+
}
|
|
829
|
+
return json(res, 404, muxError('not_found', 'Not Found'));
|
|
830
|
+
}
|
|
831
|
+
if (first !== 'assets') {
|
|
832
|
+
return json(res, 404, muxError('not_found', 'Not Found'));
|
|
833
|
+
}
|
|
834
|
+
if (!second) {
|
|
835
|
+
if (method === 'POST') {
|
|
836
|
+
const input = Array.isArray(body.inputs) ? body.inputs[0] : undefined;
|
|
837
|
+
if (!input?.url) {
|
|
838
|
+
return json(res, 400, muxError('invalid_parameters', 'inputs[0].url is required'));
|
|
839
|
+
}
|
|
840
|
+
const asset = this.newAsset(body);
|
|
841
|
+
this.ingest(asset);
|
|
842
|
+
return json(res, 201, {
|
|
843
|
+
data: asset
|
|
844
|
+
});
|
|
845
|
+
}
|
|
846
|
+
if (method === 'GET') {
|
|
847
|
+
const limit = Math.max(1, Math.min(Number(url.searchParams.get('limit') ?? 25), 100));
|
|
848
|
+
const cursor = url.searchParams.get('cursor');
|
|
849
|
+
const offset = cursor ? Number(Buffer.from(cursor, 'base64url').toString()) : (Math.max(1, Number(url.searchParams.get('page') ?? 1)) - 1) * limit;
|
|
850
|
+
let list = [
|
|
851
|
+
...this.assets.values()
|
|
852
|
+
].sort((a, b)=>Number(b.created_at ?? 0) - Number(a.created_at ?? 0));
|
|
853
|
+
const uploadId = url.searchParams.get('upload_id');
|
|
854
|
+
if (uploadId) {
|
|
855
|
+
list = list.filter((a)=>a.upload_id === uploadId);
|
|
856
|
+
}
|
|
857
|
+
const page = list.slice(offset, offset + limit);
|
|
858
|
+
const next = offset + limit < list.length ? Buffer.from(String(offset + limit)).toString('base64url') : null;
|
|
859
|
+
return json(res, 200, {
|
|
860
|
+
data: page,
|
|
861
|
+
next_cursor: next
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
const asset = second ? this.assets.get(second) : undefined;
|
|
866
|
+
if (!asset) {
|
|
867
|
+
return json(res, 404, muxError('not_found', 'Asset not found'));
|
|
868
|
+
}
|
|
869
|
+
if (!third) {
|
|
870
|
+
if (method === 'GET') {
|
|
871
|
+
return json(res, 200, {
|
|
872
|
+
data: asset
|
|
873
|
+
});
|
|
874
|
+
}
|
|
875
|
+
if (method === 'PATCH') {
|
|
876
|
+
if (body.meta && typeof body.meta === 'object') {
|
|
877
|
+
asset.meta = body.meta;
|
|
878
|
+
}
|
|
879
|
+
if (typeof body.passthrough === 'string') {
|
|
880
|
+
asset.passthrough = body.passthrough;
|
|
881
|
+
}
|
|
882
|
+
if (typeof body.thumbnail_time === 'number') {
|
|
883
|
+
asset.thumbnail_time = body.thumbnail_time;
|
|
884
|
+
}
|
|
885
|
+
return json(res, 200, {
|
|
886
|
+
data: asset
|
|
887
|
+
});
|
|
888
|
+
}
|
|
889
|
+
if (method === 'DELETE') {
|
|
890
|
+
this.assets.delete(asset.id);
|
|
891
|
+
res.writeHead(204);
|
|
892
|
+
res.end();
|
|
893
|
+
return;
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
if (third === 'playback-ids') {
|
|
897
|
+
if (!fourth && method === 'POST') {
|
|
898
|
+
const policy = body.policy;
|
|
899
|
+
if (policy !== 'public' && policy !== 'signed') {
|
|
900
|
+
return json(res, 400, muxError('invalid_parameters', 'policy must be public or signed'));
|
|
901
|
+
}
|
|
902
|
+
const playback = {
|
|
903
|
+
id: newId(),
|
|
904
|
+
policy
|
|
905
|
+
};
|
|
906
|
+
asset.playback_ids = [
|
|
907
|
+
...asset.playback_ids ?? [],
|
|
908
|
+
playback
|
|
909
|
+
];
|
|
910
|
+
return json(res, 201, {
|
|
911
|
+
data: playback
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
if (fourth && method === 'DELETE') {
|
|
915
|
+
if (!asset.playback_ids?.some((p)=>p.id === fourth)) {
|
|
916
|
+
return json(res, 404, muxError('not_found', 'Playback ID not found'));
|
|
917
|
+
}
|
|
918
|
+
asset.playback_ids = asset.playback_ids.filter((p)=>p.id !== fourth);
|
|
919
|
+
res.writeHead(204);
|
|
920
|
+
res.end();
|
|
921
|
+
return;
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
if (third === 'tracks') {
|
|
925
|
+
if (!fourth && method === 'POST') {
|
|
926
|
+
if (typeof body.url !== 'string' || body.type !== 'text' || typeof body.language_code !== 'string') {
|
|
927
|
+
return json(res, 400, muxError('invalid_parameters', 'url, type and language_code are required'));
|
|
928
|
+
}
|
|
929
|
+
if (asset.status !== 'ready') {
|
|
930
|
+
return json(res, 400, muxError('invalid_parameters', 'Asset is not ready'));
|
|
931
|
+
}
|
|
932
|
+
const track = {
|
|
933
|
+
closed_captions: Boolean(body.closed_captions),
|
|
934
|
+
id: newId(),
|
|
935
|
+
language_code: body.language_code,
|
|
936
|
+
...typeof body.name === 'string' ? {
|
|
937
|
+
name: body.name
|
|
938
|
+
} : {},
|
|
939
|
+
status: 'preparing',
|
|
940
|
+
text_source: 'uploaded',
|
|
941
|
+
text_type: 'subtitles',
|
|
942
|
+
type: 'text'
|
|
943
|
+
};
|
|
944
|
+
asset.tracks = [
|
|
945
|
+
...asset.tracks ?? [],
|
|
946
|
+
track
|
|
947
|
+
];
|
|
948
|
+
this.trackSources.push({
|
|
949
|
+
assetId: asset.id,
|
|
950
|
+
language: body.language_code,
|
|
951
|
+
trackId: track.id,
|
|
952
|
+
url: body.url
|
|
953
|
+
});
|
|
954
|
+
this.schedule(()=>{
|
|
955
|
+
track.status = 'ready';
|
|
956
|
+
}, this.options.processingDelayMs);
|
|
957
|
+
return json(res, 201, {
|
|
958
|
+
data: track
|
|
959
|
+
});
|
|
960
|
+
}
|
|
961
|
+
const track = asset.tracks?.find((t)=>t.id === fourth);
|
|
962
|
+
if (!track) {
|
|
963
|
+
return json(res, 404, muxError('not_found', 'Track not found'));
|
|
964
|
+
}
|
|
965
|
+
if (!fifth && method === 'DELETE') {
|
|
966
|
+
asset.tracks = asset.tracks.filter((t)=>t !== track);
|
|
967
|
+
res.writeHead(204);
|
|
968
|
+
res.end();
|
|
969
|
+
return;
|
|
970
|
+
}
|
|
971
|
+
if (fifth === 'generate-subtitles' && method === 'POST') {
|
|
972
|
+
if (track.type !== 'audio') {
|
|
973
|
+
return json(res, 400, muxError('invalid_parameters', 'Subtitles can only be generated from an audio track'));
|
|
974
|
+
}
|
|
975
|
+
const requested = Array.isArray(body.generated_subtitles) ? body.generated_subtitles : [];
|
|
976
|
+
const created = requested.map((s)=>({
|
|
977
|
+
id: newId(),
|
|
978
|
+
language_code: s.language_code === 'auto' ? track.language_code ?? 'en' : s.language_code,
|
|
979
|
+
name: s.name,
|
|
980
|
+
status: 'preparing',
|
|
981
|
+
text_source: 'generated_vod',
|
|
982
|
+
text_type: 'subtitles',
|
|
983
|
+
type: 'text'
|
|
984
|
+
}));
|
|
985
|
+
asset.tracks = [
|
|
986
|
+
...asset.tracks ?? [],
|
|
987
|
+
...created
|
|
988
|
+
];
|
|
989
|
+
this.schedule(()=>{
|
|
990
|
+
for (const t of created){
|
|
991
|
+
t.status = 'ready';
|
|
992
|
+
}
|
|
993
|
+
}, this.options.processingDelayMs);
|
|
994
|
+
return json(res, 201, {
|
|
995
|
+
data: created
|
|
996
|
+
});
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
if (third === 'static-renditions') {
|
|
1000
|
+
if (!fourth && method === 'POST') {
|
|
1001
|
+
const resolution = body.resolution;
|
|
1002
|
+
const name = RENDITION_FILES[resolution];
|
|
1003
|
+
if (!name) {
|
|
1004
|
+
return json(res, 400, muxError('invalid_parameters', 'The fake supports highest and audio-only'));
|
|
1005
|
+
}
|
|
1006
|
+
const files = asset.static_renditions?.files ?? [];
|
|
1007
|
+
if (files.some((f)=>f.resolution === resolution)) {
|
|
1008
|
+
return json(res, 400, muxError('invalid_parameters', 'Static rendition already exists'));
|
|
1009
|
+
}
|
|
1010
|
+
const file = {
|
|
1011
|
+
ext: name.endsWith('.m4a') ? 'm4a' : 'mp4',
|
|
1012
|
+
id: newId(),
|
|
1013
|
+
name,
|
|
1014
|
+
resolution,
|
|
1015
|
+
status: 'preparing',
|
|
1016
|
+
type: 'standard'
|
|
1017
|
+
};
|
|
1018
|
+
asset.static_renditions = {
|
|
1019
|
+
files: [
|
|
1020
|
+
...files,
|
|
1021
|
+
file
|
|
1022
|
+
]
|
|
1023
|
+
};
|
|
1024
|
+
this.schedule(()=>{
|
|
1025
|
+
file.status = 'ready';
|
|
1026
|
+
void this.sendWebhook(this.event('video.asset.static_rendition.ready', 'asset', asset.id, {
|
|
1027
|
+
...file,
|
|
1028
|
+
asset_id: asset.id
|
|
1029
|
+
}));
|
|
1030
|
+
}, this.options.processingDelayMs);
|
|
1031
|
+
return json(res, 201, {
|
|
1032
|
+
data: file
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
if (fourth && method === 'DELETE') {
|
|
1036
|
+
const files = asset.static_renditions?.files ?? [];
|
|
1037
|
+
if (!files.some((f)=>f.id === fourth)) {
|
|
1038
|
+
return json(res, 404, muxError('not_found', 'Static rendition not found'));
|
|
1039
|
+
}
|
|
1040
|
+
asset.static_renditions = {
|
|
1041
|
+
files: files.filter((f)=>f.id !== fourth)
|
|
1042
|
+
};
|
|
1043
|
+
res.writeHead(204);
|
|
1044
|
+
res.end();
|
|
1045
|
+
return;
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
return json(res, 404, muxError('not_found', 'Not Found'));
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
/** Starts a fake Mux server. Remember to `await fake.stop()`. */ export const startFakeMux = (options)=>new FakeMux(options).start();
|
|
1052
|
+
|
|
1053
|
+
//# sourceMappingURL=mux.js.map
|