@valbuild/server 0.140.0 → 0.141.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.
@@ -8,7 +8,7 @@ import path__default from 'path';
8
8
  import fs from 'fs';
9
9
  import vm from 'node:vm';
10
10
  import { Module } from 'node:module';
11
- import { isSchemaSourceFixError, resolveSchemaSourceFixForError, Patch, getErrorMessageFromUnknownJson, PatchId as PatchId$1, JSONValue, PatchGroup, newestCommitSha, SerializedSchema, VAL_ENABLE_COOKIE_NAME, VAL_STATE_COOKIE, VAL_SESSION_COOKIE, parseJob, VAL_STUDIO_HEADER, Api } from '@valbuild/shared/internal';
11
+ import { isSchemaSourceFixError, resolveSchemaSourceFixForError, Patch, getErrorMessageFromUnknownJson, PatchId as PatchId$1, JSONValue, PatchGroup, newestCommitSha, SerializedSchema, VAL_ENABLE_COOKIE_NAME, VAL_STATE_COOKIE, VAL_SESSION_COOKIE, parseJob, VAL_STUDIO_HEADER, Api, traverseSchemaSource } from '@valbuild/shared/internal';
12
12
  import { createUIRequestHandler } from '@valbuild/ui/server';
13
13
  import crypto$1 from 'crypto';
14
14
  import z$1, { z } from 'zod';
@@ -18,6 +18,7 @@ import net from 'node:net';
18
18
  import sizeOf from 'image-size';
19
19
  import { fromError } from 'zod-validation-error';
20
20
  import os from 'os';
21
+ import { Buffer as Buffer$1 } from 'buffer';
21
22
  import { transform } from 'sucrase';
22
23
  import http$1 from 'http';
23
24
  import https$1 from 'https';
@@ -3181,6 +3182,291 @@ function readableError(error) {
3181
3182
  }
3182
3183
  }
3183
3184
 
3185
+ /**
3186
+ * The `Range` request header, for the one route that serves bytes a player
3187
+ * seeks in: `/files`.
3188
+ *
3189
+ * A `<video>` element asks for ranges as a matter of course, and Safari will
3190
+ * not play a video at all from a server that does not answer them. An HLS
3191
+ * stream whose segments are byte ranges of one file (`#EXT-X-BYTERANGE`) asks
3192
+ * for nothing else.
3193
+ *
3194
+ * Only a single range is honoured. A multi-range request (`bytes=0-1,5-6`) is
3195
+ * answered with the whole file, which RFC 9110 permits, and nothing that plays
3196
+ * media sends one. A header that does not parse is ignored the same way.
3197
+ */
3198
+
3199
+ function parseRangeHeader(header, size) {
3200
+ if (!header) {
3201
+ return {
3202
+ kind: "none"
3203
+ };
3204
+ }
3205
+ const match = /^\s*bytes\s*=\s*(.*)$/i.exec(header);
3206
+ if (!match) {
3207
+ return {
3208
+ kind: "none"
3209
+ };
3210
+ }
3211
+ const spec = match[1].trim();
3212
+ if (spec.includes(",")) {
3213
+ return {
3214
+ kind: "none"
3215
+ };
3216
+ }
3217
+ const suffix = /^-(\d+)$/.exec(spec);
3218
+ if (suffix) {
3219
+ const length = Number(suffix[1]);
3220
+ if (length === 0 || size === 0) {
3221
+ return {
3222
+ kind: "unsatisfiable"
3223
+ };
3224
+ }
3225
+ return {
3226
+ kind: "range",
3227
+ start: Math.max(0, size - length),
3228
+ end: size - 1
3229
+ };
3230
+ }
3231
+ const bounded = /^(\d+)-(\d*)$/.exec(spec);
3232
+ if (!bounded) {
3233
+ return {
3234
+ kind: "none"
3235
+ };
3236
+ }
3237
+ const start = Number(bounded[1]);
3238
+ const end = bounded[2] === "" ? undefined : Number(bounded[2]);
3239
+ if (end !== undefined && end < start) {
3240
+ // Syntactically invalid (RFC 9110 §14.1.1): ignored, not refused.
3241
+ return {
3242
+ kind: "none"
3243
+ };
3244
+ }
3245
+ if (start >= size) {
3246
+ return {
3247
+ kind: "unsatisfiable"
3248
+ };
3249
+ }
3250
+ return {
3251
+ kind: "range",
3252
+ start,
3253
+ end: Math.min(end ?? size - 1, size - 1)
3254
+ };
3255
+ }
3256
+
3257
+ /**
3258
+ * The little of HLS (RFC 8216) the server has to read: the variants of a
3259
+ * master playlist, the segment durations of a media playlist, and every URI a
3260
+ * playlist names.
3261
+ *
3262
+ * Deliberately a line scanner rather than a parser. The playlists Val reads are
3263
+ * the ones the Studio wrote, and the questions asked of them are small — "how
3264
+ * big is the largest rendition", "how long is it", "where does each URI
3265
+ * point" — so a full model of the format would be code nothing exercises.
3266
+ */
3267
+
3268
+ /** One `#EXT-X-STREAM-INF` entry of a master playlist. */
3269
+
3270
+ /** Lines of a playlist, with Windows line endings tolerated. */
3271
+ function linesOf(text) {
3272
+ return text.split(/\r?\n/);
3273
+ }
3274
+
3275
+ /**
3276
+ * The attributes of a tag, e.g. the part after `#EXT-X-STREAM-INF:`.
3277
+ *
3278
+ * Quoted values may contain commas (`CODECS="avc1.64001f,mp4a.40.2"`), which
3279
+ * is why this is not a `split(",")`. Quotes are removed from the values.
3280
+ */
3281
+ function parseHlsAttributes(list) {
3282
+ const attributes = {};
3283
+ const re = /([A-Z0-9-]+)=("[^"]*"|[^,]*)/g;
3284
+ let match;
3285
+ while ((match = re.exec(list)) !== null) {
3286
+ const [, name, rawValue] = match;
3287
+ attributes[name] = rawValue.startsWith('"') && rawValue.endsWith('"') ? rawValue.slice(1, -1) : rawValue.trim();
3288
+ }
3289
+ return attributes;
3290
+ }
3291
+
3292
+ /** Whether a playlist is a master (multivariant) playlist. */
3293
+ function isHlsMasterPlaylist(text) {
3294
+ return linesOf(text).some(line => line.trim().startsWith("#EXT-X-STREAM-INF:"));
3295
+ }
3296
+
3297
+ /** The variants of a master playlist, in the order they are listed. */
3298
+ function parseHlsMasterVariants(text) {
3299
+ const variants = [];
3300
+ let pending = null;
3301
+ for (const rawLine of linesOf(text)) {
3302
+ const line = rawLine.trim();
3303
+ if (line === "") {
3304
+ continue;
3305
+ }
3306
+ if (line.startsWith("#EXT-X-STREAM-INF:")) {
3307
+ const attributes = parseHlsAttributes(line.slice("#EXT-X-STREAM-INF:".length));
3308
+ const variant = {};
3309
+ const bandwidth = Number(attributes["BANDWIDTH"]);
3310
+ if (attributes["BANDWIDTH"] !== undefined && Number.isFinite(bandwidth)) {
3311
+ variant.bandwidth = bandwidth;
3312
+ }
3313
+ const resolution = /^(\d+)x(\d+)$/.exec(attributes["RESOLUTION"] ?? "");
3314
+ if (resolution) {
3315
+ variant.width = Number(resolution[1]);
3316
+ variant.height = Number(resolution[2]);
3317
+ }
3318
+ pending = variant;
3319
+ continue;
3320
+ }
3321
+ if (line.startsWith("#")) {
3322
+ continue;
3323
+ }
3324
+ // The URI line that follows a STREAM-INF tag belongs to it.
3325
+ if (pending) {
3326
+ variants.push({
3327
+ ...pending,
3328
+ uri: line
3329
+ });
3330
+ pending = null;
3331
+ }
3332
+ }
3333
+ return variants;
3334
+ }
3335
+
3336
+ /**
3337
+ * The variant whose dimensions describe the video: the largest picture, and
3338
+ * among equally large ones the highest bandwidth. `undefined` when no variant
3339
+ * declares a `RESOLUTION`.
3340
+ */
3341
+ function largestHlsVariant(variants) {
3342
+ let best;
3343
+ for (const variant of variants) {
3344
+ const {
3345
+ width,
3346
+ height
3347
+ } = variant;
3348
+ if (width === undefined || height === undefined) {
3349
+ continue;
3350
+ }
3351
+ if (!best || width * height > best.width * best.height || width * height === best.width * best.height && (variant.bandwidth ?? 0) > (best.bandwidth ?? 0)) {
3352
+ best = {
3353
+ ...variant,
3354
+ width,
3355
+ height
3356
+ };
3357
+ }
3358
+ }
3359
+ return best;
3360
+ }
3361
+
3362
+ /**
3363
+ * The sum of a media playlist's `#EXTINF` durations, in seconds, or
3364
+ * `undefined` when it has none (a master playlist, or not a playlist).
3365
+ */
3366
+ function sumHlsSegmentDurations(text) {
3367
+ let total = 0;
3368
+ let found = false;
3369
+ for (const rawLine of linesOf(text)) {
3370
+ const line = rawLine.trim();
3371
+ if (!line.startsWith("#EXTINF:")) {
3372
+ continue;
3373
+ }
3374
+ const seconds = Number.parseFloat(line.slice("#EXTINF:".length));
3375
+ if (Number.isFinite(seconds)) {
3376
+ total += seconds;
3377
+ found = true;
3378
+ }
3379
+ }
3380
+ return found ? total : undefined;
3381
+ }
3382
+
3383
+ /**
3384
+ * Rewrite every URI a playlist names, leaving everything else byte for byte.
3385
+ *
3386
+ * URIs are the non-comment lines (segments, variant playlists) and the `URI`
3387
+ * attribute of tags such as `#EXT-X-MAP` and `#EXT-X-MEDIA`. Line endings are
3388
+ * kept as they were.
3389
+ */
3390
+ function mapHlsUris(text, map) {
3391
+ return text.split(/(\r?\n)/).map(part => {
3392
+ if (part === "\n" || part === "\r\n") {
3393
+ return part;
3394
+ }
3395
+ const trimmed = part.trim();
3396
+ if (trimmed === "") {
3397
+ return part;
3398
+ }
3399
+ if (trimmed.startsWith("#")) {
3400
+ // Only an attribute that is exactly `URI` — preceded by the tag's
3401
+ // colon or a comma — and not, say, a `KEYFORMAT-URI` lookalike.
3402
+ return part.replace(/([:,]\s*)URI="([^"]*)"/g, (_match, before, uri) => `${before}URI="${map(uri)}"`);
3403
+ }
3404
+ const leading = part.slice(0, part.indexOf(trimmed));
3405
+ const trailing = part.slice(part.indexOf(trimmed) + trimmed.length);
3406
+ return `${leading}${map(trimmed)}${trailing}`;
3407
+ }).join("");
3408
+ }
3409
+
3410
+ /**
3411
+ * An HLS playlist served as a DRAFT, with every URI in it pointed at the draft
3412
+ * endpoint.
3413
+ *
3414
+ * Why this exists: a draft is served from `/api/val/files<path>?patch_id=…`,
3415
+ * and a player resolves the playlist's URIs against that URL. A RELATIVE URI
3416
+ * (`720p.m3u8`, how a local stream is written so it works wherever the
3417
+ * directory is served from) resolves to `/api/val/files/public/val/x/720p.m3u8`
3418
+ * — the query string is dropped by URL resolution, so the `patch_id` is gone,
3419
+ * and the endpoint looks for a PUBLISHED file that does not exist yet. An
3420
+ * ABSOLUTE remote ref (how a remote stream is written, because the content host
3421
+ * addresses files by hash) points at the content host, which has nothing until
3422
+ * publish. Either way the master plays and nothing it names does.
3423
+ *
3424
+ * So each URI is rewritten to the URL `Internal.mediaUrl` gives the same file
3425
+ * as a draft. Every file of one upload is in the same patch, so they share the
3426
+ * `patch_id` the playlist itself was requested with.
3427
+ *
3428
+ * What is NOT rewritten, and why:
3429
+ * - an absolute URL that is not a Val remote ref (another host's stream): it
3430
+ * was never in a patch;
3431
+ * - a root-relative URI (`/val/x/720p.mp4`): the Studio never writes one, and
3432
+ * it already names a published URL, so it is not this function's to guess at.
3433
+ *
3434
+ * Pure, and the whole rule: the `/files` route calls it and nothing else.
3435
+ */
3436
+ function rewriteDraftPlaylist(playlist, options) {
3437
+ return mapHlsUris(playlist, uri => rewriteUri(uri, options));
3438
+ }
3439
+ function rewriteUri(uri, {
3440
+ playlistPath,
3441
+ patchId,
3442
+ remote
3443
+ }) {
3444
+ if (Internal.remote.splitRemoteRef(uri).status === "success") {
3445
+ return Internal.mediaUrl({
3446
+ path: uri,
3447
+ patch_id: patchId
3448
+ });
3449
+ }
3450
+ if (/^[a-z][a-z0-9+.-]*:/i.test(uri) || uri.startsWith("/")) {
3451
+ // Another scheme (https:, data:, …), protocol-relative or root-relative.
3452
+ return uri;
3453
+ }
3454
+ // The query and fragment of a relative URI address the published file; the
3455
+ // draft endpoint has its own query, and fragments do not reach a server.
3456
+ const relative = uri.split(/[?#]/)[0];
3457
+ if (relative === "") {
3458
+ return uri;
3459
+ }
3460
+ // `join` from an absolute directory stays absolute: `..` stops at the root.
3461
+ const resolved = path__default.posix.join(path__default.posix.dirname(playlistPath), relative);
3462
+ return `/api/val/files${resolved}?patch_id=${patchId}${remote ? "&remote=true" : ""}`;
3463
+ }
3464
+
3465
+ /** Whether a served file is an HLS playlist, by its extension. */
3466
+ function isHlsPlaylistPath(filePath) {
3467
+ return filePath.split("?")[0].toLowerCase().endsWith(".m3u8");
3468
+ }
3469
+
3184
3470
  /* eslint-disable @typescript-eslint/no-unused-vars */
3185
3471
  const jsonOps = new JSONOps();
3186
3472
  /**
@@ -4004,9 +4290,20 @@ class ValOps {
4004
4290
  // when constructing the url we use the patch id (and the file path)
4005
4291
  // to fetch the right file
4006
4292
  // NOTE: overwrite and use last patch_id if multiple patches modify the same file
4007
- fileFixOps[op.path.join("/")] = [{
4293
+ //
4294
+ // Keyed by where the patch_id LANDS — the field's path plus
4295
+ // `nestedFilePath` — not by the field's path alone. A video's
4296
+ // poster and caption files are file ops on the video's own path
4297
+ // with `nestedFilePath` ["poster"] / ["captions", "0"]; keyed by
4298
+ // `op.path` they overwrote the video's entry (and each other),
4299
+ // so only one of the files got a patch_id and the rest were
4300
+ // looked for at a published URL that holds nothing. JSON rather
4301
+ // than a "/" join because a segment can contain "/" (a gallery
4302
+ // key is a file path).
4303
+ const patchIdPath = op.path.concat(...(op.nestedFilePath || [])).concat("patch_id");
4304
+ fileFixOps[JSON.stringify(patchIdPath)] = [{
4008
4305
  op: "add",
4009
- path: op.path.concat(...(op.nestedFilePath || [])).concat("patch_id"),
4306
+ path: patchIdPath,
4010
4307
  value: patchId
4011
4308
  }];
4012
4309
  }
@@ -4204,7 +4501,7 @@ class ValOps {
4204
4501
  };
4205
4502
  if (validationErrors) {
4206
4503
  for (const validationError of validationErrors) {
4207
- var _validationError$fixe, _validationError$fixe2, _validationError$fixe3, _validationError$fixe4, _validationError$fixe5, _validationError$fixe6;
4504
+ var _validationError$fixe, _validationError$fixe2, _validationError$fixe3, _validationError$fixe4, _validationError$fixe5, _validationError$fixe6, _validationError$fixe7, _validationError$fixe8;
4208
4505
  if (isOnlyFileCheckValidationError(validationError)) {
4209
4506
  if (files[sourcePath]) {
4210
4507
  addError({
@@ -4224,7 +4521,7 @@ class ValOps {
4224
4521
  addError(resolved.error);
4225
4522
  }
4226
4523
  // resolved.status === "resolved" → drop silently
4227
- } else if ((_validationError$fixe3 = validationError.fixes) !== null && _validationError$fixe3 !== void 0 && _validationError$fixe3.includes("images:check-unique-folder") || (_validationError$fixe4 = validationError.fixes) !== null && _validationError$fixe4 !== void 0 && _validationError$fixe4.includes("files:check-unique-folder")) {
4524
+ } else if ((_validationError$fixe3 = validationError.fixes) !== null && _validationError$fixe3 !== void 0 && _validationError$fixe3.includes("images:check-unique-folder") || (_validationError$fixe4 = validationError.fixes) !== null && _validationError$fixe4 !== void 0 && _validationError$fixe4.includes("files:check-unique-folder") || (_validationError$fixe5 = validationError.fixes) !== null && _validationError$fixe5 !== void 0 && _validationError$fixe5.includes("videos:check-unique-folder")) {
4228
4525
  const TYPE_ERROR_MESSAGE = `This is most likely a Val version mismatch or Val bug.`;
4229
4526
  if (!validationError.value || typeof validationError.value !== "object") {
4230
4527
  addError({
@@ -4249,7 +4546,7 @@ class ValOps {
4249
4546
  // If conflictingModules is empty, directory is unique — silently drop the error.
4250
4547
  }
4251
4548
  }
4252
- } else if ((_validationError$fixe5 = validationError.fixes) !== null && _validationError$fixe5 !== void 0 && _validationError$fixe5.includes("images:check-all-files") || (_validationError$fixe6 = validationError.fixes) !== null && _validationError$fixe6 !== void 0 && _validationError$fixe6.includes("files:check-all-files")) ; else {
4549
+ } else if ((_validationError$fixe6 = validationError.fixes) !== null && _validationError$fixe6 !== void 0 && _validationError$fixe6.includes("images:check-all-files") || (_validationError$fixe7 = validationError.fixes) !== null && _validationError$fixe7 !== void 0 && _validationError$fixe7.includes("files:check-all-files") || (_validationError$fixe8 = validationError.fixes) !== null && _validationError$fixe8 !== void 0 && _validationError$fixe8.includes("videos:check-all-files")) ; else {
4253
4550
  addError(validationError);
4254
4551
  }
4255
4552
  }
@@ -5354,6 +5651,19 @@ class ValOps {
5354
5651
  async saveBinaryFileFromPatch(filePath, parentRef, patchId, bytes, mimeType, type, metadata) {
5355
5652
  return this.saveBase64EncodedBinaryFileFromPatch(filePath, parentRef, patchId, `data:${mimeType};base64,${bytes.toString("base64")}`, type, metadata);
5356
5653
  }
5654
+ /**
5655
+ * A file's bytes as something a `Range` request can be answered from
5656
+ * without reading the rest: a video is seeked in by many small ranges, and
5657
+ * each used to load the whole file.
5658
+ *
5659
+ * This default holds the whole file, which is all a mode that only gets
5660
+ * whole files can do (`ValOpsHttp`: the content service answers with the
5661
+ * file in a JSON body). `ValOpsFS` reads only the asked-for range off disk.
5662
+ */
5663
+ async openBinaryFile(filePath, fromPatch) {
5664
+ const buffer = fromPatch ? await this.getBase64EncodedBinaryFileFromPatch(filePath, fromPatch.patchId, fromPatch.remote) : await this.getBinaryFile(filePath);
5665
+ return buffer === null ? null : bufferReader(buffer);
5666
+ }
5357
5667
 
5358
5668
  // #region history
5359
5669
  //
@@ -5404,8 +5714,8 @@ class ValOps {
5404
5714
  // #endregion history
5405
5715
  }
5406
5716
  function isOnlyFileCheckValidationError(validationError) {
5407
- var _validationError$fixe7;
5408
- if ((_validationError$fixe7 = validationError.fixes) !== null && _validationError$fixe7 !== void 0 && _validationError$fixe7.every(f => f === "file:check-metadata" || f === "image:check-metadata")) {
5717
+ var _validationError$fixe9;
5718
+ if ((_validationError$fixe9 = validationError.fixes) !== null && _validationError$fixe9 !== void 0 && _validationError$fixe9.every(f => f === "file:check-metadata" || f === "image:check-metadata")) {
5409
5719
  return true;
5410
5720
  }
5411
5721
  return false;
@@ -5595,6 +5905,15 @@ function bufferFromDataUrl(dataUrl) {
5595
5905
  }
5596
5906
  }
5597
5907
 
5908
+ /** A file of known size whose bytes are read a range at a time. */
5909
+
5910
+ function bufferReader(buffer) {
5911
+ return {
5912
+ size: buffer.length,
5913
+ read: async (start, end) => buffer.subarray(start, end + 1)
5914
+ };
5915
+ }
5916
+
5598
5917
  /**
5599
5918
  * The `*.val.json` files backing a `.jsonValues()` module's entries, as paths
5600
5919
  * relative to the project root.
@@ -8029,6 +8348,26 @@ class ValOpsFS extends ValOps {
8029
8348
  errors
8030
8349
  };
8031
8350
  }
8351
+ async openBinaryFile(filePath, fromPatch) {
8352
+ let absPath;
8353
+ if (fromPatch) {
8354
+ const patchesDir = this.getPatchesDir();
8355
+ absPath = this.wherePatchFileIs(patchBinaryFile(patchesDir, fromPatch.patchId, filePath), stagedPatchBinaryFile(patchesDir, fromPatch.patchId, filePath));
8356
+ } else {
8357
+ absPath = path__default.join(this.rootDir, ...filePath.split("/"));
8358
+ if (!this.host.fileExists(absPath)) {
8359
+ absPath = null;
8360
+ }
8361
+ }
8362
+ if (absPath === null) {
8363
+ return null;
8364
+ }
8365
+ const path = absPath;
8366
+ return {
8367
+ size: this.host.binaryFileSize(path),
8368
+ read: async (start, end) => this.host.readBinaryFileRange(path, start, end)
8369
+ };
8370
+ }
8032
8371
  async getBinaryFile(filePath) {
8033
8372
  const absPath = path__default.join(this.rootDir, ...filePath.split("/"));
8034
8373
  if (!this.host.fileExists(absPath)) {
@@ -8151,6 +8490,30 @@ class FSOpsHost {
8151
8490
  readBinaryFile(path) {
8152
8491
  return fs.readFileSync(path);
8153
8492
  }
8493
+ binaryFileSize(path) {
8494
+ return fs.statSync(path).size;
8495
+ }
8496
+
8497
+ /** Bytes `start` to `end` inclusive, and only those, read off disk. */
8498
+ async readBinaryFileRange(path, start, end) {
8499
+ const handle = await fs.promises.open(path, "r");
8500
+ try {
8501
+ const buffer = Buffer$1.alloc(Math.max(0, end - start + 1));
8502
+ let filled = 0;
8503
+ while (filled < buffer.length) {
8504
+ const {
8505
+ bytesRead
8506
+ } = await handle.read(buffer, filled, buffer.length - filled, start + filled);
8507
+ if (bytesRead === 0) {
8508
+ break;
8509
+ }
8510
+ filled += bytesRead;
8511
+ }
8512
+ return buffer.subarray(0, filled);
8513
+ } finally {
8514
+ await handle.close();
8515
+ }
8516
+ }
8154
8517
  readUtf8File(path) {
8155
8518
  return fs.readFileSync(path, "utf-8");
8156
8519
  }
@@ -8452,6 +8815,8 @@ const GetApplicablePatches = z.object({
8452
8815
  * Optional for the same reason.
8453
8816
  */
8454
8817
  headVersion: z.number().optional(),
8818
+ /** Of `patches`, the ones a running publish holds. See `OrderedPatches.publishingPatches`. */
8819
+ publishingPatches: z.array(PatchId$1).optional(),
8455
8820
  commits: z.array(z.object({
8456
8821
  commitSha: z.string(),
8457
8822
  /*
@@ -9336,6 +9701,13 @@ class ValOpsHttp extends ValOps {
9336
9701
  deployments: allPatchData.deployments || [],
9337
9702
  patches,
9338
9703
  appliedPatches,
9704
+ /*
9705
+ * Absent, not empty, from a content service that does not say: an empty
9706
+ * list would claim no publish is running when it cannot know.
9707
+ */
9708
+ ...(allPatchData.publishingPatches !== undefined ? {
9709
+ publishingPatches: allPatchData.publishingPatches
9710
+ } : {}),
9339
9711
  /*
9340
9712
  * The CHAIN head, not the publish head below. Spread: absent is a content
9341
9713
  * service that does not report it, which is not the same as `null`.
@@ -9703,6 +10075,9 @@ class ValOpsHttp extends ValOps {
9703
10075
  } : {}),
9704
10076
  ...(data.headVersion !== undefined ? {
9705
10077
  headVersion: data.headVersion
10078
+ } : {}),
10079
+ ...(data.publishingPatches !== undefined ? {
10080
+ publishingPatches: data.publishingPatches
9706
10081
  } : {})
9707
10082
  };
9708
10083
  }
@@ -12280,6 +12655,15 @@ const DEFAULT_VAL_BUILD_URL = "https://admin.val.build";
12280
12655
  */
12281
12656
  const VAL_APP_ENV = "app";
12282
12657
 
12658
+ /**
12659
+ * What the Val app says when a project does not store its media remotely.
12660
+ *
12661
+ * Exported so that `val publish` -- which publishes to the app, and so is
12662
+ * the last place to catch this before a build goes out -- refuses with the
12663
+ * same sentence the deployed server would.
12664
+ */
12665
+ const APP_MODE_REQUIRES_REMOTE_FILES = "This project runs in the Val app, which stores every image, file and " + "video on Val's remote content host -- there is no repository for an " + "upload to go into. Add `files: { remote: true }` to `initVal` in " + "val.config.ts, so that `s.image()`, `s.file()`, `s.video()` and the " + "sets are remote everywhere this project is read. Images already in the " + "project then fail validation until they are uploaded: `npx val validate " + "--fix` does that.";
12666
+
12283
12667
  /** Which mode the environment SAYS this is, and which variable said so. */
12284
12668
 
12285
12669
  /**
@@ -12426,7 +12810,7 @@ async function initHandlerOptions(route, opts, config) {
12426
12810
  valContentUrl
12427
12811
  });
12428
12812
  if (isProxyMode) {
12429
- var _opts$versions, _opts$versions2;
12813
+ var _config$files, _opts$versions, _opts$versions2;
12430
12814
  /*
12431
12815
  * Why this app is in http mode, in the message that says what is missing.
12432
12816
  *
@@ -12479,6 +12863,27 @@ async function initHandlerOptions(route, opts, config) {
12479
12863
  if (!maybeValProject) {
12480
12864
  throw new Error("Proxy mode does not work unless the 'project' option in val.config is defined or the VAL_PROJECT env var is set." + because);
12481
12865
  }
12866
+ /*
12867
+ * The Val app has no repository for an uploaded file to go into, so every
12868
+ * image, file and video in it is remote -- and the project has to SAY so,
12869
+ * in `val.config.ts`, rather than this server deciding it.
12870
+ *
12871
+ * Deciding it here would be easy and wrong. The schemas are built when
12872
+ * `val.config.ts` and the modules are evaluated, before this function
12873
+ * sees anything, and the same file is evaluated by `val validate`, the VS
12874
+ * Code extension and `pnpm dev`. A switch only the app could see would
12875
+ * leave every one of those reading the project's media as local: every
12876
+ * remote image reported as a mistake, and `val validate --fix` downloading
12877
+ * it back into the repository.
12878
+ *
12879
+ * So this refuses rather than covers for it. Without the check, the
12880
+ * failure is quieter and later: a local upload that the app has nowhere
12881
+ * to put, found at a publish.
12882
+ */
12883
+ // `config?.`: `initVal()` with no argument hands back no config at all.
12884
+ if (isAppEnv && (config === null || config === void 0 || (_config$files = config.files) === null || _config$files === void 0 ? void 0 : _config$files.remote) !== true) {
12885
+ throw new Error(APP_MODE_REQUIRES_REMOTE_FILES);
12886
+ }
12482
12887
  const coreVersion = (_opts$versions = opts.versions) === null || _opts$versions === void 0 ? void 0 : _opts$versions.core;
12483
12888
  if (!coreVersion) {
12484
12889
  throw new Error("Could not determine version of @valbuild/core");
@@ -12811,6 +13216,12 @@ async function resolveRemoteFileAuth(options) {
12811
13216
 
12812
13217
  /** What a publish reports back, in either shape. */
12813
13218
 
13219
+ /**
13220
+ * Where a local file a publish commits is written. Fixed: it was configurable
13221
+ * (`files.directory` in val.config.ts), nobody configured it, and the schemas
13222
+ * have their own `dir` for any collection that wants somewhere else.
13223
+ */
13224
+ const FILES_DIRECTORY = "/public/val";
12814
13225
  const ValServer = (valModules, options, callbacks) => {
12815
13226
  var _options$git;
12816
13227
  const AIContentBlock = z.union([z.object({
@@ -14827,7 +15238,6 @@ const ValServer = (valModules, options, callbacks) => {
14827
15238
  },
14828
15239
  "/publish-job-prepare": {
14829
15240
  POST: async req => {
14830
- var _options$config$files2;
14831
15241
  const auth = getAuth(req.cookies);
14832
15242
  if (auth.error) {
14833
15243
  return {
@@ -14874,7 +15284,6 @@ const ValServer = (valModules, options, callbacks) => {
14874
15284
  * push either way.
14875
15285
  */
14876
15286
  if (serverOps.sourceMode() === "connected") {
14877
- var _options$config$files;
14878
15287
  const jobPatches = await serverOps.fetchPatches({
14879
15288
  patchIds,
14880
15289
  excludePatchOps: false
@@ -14927,7 +15336,7 @@ const ValServer = (valModules, options, callbacks) => {
14927
15336
  const deploymentFiles = commit === undefined ? await serverOps.embeddedValSourceShas() : null;
14928
15337
  const sent = await serverOps.prepareJob(jobId, {
14929
15338
  tab,
14930
- filesDirectory: ((_options$config$files = options.config.files) === null || _options$config$files === void 0 ? void 0 : _options$config$files.directory) || "/public/val",
15339
+ filesDirectory: FILES_DIRECTORY,
14931
15340
  ...split.archive,
14932
15341
  ...(commit !== undefined ? {
14933
15342
  gitCommit: commit
@@ -14956,7 +15365,7 @@ const ValServer = (valModules, options, callbacks) => {
14956
15365
  } = built;
14957
15366
  const sent = await serverOps.prepareJob(jobId, {
14958
15367
  tab,
14959
- filesDirectory: ((_options$config$files2 = options.config.files) === null || _options$config$files2 === void 0 ? void 0 : _options$config$files2.directory) || "/public/val",
15368
+ filesDirectory: FILES_DIRECTORY,
14960
15369
  ...split.archive
14961
15370
  });
14962
15371
  return jobPrepareAnswer(sent, {
@@ -15444,17 +15853,14 @@ const ValServer = (valModules, options, callbacks) => {
15444
15853
  */
15445
15854
  const managedBranch = serverOps.sourceMode() === "managed" ? serverOps.projectBranch() : null;
15446
15855
  const committedBinaries = serverOps.sourceMode() === "managed" ? await readCommittedBinaryFiles(serverOps, preparedCommit.patchedBinaryFilesDescriptors) : null;
15447
- const commitToGit = () => {
15448
- var _options$config$files3;
15449
- return serverOps.commit(preparedCommit, message, auth.id, ((_options$config$files3 = options.config.files) === null || _options$config$files3 === void 0 ? void 0 : _options$config$files3.directory) || "/public/val", undefined,
15450
- /*
15451
- * Forwarded verbatim, and only the client can decide it: the
15452
- * content API closes the group it is named without checking
15453
- * that the commit shipped all of it, and whether it did needs
15454
- * the patch sets, which live in the browser.
15455
- */
15456
- body.patchGroupId);
15457
- };
15856
+ const commitToGit = () => serverOps.commit(preparedCommit, message, auth.id, FILES_DIRECTORY, undefined,
15857
+ /*
15858
+ * Forwarded verbatim, and only the client can decide it: the
15859
+ * content API closes the group it is named without checking
15860
+ * that the commit shipped all of it, and whether it did needs
15861
+ * the patch sets, which live in the browser.
15862
+ */
15863
+ body.patchGroupId);
15458
15864
  /*
15459
15865
  * A host may publish somewhere other than the repository.
15460
15866
  *
@@ -16441,34 +16847,18 @@ const ValServer = (valModules, options, callbacks) => {
16441
16847
  // nothing fetches it backend-to-backend. Neither half of the argument
16442
16848
  // above transfers. See architecture/media.md, "Why /files has no auth,
16443
16849
  // and /history/files does".
16444
- let fileBuffer;
16445
- let mimeType;
16446
16850
  const remote = query.remote === "true";
16447
- if (query.patch_id) {
16448
- fileBuffer = await serverOps.getBase64EncodedBinaryFileFromPatch(filePath, query.patch_id, remote);
16449
- mimeType = Internal.filenameToMimeType(filePath);
16450
- } else {
16451
- if (serverOps instanceof ValOpsHttp && remote) {
16452
- console.error(`Remote file: ${filePath} requested without patch id. This is most likely a bug in Val.`);
16453
- }
16454
- fileBuffer = await serverOps.getBinaryFile(filePath);
16851
+ const patchId = query.patch_id;
16852
+ if (!patchId && serverOps instanceof ValOpsHttp && remote) {
16853
+ console.error(`Remote file: ${filePath} requested without patch id. This is most likely a bug in Val.`);
16455
16854
  }
16456
- if (fileBuffer) {
16457
- return {
16458
- status: 200,
16459
- headers: {
16460
- // TODO: we could use ETag and return 304 instead
16461
- "Content-Type": mimeType || "application/octet-stream",
16462
- // TODO: a file requested with a patch_id is immutable for that
16463
- // patch, so it could be served "public, max-age=20000, immutable"
16464
- // instead. There used to be a `cacheControl` variable here for
16465
- // that, but its only assignment was commented out, so every
16466
- // response has always taken the revalidate branch.
16467
- "Cache-Control": "public, max-age=0, must-revalidate"
16468
- },
16469
- body: bufferToReadableStream(fileBuffer)
16470
- };
16471
- } else {
16855
+ // Opened, not read: a video is seeked in by many small ranges, and
16856
+ // only the asked-for bytes are read where the mode can (fs).
16857
+ const opened = await serverOps.openBinaryFile(filePath, patchId ? {
16858
+ patchId: patchId,
16859
+ remote
16860
+ } : null);
16861
+ if (!opened) {
16472
16862
  return {
16473
16863
  status: 404,
16474
16864
  json: {
@@ -16476,6 +16866,62 @@ const ValServer = (valModules, options, callbacks) => {
16476
16866
  }
16477
16867
  };
16478
16868
  }
16869
+ // A DRAFT playlist names files that are drafts too, at URLs that only
16870
+ // resolve once published. See `rewriteDraftPlaylist`. Playlists are
16871
+ // small, so one is read whole to be rewritten.
16872
+ const file = patchId && isHlsPlaylistPath(filePath) ? bufferReader(Buffer.from(rewriteDraftPlaylist((await opened.read(0, opened.size - 1)).toString("utf-8"), {
16873
+ playlistPath: filePath,
16874
+ patchId,
16875
+ remote
16876
+ }), "utf-8")) : opened;
16877
+ const headers = {
16878
+ // TODO: we could use ETag and return 304 instead
16879
+ // From the extension, published or draft: a `<video>` and an HLS
16880
+ // player both decide what they are holding by it, and it used to be
16881
+ // set for drafts only.
16882
+ "Content-Type": Internal.filenameToMimeType(filePath) || "application/octet-stream",
16883
+ // TODO: a file requested with a patch_id is immutable for that
16884
+ // patch, so it could be served "public, max-age=20000, immutable"
16885
+ // instead. There used to be a `cacheControl` variable here for
16886
+ // that, but its only assignment was commented out, so every
16887
+ // response has always taken the revalidate branch.
16888
+ "Cache-Control": "public, max-age=0, must-revalidate",
16889
+ "Accept-Ranges": "bytes"
16890
+ };
16891
+ const range = parseRangeHeader(req.headers.range, file.size);
16892
+ if (range.kind === "unsatisfiable") {
16893
+ return {
16894
+ status: 416,
16895
+ headers: {
16896
+ ...headers,
16897
+ "Content-Range": `bytes */${file.size}`
16898
+ },
16899
+ json: {
16900
+ message: `Range not satisfiable: ${req.headers.range}`
16901
+ }
16902
+ };
16903
+ }
16904
+ if (range.kind === "range") {
16905
+ const slice = await file.read(range.start, range.end);
16906
+ return {
16907
+ status: 206,
16908
+ headers: {
16909
+ ...headers,
16910
+ "Content-Range": `bytes ${range.start}-${range.end}/${file.size}`,
16911
+ "Content-Length": String(slice.length)
16912
+ },
16913
+ body: bufferToReadableStream(slice)
16914
+ };
16915
+ }
16916
+ const body = file.size === 0 ? Buffer.alloc(0) : await file.read(0, file.size - 1);
16917
+ return {
16918
+ status: 200,
16919
+ headers: {
16920
+ ...headers,
16921
+ "Content-Length": String(body.length)
16922
+ },
16923
+ body: bufferToReadableStream(body)
16924
+ };
16479
16925
  }
16480
16926
  }
16481
16927
  };
@@ -17823,301 +18269,2692 @@ class ValFSHost {
17823
18269
  }
17824
18270
  }
17825
18271
 
17826
- async function extractImageMetadata(filename, input) {
17827
- const imageSize = sizeOf(new Uint8Array(input));
17828
- let mimeType = null;
17829
- if (imageSize.type) {
17830
- const possibleMimeType = `image/${imageSize.type}`;
17831
- if (Internal.MIME_TYPES_TO_EXT[possibleMimeType]) {
17832
- mimeType = possibleMimeType;
17833
- }
17834
- const filenameBasedLookup = Internal.filenameToMimeType(filename);
17835
- if (filenameBasedLookup) {
17836
- mimeType = filenameBasedLookup;
17837
- }
17838
- }
17839
- if (!mimeType) {
17840
- mimeType = "application/octet-stream";
17841
- }
17842
- let {
17843
- width,
17844
- height
17845
- } = imageSize;
17846
- if (!width || !height) {
17847
- width = 0;
17848
- height = 0;
17849
- }
18272
+ /**
18273
+ * The size and length of an ISO base media file (`.mp4`, `.m4v`, `.mov`),
18274
+ * read from its headers. Nothing is decoded.
18275
+ *
18276
+ * Hand-written rather than a media library, deliberately: `@valbuild/server`
18277
+ * is loaded by every app that runs Val, and the four numbers wanted here are
18278
+ * three small boxes away from the start of the `moov` box:
18279
+ *
18280
+ * moov > mvhd timescale and duration (version 0 and 1)
18281
+ * moov > mvex > mehd duration of a FRAGMENTED file, whose mvhd says 0
18282
+ * moov > trak > tkhd width and height (16.16 fixed point) and the
18283
+ * display matrix, for a rotated phone video
18284
+ * moov > trak > mdia > hdlr `vide`: which trak is the picture
18285
+ *
18286
+ * Only the box headers are read on the way to `moov`, and then `moov` itself,
18287
+ * so a multi-GB file costs a few small reads: `mdat` is seeked past, never
18288
+ * loaded. That is what {@link ByteSource} is for.
18289
+ */
18290
+
18291
+ /** Random access to a file's bytes, so a large `mdat` can be skipped. */
18292
+
18293
+ function bufferByteSource(buffer) {
17850
18294
  return {
17851
- width,
17852
- height,
17853
- mimeType
18295
+ size: buffer.length,
18296
+ read: (offset, length) => buffer.subarray(offset, offset + length)
17854
18297
  };
17855
18298
  }
17856
- async function extractFileMetadata(filename, _input // TODO: use buffer to determine mimetype
17857
- ) {
17858
- let mimeType = Internal.filenameToMimeType(filename);
17859
- if (!mimeType) {
17860
- mimeType = "application/octet-stream";
18299
+
18300
+ /**
18301
+ * Run `read` against a file on disk, reading only what it asks for. The file
18302
+ * is closed afterwards whatever happens.
18303
+ */
18304
+ function withFileByteSource(absolutePath, read) {
18305
+ const fd = fs.openSync(absolutePath, "r");
18306
+ try {
18307
+ const size = fs.fstatSync(fd).size;
18308
+ return read({
18309
+ size,
18310
+ read: (offset, length) => {
18311
+ const wanted = Math.max(0, Math.min(length, size - offset));
18312
+ const buffer = Buffer.alloc(wanted);
18313
+ let filled = 0;
18314
+ while (filled < wanted) {
18315
+ const n = fs.readSync(fd, buffer, filled, wanted - filled, offset + filled);
18316
+ if (n === 0) {
18317
+ break;
18318
+ }
18319
+ filled += n;
18320
+ }
18321
+ return buffer.subarray(0, filled);
18322
+ }
18323
+ });
18324
+ } finally {
18325
+ fs.closeSync(fd);
17861
18326
  }
17862
- return {
17863
- mimeType
17864
- };
17865
18327
  }
17866
-
17867
18328
  /**
17868
- * A gallery entry's key, read as what it actually is.
17869
- *
17870
- * A gallery is a record keyed by its entries' file paths. A REMOTE gallery keys
17871
- * an uploaded entry by the remote URL instead — which encodes that same path —
17872
- * so every entry has a local path, and the interesting question is whether the
17873
- * bytes are expected to be at it.
17874
- *
17875
- * **They are not, for a remote entry added the ordinary way.** `saveOrUploadFiles`
17876
- * uploads the remote descriptors to the content host and copies only the local
17877
- * ones into the working tree, so an image added through the Studio (or over MCP)
17878
- * and published has no file in the repo, by design — putting one there is what
17879
- * remote storage exists to avoid. A remote entry CAN have one, because
17880
- * `val validate --fix` promotes a local file to a remote ref and leaves the file
17881
- * where it was; so "remote" means "do not require it", never "there is not one".
17882
- *
17883
- * One copy, in its own file, because this used to be two: a `remoteKeyToLocalPath`
17884
- * in `fixHandlers` and a `galleryKeyToLocalPath` in `createFixPatch`, each
17885
- * normalising the key correctly and each then treating the result as a file that
17886
- * must exist. That agreement is what made a published remote image report as
17887
- * missing from both sides at once.
18329
+ * A `moov` larger than this is not a header worth reading into memory. A
18330
+ * two-hour film's is a few MB; this is far past any real one.
17888
18331
  */
18332
+ const MAX_MOOV_SIZE = 64 * 1024 * 1024;
17889
18333
 
17890
18334
  /**
17891
- * A key that names somewhere else, whether or not it is a ref we can read.
17892
- *
17893
- * Case-insensitive, because a scheme is (RFC 3986) — and because
17894
- * `splitRemoteRef`'s pattern is not, so `HTTPS://…` is precisely one of the
17895
- * spellings that arrives here unparsed and must not be mistaken for a path.
18335
+ * Whatever of {@link IsoBmffMetadata} the file declares. A field that cannot be
18336
+ * read is absent; nothing here throws on a file that is not ISO BMFF.
17896
18337
  */
17897
- function isRemoteUrl(key) {
17898
- return /^https?:\/\//i.test(key);
17899
- }
17900
- function galleryEntryOf(key) {
17901
- const remoteRefRes = Internal.remote.splitRemoteRef(key);
18338
+ function readIsoBmffMetadata(source) {
18339
+ const moov = findTopLevelBox(source, "moov");
18340
+ if (!moov) {
18341
+ return {};
18342
+ }
18343
+ const metadata = {};
18344
+ const mvhd = childBox(moov, "mvhd");
18345
+ const timescaleAndDuration = mvhd ? readMvhd(mvhd) : undefined;
18346
+ if (timescaleAndDuration) {
18347
+ const {
18348
+ timescale,
18349
+ duration
18350
+ } = timescaleAndDuration;
18351
+ if (duration > 0) {
18352
+ metadata.duration = duration / timescale;
18353
+ } else {
18354
+ // A fragmented file (CMAF) says 0 in mvhd and puts the length in mehd,
18355
+ // in the same timescale.
18356
+ const mehd = childBox(childBox(moov, "mvex"), "mehd");
18357
+ const fragmentDuration = mehd ? readMehd(mehd) : undefined;
18358
+ if (fragmentDuration !== undefined && fragmentDuration > 0) {
18359
+ metadata.duration = fragmentDuration / timescale;
18360
+ }
18361
+ }
18362
+ }
18363
+ for (const trak of childBoxes(moov, "trak")) {
18364
+ const hdlr = childBox(childBox(trak, "mdia"), "hdlr");
18365
+ if (!hdlr || hdlr.length < 12 || hdlr.toString("latin1", 8, 12) !== "vide") {
18366
+ continue;
18367
+ }
18368
+ const tkhd = childBox(trak, "tkhd");
18369
+ const size = tkhd ? readTkhd(tkhd) : undefined;
18370
+ if (size && size.width > 0 && size.height > 0) {
18371
+ metadata.width = size.width;
18372
+ metadata.height = size.height;
18373
+ break;
18374
+ }
18375
+ }
18376
+ return metadata;
18377
+ }
18378
+
18379
+ /** The payload (after the header) of the first top-level box of a type. */
18380
+ function findTopLevelBox(source, type) {
18381
+ let offset = 0;
18382
+ while (offset + 8 <= source.size) {
18383
+ const header = source.read(offset, 16);
18384
+ if (header.length < 8) {
18385
+ return undefined;
18386
+ }
18387
+ let size = header.readUInt32BE(0);
18388
+ const boxType = header.toString("latin1", 4, 8);
18389
+ let headerSize = 8;
18390
+ if (size === 1) {
18391
+ if (header.length < 16) {
18392
+ return undefined;
18393
+ }
18394
+ size = Number(header.readBigUInt64BE(8));
18395
+ headerSize = 16;
18396
+ } else if (size === 0) {
18397
+ size = source.size - offset;
18398
+ }
18399
+ if (size < headerSize) {
18400
+ return undefined;
18401
+ }
18402
+ if (boxType === type) {
18403
+ if (size - headerSize > MAX_MOOV_SIZE) {
18404
+ return undefined;
18405
+ }
18406
+ const payload = source.read(offset + headerSize, size - headerSize);
18407
+ return payload.length === size - headerSize ? payload : undefined;
18408
+ }
18409
+ offset += size;
18410
+ }
18411
+ return undefined;
18412
+ }
18413
+
18414
+ /** Each child box of a container payload, as `[type, payload]`. */
18415
+ function* boxesIn(payload) {
18416
+ let offset = 0;
18417
+ while (offset + 8 <= payload.length) {
18418
+ let size = payload.readUInt32BE(offset);
18419
+ const type = payload.toString("latin1", offset + 4, offset + 8);
18420
+ let headerSize = 8;
18421
+ if (size === 1) {
18422
+ if (offset + 16 > payload.length) {
18423
+ return;
18424
+ }
18425
+ size = Number(payload.readBigUInt64BE(offset + 8));
18426
+ headerSize = 16;
18427
+ } else if (size === 0) {
18428
+ size = payload.length - offset;
18429
+ }
18430
+ if (size < headerSize || offset + size > payload.length) {
18431
+ return;
18432
+ }
18433
+ yield [type, payload.subarray(offset + headerSize, offset + size)];
18434
+ offset += size;
18435
+ }
18436
+ }
18437
+ function childBoxes(payload, type) {
18438
+ if (!payload) {
18439
+ return [];
18440
+ }
18441
+ const found = [];
18442
+ for (const [boxType, child] of boxesIn(payload)) {
18443
+ if (boxType === type) {
18444
+ found.push(child);
18445
+ }
18446
+ }
18447
+ return found;
18448
+ }
18449
+ function childBox(payload, type) {
18450
+ return childBoxes(payload, type)[0];
18451
+ }
18452
+
18453
+ /** "Unknown" in a version 1 box. Not a literal: `0x…n` needs an ES2020 target. */
18454
+ const ALL_ONES_64 = BigInt("0xffffffffffffffff");
18455
+ function readMvhd(mvhd) {
18456
+ const version = mvhd[0];
18457
+ if (version === 1) {
18458
+ if (mvhd.length < 32) return undefined;
18459
+ const timescale = mvhd.readUInt32BE(20);
18460
+ const duration = mvhd.readBigUInt64BE(24);
18461
+ if (timescale === 0 || duration === ALL_ONES_64) {
18462
+ return undefined;
18463
+ }
18464
+ return {
18465
+ timescale,
18466
+ duration: Number(duration)
18467
+ };
18468
+ }
18469
+ if (mvhd.length < 20) return undefined;
18470
+ const timescale = mvhd.readUInt32BE(12);
18471
+ const duration = mvhd.readUInt32BE(16);
18472
+ // All ones means "unknown" in a version 0 box.
18473
+ if (timescale === 0 || duration === 0xffffffff) {
18474
+ return undefined;
18475
+ }
18476
+ return {
18477
+ timescale,
18478
+ duration
18479
+ };
18480
+ }
18481
+ function readMehd(mehd) {
18482
+ if (mehd[0] === 1) {
18483
+ return mehd.length >= 12 ? Number(mehd.readBigUInt64BE(4)) : undefined;
18484
+ }
18485
+ return mehd.length >= 8 ? mehd.readUInt32BE(4) : undefined;
18486
+ }
18487
+
18488
+ /**
18489
+ * The size a track is SHOWN at: tkhd's width and height, swapped when the
18490
+ * display matrix turns the picture a quarter turn — a phone records upright
18491
+ * video sideways and says so here, and a page lays it out as it is shown.
18492
+ */
18493
+ function readTkhd(tkhd) {
18494
+ // Past the version-specific times and ids, then 16 bytes of reserved,
18495
+ // layer, alternate group, volume and reserved, then the 36-byte matrix.
18496
+ const matrixAt = tkhd[0] === 1 ? 4 + 32 + 16 : 4 + 20 + 16;
18497
+ const widthAt = matrixAt + 36;
18498
+ if (tkhd.length < widthAt + 8) {
18499
+ return undefined;
18500
+ }
18501
+ const a = tkhd.readInt32BE(matrixAt);
18502
+ const b = tkhd.readInt32BE(matrixAt + 4);
18503
+ const c = tkhd.readInt32BE(matrixAt + 12);
18504
+ const d = tkhd.readInt32BE(matrixAt + 16);
18505
+ const width = Math.round(tkhd.readUInt32BE(widthAt) / 0x10000);
18506
+ const height = Math.round(tkhd.readUInt32BE(widthAt + 4) / 0x10000);
18507
+ const quarterTurn = a === 0 && d === 0 && b !== 0 && c !== 0;
18508
+ return quarterTurn ? {
18509
+ width: height,
18510
+ height: width
18511
+ } : {
18512
+ width,
18513
+ height
18514
+ };
18515
+ }
18516
+
18517
+ /**
18518
+ * The size and length of a Matroska file (`.webm`, and `.mkv`, which is the
18519
+ * same container), read from its headers. Nothing is decoded.
18520
+ *
18521
+ * Hand-written for the same reason `isoBmff.ts` is: `@valbuild/server` is
18522
+ * loaded by every app that runs Val, and what is wanted here is a handful of
18523
+ * integers two levels into the file:
18524
+ *
18525
+ * EBML the header; a file without one is not Matroska
18526
+ * Segment > Info TimecodeScale and Duration
18527
+ * Segment > Tracks > TrackEntry TrackType 1 (video) >
18528
+ * Video PixelWidth / PixelHeight, and DisplayWidth /
18529
+ * DisplayHeight when they are in pixels
18530
+ *
18531
+ * Matroska is EBML: every element is a variable-length ID, a variable-length
18532
+ * size and a payload. Only element HEADERS are read on the way through the
18533
+ * Segment, and then the payloads of Info and Tracks, which are a few hundred
18534
+ * bytes. The Clusters — the frames, which are the file — are never read: the
18535
+ * walk stops at the first one.
18536
+ *
18537
+ * That is allowed because the spec (RFC 9559, section 6.3) requires the first
18538
+ * Info and Tracks to come before the first Cluster, or to be named by a
18539
+ * SeekHead that does. A file written by a browser's MediaRecorder, or by
18540
+ * anything else that streams, does not know its own length when it starts:
18541
+ * its Segment and Clusters have the "unknown" size, and its Info has no
18542
+ * Duration. The Segment is then read as running to the end of the file, and
18543
+ * the duration is left out rather than counted from the Clusters — a caller
18544
+ * reports it, as it does for a fragmented mp4.
18545
+ */
18546
+
18547
+ const EBML_HEADER = 0x1a45dfa3;
18548
+ const SEGMENT = 0x18538067;
18549
+ const SEEK_HEAD = 0x114d9b74;
18550
+ const SEEK = 0x4dbb;
18551
+ const SEEK_ID = 0x53ab;
18552
+ const SEEK_POSITION = 0x53ac;
18553
+ const INFO = 0x1549a966;
18554
+ const TIMECODE_SCALE = 0x2ad7b1;
18555
+ const DURATION = 0x4489;
18556
+ const TRACKS = 0x1654ae6b;
18557
+ const TRACK_ENTRY = 0xae;
18558
+ const TRACK_TYPE = 0x83;
18559
+ const VIDEO = 0xe0;
18560
+ const PIXEL_WIDTH = 0xb0;
18561
+ const PIXEL_HEIGHT = 0xba;
18562
+ const DISPLAY_WIDTH = 0x54b0;
18563
+ const DISPLAY_HEIGHT = 0x54ba;
18564
+ const DISPLAY_UNIT = 0x54b2;
18565
+ const CLUSTER = 0x1f43b675;
18566
+ const TRACK_TYPE_VIDEO = 1;
18567
+ const DISPLAY_UNIT_PIXELS = 0;
18568
+ /** Nanoseconds per tick, when Info does not say. */
18569
+ const DEFAULT_TIMECODE_SCALE = 1_000_000;
18570
+
18571
+ /**
18572
+ * Info, Tracks or a SeekHead larger than this is not a header worth reading
18573
+ * into memory. Tracks is the big one, for its codec private data, and that is
18574
+ * kilobytes.
18575
+ */
18576
+ const MAX_HEADER_ELEMENT_SIZE = 16 * 1024 * 1024;
18577
+
18578
+ /**
18579
+ * Whatever of {@link EbmlMetadata} the file declares. A field that cannot be
18580
+ * read is absent; nothing here throws on a file that is not Matroska.
18581
+ */
18582
+ function readEbmlMetadata(source) {
18583
+ const header = readElementHeader(source, 0);
18584
+ if (!header || header.id !== EBML_HEADER || header.size === undefined) {
18585
+ return {};
18586
+ }
18587
+ const segment = findSegment(source, header.dataStart + header.size);
18588
+ if (!segment) {
18589
+ return {};
18590
+ }
18591
+ const segmentStart = segment.dataStart;
18592
+ const segmentEnd = segment.size === undefined ? source.size : Math.min(source.size, segmentStart + segment.size);
18593
+ let info;
18594
+ let tracks;
18595
+ const seekPositions = new Map();
18596
+ let offset = segmentStart;
18597
+ while (offset < segmentEnd && !(info && tracks)) {
18598
+ const element = readElementHeader(source, offset);
18599
+ if (!element || element.id === CLUSTER) {
18600
+ break;
18601
+ }
18602
+ if (element.id === INFO && !info) {
18603
+ info = readPayload(source, element);
18604
+ } else if (element.id === TRACKS && !tracks) {
18605
+ tracks = readPayload(source, element);
18606
+ } else if (element.id === SEEK_HEAD) {
18607
+ const seekHead = readPayload(source, element);
18608
+ if (seekHead) {
18609
+ readSeekHead(seekHead, seekPositions);
18610
+ }
18611
+ }
18612
+ if (element.size === undefined) {
18613
+ // Only a Segment or a Cluster may have an unknown size, and an element
18614
+ // whose end is unknown cannot be stepped over.
18615
+ break;
18616
+ }
18617
+ offset = element.dataStart + element.size;
18618
+ }
18619
+ // Not before the first Cluster: the SeekHead says where.
18620
+ if (!info) {
18621
+ info = readSought(source, segmentStart, seekPositions, INFO);
18622
+ }
18623
+ if (!tracks) {
18624
+ tracks = readSought(source, segmentStart, seekPositions, TRACKS);
18625
+ }
18626
+ const metadata = {};
18627
+ const duration = info ? readDuration(info) : undefined;
18628
+ if (duration !== undefined) {
18629
+ metadata.duration = duration;
18630
+ }
18631
+ const size = tracks ? readVideoSize(tracks) : undefined;
18632
+ if (size) {
18633
+ metadata.width = size.width;
18634
+ metadata.height = size.height;
18635
+ }
18636
+ return metadata;
18637
+ }
18638
+ /** The first Segment among the top-level elements after the EBML header. */
18639
+ function findSegment(source, from) {
18640
+ let offset = from;
18641
+ while (offset < source.size) {
18642
+ const element = readElementHeader(source, offset);
18643
+ if (!element) {
18644
+ return undefined;
18645
+ }
18646
+ if (element.id === SEGMENT) {
18647
+ return element;
18648
+ }
18649
+ if (element.size === undefined) {
18650
+ return undefined;
18651
+ }
18652
+ offset = element.dataStart + element.size;
18653
+ }
18654
+ return undefined;
18655
+ }
18656
+ function readElementHeader(source, offset) {
18657
+ // At most 4 bytes of ID and 8 of size.
18658
+ const bytes = source.read(offset, 12);
18659
+ const id = readVint(bytes, 0, 4);
18660
+ if (!id) {
18661
+ return undefined;
18662
+ }
18663
+ const size = readVint(bytes, id.length, 8);
18664
+ if (!size) {
18665
+ return undefined;
18666
+ }
18667
+ return {
18668
+ id: id.raw,
18669
+ size: size.unknown ? undefined : size.value,
18670
+ dataStart: offset + id.length + size.length
18671
+ };
18672
+ }
18673
+ function readPayload(source, element) {
18674
+ const {
18675
+ size
18676
+ } = element;
18677
+ if (size === undefined || size > MAX_HEADER_ELEMENT_SIZE) {
18678
+ return undefined;
18679
+ }
18680
+ const payload = source.read(element.dataStart, size);
18681
+ return payload.length === size ? payload : undefined;
18682
+ }
18683
+ /**
18684
+ * An EBML variable-length integer: the number of leading zero bits of the
18685
+ * first byte, plus one, is its length in bytes. Built with arithmetic rather
18686
+ * than shifts, which are 32-bit and signed in JavaScript.
18687
+ */
18688
+ function readVint(bytes, offset, maxLength) {
18689
+ if (offset >= bytes.length) {
18690
+ return undefined;
18691
+ }
18692
+ const first = bytes[offset];
18693
+ if (first === 0) {
18694
+ return undefined;
18695
+ }
18696
+ const length = Math.clz32(first) - 23;
18697
+ if (length > maxLength || offset + length > bytes.length) {
18698
+ return undefined;
18699
+ }
18700
+ const valueMask = 0xff >> length;
18701
+ let raw = first;
18702
+ let value = first & valueMask;
18703
+ let unknown = value === valueMask;
18704
+ for (let i = 1; i < length; i++) {
18705
+ const byte = bytes[offset + i];
18706
+ raw = raw * 256 + byte;
18707
+ value = value * 256 + byte;
18708
+ unknown = unknown && byte === 0xff;
18709
+ }
18710
+ return {
18711
+ length,
18712
+ raw,
18713
+ value,
18714
+ unknown
18715
+ };
18716
+ }
18717
+
18718
+ /** Each child element of a master element's payload, as `[id, payload]`. */
18719
+ function* elementsIn(payload) {
18720
+ let offset = 0;
18721
+ while (offset < payload.length) {
18722
+ const id = readVint(payload, offset, 4);
18723
+ if (!id) {
18724
+ return;
18725
+ }
18726
+ const size = readVint(payload, offset + id.length, 8);
18727
+ if (!size || size.unknown) {
18728
+ return;
18729
+ }
18730
+ const dataStart = offset + id.length + size.length;
18731
+ const end = dataStart + size.value;
18732
+ if (end > payload.length) {
18733
+ return;
18734
+ }
18735
+ yield [id.raw, payload.subarray(dataStart, end)];
18736
+ offset = end;
18737
+ }
18738
+ }
18739
+ function child(payload, id) {
18740
+ for (const [childId, data] of elementsIn(payload)) {
18741
+ if (childId === id) {
18742
+ return data;
18743
+ }
18744
+ }
18745
+ return undefined;
18746
+ }
18747
+ function readUint(data) {
18748
+ if (!data || data.length > 8) {
18749
+ return undefined;
18750
+ }
18751
+ let value = 0;
18752
+ for (const byte of data) {
18753
+ value = value * 256 + byte;
18754
+ }
18755
+ return value;
18756
+ }
18757
+ function readFloat(data) {
18758
+ if ((data === null || data === void 0 ? void 0 : data.length) === 4) {
18759
+ return data.readFloatBE(0);
18760
+ }
18761
+ if ((data === null || data === void 0 ? void 0 : data.length) === 8) {
18762
+ return data.readDoubleBE(0);
18763
+ }
18764
+ return undefined;
18765
+ }
18766
+
18767
+ /** Where each top-level element a SeekHead names is, from the Segment's data. */
18768
+ function readSeekHead(seekHead, into) {
18769
+ for (const [id, seek] of elementsIn(seekHead)) {
18770
+ if (id !== SEEK) {
18771
+ continue;
18772
+ }
18773
+ const seekId = child(seek, SEEK_ID);
18774
+ const position = readUint(child(seek, SEEK_POSITION));
18775
+ if (seekId && seekId.length <= 4 && position !== undefined) {
18776
+ const target = readUint(seekId);
18777
+ if (target !== undefined && !into.has(target)) {
18778
+ into.set(target, position);
18779
+ }
18780
+ }
18781
+ }
18782
+ }
18783
+ function readSought(source, segmentStart, seekPositions, id) {
18784
+ const position = seekPositions.get(id);
18785
+ if (position === undefined) {
18786
+ return undefined;
18787
+ }
18788
+ const element = readElementHeader(source, segmentStart + position);
18789
+ return (element === null || element === void 0 ? void 0 : element.id) === id ? readPayload(source, element) : undefined;
18790
+ }
18791
+
18792
+ /**
18793
+ * Info's Duration is a float in ticks of TimecodeScale nanoseconds. Absent in
18794
+ * a file written as it was recorded, and then absent here too.
18795
+ */
18796
+ function readDuration(info) {
18797
+ const duration = readFloat(child(info, DURATION));
18798
+ if (duration === undefined || !Number.isFinite(duration) || duration <= 0) {
18799
+ return undefined;
18800
+ }
18801
+ const scale = readUint(child(info, TIMECODE_SCALE)) ?? DEFAULT_TIMECODE_SCALE;
18802
+ if (scale <= 0) {
18803
+ return undefined;
18804
+ }
18805
+ return duration * scale / 1e9;
18806
+ }
18807
+
18808
+ /**
18809
+ * The size the first video track is SHOWN at. DisplayWidth and DisplayHeight
18810
+ * are what a non-square-pixel (anamorphic) video is laid out at, so they win
18811
+ * over the stored PixelWidth and PixelHeight — but only when DisplayUnit says
18812
+ * they are pixels. The other units (centimetres, inches, a bare aspect ratio)
18813
+ * are not a size a page can use, so the pixel size is reported instead.
18814
+ */
18815
+ function readVideoSize(tracks) {
18816
+ for (const [id, entry] of elementsIn(tracks)) {
18817
+ if (id !== TRACK_ENTRY || readUint(child(entry, TRACK_TYPE)) !== TRACK_TYPE_VIDEO) {
18818
+ continue;
18819
+ }
18820
+ const video = child(entry, VIDEO);
18821
+ if (!video) {
18822
+ continue;
18823
+ }
18824
+ const pixelWidth = readUint(child(video, PIXEL_WIDTH));
18825
+ const pixelHeight = readUint(child(video, PIXEL_HEIGHT));
18826
+ const displayUnit = readUint(child(video, DISPLAY_UNIT)) ?? DISPLAY_UNIT_PIXELS;
18827
+ if (displayUnit === DISPLAY_UNIT_PIXELS) {
18828
+ const displayWidth = readUint(child(video, DISPLAY_WIDTH));
18829
+ const displayHeight = readUint(child(video, DISPLAY_HEIGHT));
18830
+ if (displayWidth && displayHeight) {
18831
+ return {
18832
+ width: displayWidth,
18833
+ height: displayHeight
18834
+ };
18835
+ }
18836
+ }
18837
+ if (pixelWidth && pixelHeight) {
18838
+ return {
18839
+ width: pixelWidth,
18840
+ height: pixelHeight
18841
+ };
18842
+ }
18843
+ }
18844
+ return undefined;
18845
+ }
18846
+
18847
+ async function extractImageMetadata(filename, input) {
18848
+ const imageSize = sizeOf(new Uint8Array(input));
18849
+ let mimeType = null;
18850
+ if (imageSize.type) {
18851
+ const possibleMimeType = `image/${imageSize.type}`;
18852
+ if (Internal.MIME_TYPES_TO_EXT[possibleMimeType]) {
18853
+ mimeType = possibleMimeType;
18854
+ }
18855
+ const filenameBasedLookup = Internal.filenameToMimeType(filename);
18856
+ if (filenameBasedLookup) {
18857
+ mimeType = filenameBasedLookup;
18858
+ }
18859
+ }
18860
+ if (!mimeType) {
18861
+ mimeType = "application/octet-stream";
18862
+ }
18863
+ let {
18864
+ width,
18865
+ height
18866
+ } = imageSize;
18867
+ if (!width || !height) {
18868
+ width = 0;
18869
+ height = 0;
18870
+ }
18871
+ return {
18872
+ width,
18873
+ height,
18874
+ mimeType
18875
+ };
18876
+ }
18877
+ async function extractFileMetadata(filename, _input // TODO: use buffer to determine mimetype
18878
+ ) {
18879
+ let mimeType = Internal.filenameToMimeType(filename);
18880
+ if (!mimeType) {
18881
+ mimeType = "application/octet-stream";
18882
+ }
18883
+ return {
18884
+ mimeType
18885
+ };
18886
+ }
18887
+
18888
+ /**
18889
+ * What `val validate --fix` writes into a video: `mimeType`, `width`, `height`
18890
+ * and `duration`, read from the file. A field that cannot be read is left out
18891
+ * rather than guessed, and the caller reports it — see
18892
+ * {@link unreadableVideoMetadataMessage}.
18893
+ *
18894
+ * `mimeType` always comes from the file EXTENSION: validation compares the two,
18895
+ * so any other answer is one validation rejects. The rest depends on the kind
18896
+ * of file:
18897
+ *
18898
+ * - **ISO BMFF** (`.mp4`, `.m4v`, `.mov`): read from the `moov` box by a small
18899
+ * parser of our own (`isoBmff.ts`). No media library: this package is loaded
18900
+ * by every app that runs Val.
18901
+ * - **WebM / Matroska** (`.webm`, `.mkv`): read from the Segment's Info and Tracks by another
18902
+ * (`ebml.ts`). A WebM recorded in a browser does not declare its length, and
18903
+ * then `duration` is left out — the frames are not counted to find it.
18904
+ * - **An HLS master playlist** (`.m3u8`): the dimensions are the largest
18905
+ * rendition's `RESOLUTION`, and the duration is the sum of the `#EXTINF`s of
18906
+ * the first media playlist it names, read from disk beside it — which is why
18907
+ * `filename` must be the playlist's path on disk.
18908
+ * - **Anything else**: the mime type and nothing more. The Studio reads those
18909
+ * in the browser when they are uploaded.
18910
+ */
18911
+ async function extractVideoMetadata(filename, input, readFile = readFileOrUndefined$2) {
18912
+ if (isHlsPath(filename)) {
18913
+ return extractHlsMetadata(filename, input.toString("utf-8"), readFile);
18914
+ }
18915
+ return extractFromByteSource(filename, bufferByteSource(input));
18916
+ }
18917
+
18918
+ /**
18919
+ * {@link extractVideoMetadata} for a file on disk, reading only the headers
18920
+ * it needs: a video's frames (an mp4's `mdat`, a WebM's Clusters) are most of
18921
+ * the file, and are skipped, not loaded.
18922
+ */
18923
+ async function extractVideoMetadataFromFile(absolutePath) {
18924
+ if (isHlsPath(absolutePath)) {
18925
+ return extractVideoMetadata(absolutePath, fs.readFileSync(absolutePath));
18926
+ }
18927
+ return withFileByteSource(absolutePath, source => extractFromByteSource(absolutePath, source));
18928
+ }
18929
+ const ISO_BMFF_EXTENSIONS = [".mp4", ".m4v", ".mov"];
18930
+ const EBML_EXTENSIONS = [".webm", ".mkv"];
18931
+
18932
+ /** The extensions whose size and length Val reads itself. */
18933
+ const READABLE_VIDEO_EXTENSIONS = [...ISO_BMFF_EXTENSIONS, ...EBML_EXTENSIONS, ".m3u8"];
18934
+
18935
+ /**
18936
+ * What to tell someone whose video's `fields` could not be read. Names the
18937
+ * way out, because "could not read" alone leaves them nowhere to go.
18938
+ */
18939
+ function unreadableVideoMetadataMessage(fileRef, fields) {
18940
+ const extension = extensionOf(fileRef);
18941
+ if (!canReadVideoMetadata(fileRef)) {
18942
+ return `Val cannot read the size and length of a ${extension || "file without an extension"} file on the command line. Upload it again in the Val Studio, or add ${listOf(fields)} by hand.`;
18943
+ }
18944
+ return `Val could not read the ${listOf(fields)} of ${fileRef}. Upload it again in the Val Studio, or add ${listOf(fields)} by hand.`;
18945
+ }
18946
+
18947
+ /** Whether Val reads this video's size and length itself, by its extension. */
18948
+ function canReadVideoMetadata(fileRef) {
18949
+ return READABLE_VIDEO_EXTENSIONS.includes(extensionOf(fileRef));
18950
+ }
18951
+ function extensionOf(fileRef) {
18952
+ return path__default.extname(fileRef.split("?")[0]).toLowerCase();
18953
+ }
18954
+ function listOf(fields) {
18955
+ return fields.length <= 1 ? fields.join("") : `${fields.slice(0, -1).join(", ")} and ${fields[fields.length - 1]}`;
18956
+ }
18957
+ function isHlsPath(filename) {
18958
+ return path__default.extname(filename).toLowerCase() === ".m3u8";
18959
+ }
18960
+ function extractFromByteSource(filename, source) {
18961
+ const metadata = {};
18962
+ const mimeType = Internal.filenameToMimeType(filename);
18963
+ if (mimeType) {
18964
+ metadata.mimeType = mimeType;
18965
+ }
18966
+ const extension = extensionOf(filename);
18967
+ const read = ISO_BMFF_EXTENSIONS.includes(extension) ? readIsoBmffMetadata(source) : EBML_EXTENSIONS.includes(extension) ? readEbmlMetadata(source) : undefined;
18968
+ if (!read) {
18969
+ return metadata;
18970
+ }
18971
+ if (read.width !== undefined && read.height !== undefined) {
18972
+ metadata.width = read.width;
18973
+ metadata.height = read.height;
18974
+ }
18975
+ const duration = roundSeconds(read.duration);
18976
+ if (duration !== undefined) {
18977
+ metadata.duration = duration;
18978
+ }
18979
+ return metadata;
18980
+ }
18981
+
18982
+ /**
18983
+ * An HLS stream's metadata from its master playlist's text, and — for the
18984
+ * duration — the first media playlist it names, which `readMediaPlaylist`
18985
+ * fetches by the URI the master gives (relative to it, or a remote ref). The
18986
+ * one implementation for a stream on disk and one on Val Remote.
18987
+ */
18988
+ async function readHlsMetadata(text, readMediaPlaylist) {
18989
+ const metadata = {
18990
+ mimeType: Internal.media.HLS_MIME_TYPE
18991
+ };
18992
+ if (!isHlsMasterPlaylist(text)) {
18993
+ // A media playlist on its own: it knows how long it is, not how big.
18994
+ const duration = roundSeconds(sumHlsSegmentDurations(text));
18995
+ if (duration !== undefined) {
18996
+ metadata.duration = duration;
18997
+ }
18998
+ return metadata;
18999
+ }
19000
+ const variants = parseHlsMasterVariants(text);
19001
+ const largest = largestHlsVariant(variants);
19002
+ if (largest) {
19003
+ metadata.width = largest.width;
19004
+ metadata.height = largest.height;
19005
+ }
19006
+ // Every rendition is the same length, so the first one listed is as good as
19007
+ // any.
19008
+ const first = variants[0];
19009
+ if (first) {
19010
+ const mediaPlaylist = await readMediaPlaylist(first.uri);
19011
+ if (mediaPlaylist !== undefined) {
19012
+ const duration = roundSeconds(sumHlsSegmentDurations(mediaPlaylist));
19013
+ if (duration !== undefined) {
19014
+ metadata.duration = duration;
19015
+ }
19016
+ }
19017
+ }
19018
+ return metadata;
19019
+ }
19020
+ function extractHlsMetadata(filename, text, readFile) {
19021
+ // Only a relative URI can be read from disk: the Studio writes relative
19022
+ // URIs into a local stream.
19023
+ return readHlsMetadata(text, async uri => {
19024
+ var _readFile;
19025
+ return isRelativeUri(uri) ? (_readFile = readFile(path__default.resolve(path__default.dirname(filename), uri.split(/[?#]/)[0]))) === null || _readFile === void 0 ? void 0 : _readFile.toString("utf-8") : undefined;
19026
+ });
19027
+ }
19028
+ function isRelativeUri(uri) {
19029
+ return !/^[a-z][a-z0-9+.-]*:/i.test(uri) && !uri.startsWith("/");
19030
+ }
19031
+
19032
+ /**
19033
+ * Seconds to the millisecond. A duration summed from `#EXTINF`s or computed
19034
+ * from timestamps carries float noise (`5.999999999`), and this value is
19035
+ * written into a `.val.ts` someone reads.
19036
+ */
19037
+ function roundSeconds(seconds) {
19038
+ if (seconds === undefined || !Number.isFinite(seconds) || seconds <= 0) {
19039
+ return undefined;
19040
+ }
19041
+ return Math.round(seconds * 1000) / 1000;
19042
+ }
19043
+ function readFileOrUndefined$2(absolutePath) {
19044
+ try {
19045
+ return fs.readFileSync(absolutePath);
19046
+ } catch {
19047
+ return undefined;
19048
+ }
19049
+ }
19050
+
19051
+ /**
19052
+ * A remote video's size and length, read over HTTP without downloading it.
19053
+ *
19054
+ * The parsers (`isoBmff.ts`, `ebml.ts`) are synchronous and ask a
19055
+ * {@link ByteSource} for the few header bytes they need. Here that source is
19056
+ * a cache of byte ranges fetched with `Range` requests: when the parser asks
19057
+ * for bytes the cache does not hold, the read throws {@link NeedBytes}, the
19058
+ * missing range is fetched, and the parser runs again from the start. Parsing
19059
+ * headers is microseconds and fetching is milliseconds, so re-running is the
19060
+ * cheap side of that trade — and it keeps ONE parser for files on disk and
19061
+ * files on Val Remote, rather than an async copy of each.
19062
+ *
19063
+ * An mp4 with `moov` first costs one request; one with `moov` after `mdat`
19064
+ * costs about three (the start, the box header past `mdat`, and `moov`
19065
+ * itself), however large the file. An HLS stream is its master playlist and
19066
+ * one media playlist.
19067
+ */
19068
+
19069
+ /** How much to fetch past what was asked for: box headers come in runs. */
19070
+ const READ_AHEAD = 64 * 1024;
19071
+ /** A parser that needs more fetches than this is not reading headers. */
19072
+ const MAX_FETCHES = 16;
19073
+ /** Thrown by a cached read that needs bytes not fetched yet. */
19074
+ class NeedBytes {
19075
+ constructor(offset, length) {
19076
+ this.offset = offset;
19077
+ this.length = length;
19078
+ }
19079
+ }
19080
+
19081
+ /**
19082
+ * Read `url`'s metadata. `nameForType` is the file name its type is read off —
19083
+ * for a remote ref, the `/public/...` path inside it, since the ref's own URL
19084
+ * ends in the same name but is not where a reader would look for it.
19085
+ */
19086
+ async function extractVideoMetadataFromUrl(url, nameForType, fetchImpl = fetch) {
19087
+ if (nameForType.split("?")[0].toLowerCase().endsWith(".m3u8")) {
19088
+ const master = await fetchText(url, fetchImpl);
19089
+ return readHlsMetadata(master, uri => fetchText(new URL(uri, url).toString(), fetchImpl).catch(() => undefined));
19090
+ }
19091
+ const cache = new RangeCache(url, fetchImpl);
19092
+ for (let fetches = 0;; fetches++) {
19093
+ const source = await cache.source();
19094
+ try {
19095
+ return extractFromByteSource(nameForType, source);
19096
+ } catch (err) {
19097
+ if (!(err instanceof NeedBytes)) {
19098
+ throw err;
19099
+ }
19100
+ if (fetches >= MAX_FETCHES) {
19101
+ throw new Error(`Reading the headers of ${url} took more than ${MAX_FETCHES} requests`, {
19102
+ cause: err
19103
+ });
19104
+ }
19105
+ await cache.fetch(err.offset, err.length);
19106
+ }
19107
+ }
19108
+ }
19109
+
19110
+ /** The local `/public/...` path a remote ref names, for its file type. */
19111
+ function nameForTypeOf(ref) {
19112
+ const split = Internal.remote.splitRemoteRef(ref);
19113
+ return split.status === "success" ? `/${split.filePath}` : ref;
19114
+ }
19115
+ async function fetchText(url, fetchImpl) {
19116
+ const res = await fetchImpl(url, {
19117
+ headers: {}
19118
+ });
19119
+ if (!res.ok) {
19120
+ throw new Error(`Could not read ${url}: HTTP ${res.status}`);
19121
+ }
19122
+ return res.text();
19123
+ }
19124
+ class RangeCache {
19125
+ /** Fetched ranges, as [start, bytes]. Few, so a list is enough. */
19126
+ chunks = [];
19127
+ size;
19128
+ constructor(url, fetchImpl) {
19129
+ this.url = url;
19130
+ this.fetchImpl = fetchImpl;
19131
+ }
19132
+
19133
+ /** A source over what is cached, after fetching the start if nothing is. */
19134
+ async source() {
19135
+ if (this.size === undefined) {
19136
+ await this.fetch(0, READ_AHEAD);
19137
+ }
19138
+ const size = this.size ?? 0;
19139
+ return {
19140
+ size,
19141
+ read: (offset, length) => {
19142
+ const end = Math.min(offset + length, size);
19143
+ if (end <= offset) {
19144
+ return Buffer.alloc(0);
19145
+ }
19146
+ for (const [start, bytes] of this.chunks) {
19147
+ if (start <= offset && end <= start + bytes.length) {
19148
+ return bytes.subarray(offset - start, end - start);
19149
+ }
19150
+ }
19151
+ throw new NeedBytes(offset, end - offset);
19152
+ }
19153
+ };
19154
+ }
19155
+ async fetch(offset, length) {
19156
+ const last = offset + Math.max(length, READ_AHEAD) - 1;
19157
+ const res = await this.fetchImpl(this.url, {
19158
+ headers: {
19159
+ Range: `bytes=${offset}-${last}`
19160
+ }
19161
+ });
19162
+ if (res.status === 200) {
19163
+ // The server ignored the range and sent the whole file. That answers
19164
+ // every read there will be.
19165
+ const whole = Buffer.from(await res.arrayBuffer());
19166
+ this.chunks = [[0, whole]];
19167
+ this.size = whole.length;
19168
+ return;
19169
+ }
19170
+ if (res.status !== 206) {
19171
+ throw new Error(`Could not read ${this.url}: HTTP ${res.status}`);
19172
+ }
19173
+ // `bytes 0-65535/1234567`: where the bytes start, and how big the file is.
19174
+ const range = /^bytes (\d+)-(\d+)\/(\d+|\*)$/.exec(res.headers.get("content-range") ?? "");
19175
+ if (!range) {
19176
+ throw new Error(`Could not read ${this.url}: a partial answer without a Content-Range`);
19177
+ }
19178
+ const bytes = Buffer.from(await res.arrayBuffer());
19179
+ if (range[3] !== "*") {
19180
+ this.size = Number(range[3]);
19181
+ } else if (this.size === undefined) {
19182
+ throw new Error(`Could not read ${this.url}: its size is not known`);
19183
+ }
19184
+ this.chunks.push([Number(range[1]), bytes]);
19185
+ }
19186
+ }
19187
+
19188
+ /**
19189
+ * A gallery entry's key, read as what it actually is.
19190
+ *
19191
+ * A gallery is a record keyed by its entries' file paths. A REMOTE gallery keys
19192
+ * an uploaded entry by the remote URL instead — which encodes that same path —
19193
+ * so every entry has a local path, and the interesting question is whether the
19194
+ * bytes are expected to be at it.
19195
+ *
19196
+ * **They are not, for a remote entry added the ordinary way.** `saveOrUploadFiles`
19197
+ * uploads the remote descriptors to the content host and copies only the local
19198
+ * ones into the working tree, so an image added through the Studio (or over MCP)
19199
+ * and published has no file in the repo, by design — putting one there is what
19200
+ * remote storage exists to avoid. A remote entry CAN have one, because
19201
+ * `val validate --fix` promotes a local file to a remote ref and leaves the file
19202
+ * where it was; so "remote" means "do not require it", never "there is not one".
19203
+ *
19204
+ * One copy, in its own file, because this used to be two: a `remoteKeyToLocalPath`
19205
+ * in `fixHandlers` and a `galleryKeyToLocalPath` in `createFixPatch`, each
19206
+ * normalising the key correctly and each then treating the result as a file that
19207
+ * must exist. That agreement is what made a published remote image report as
19208
+ * missing from both sides at once.
19209
+ */
19210
+
19211
+ /**
19212
+ * A key that names somewhere else, whether or not it is a ref we can read.
19213
+ *
19214
+ * Case-insensitive, because a scheme is (RFC 3986) — and because
19215
+ * `splitRemoteRef`'s pattern is not, so `HTTPS://…` is precisely one of the
19216
+ * spellings that arrives here unparsed and must not be mistaken for a path.
19217
+ */
19218
+ function isRemoteUrl(key) {
19219
+ return /^https?:\/\//i.test(key);
19220
+ }
19221
+ function galleryEntryOf(key) {
19222
+ const remoteRefRes = Internal.remote.splitRemoteRef(key);
17902
19223
  if (remoteRefRes.status === "success") {
17903
19224
  return {
17904
- localPath: `/${remoteRefRes.filePath}`,
17905
- remote: true
19225
+ localPath: `/${remoteRefRes.filePath}`,
19226
+ remote: true
19227
+ };
19228
+ }
19229
+ if (isRemoteUrl(key)) {
19230
+ // A URL that is not a ref this version can read: truncated by a hand edit,
19231
+ // a path outside `public/`, a `..` segment — or written by a core version
19232
+ // whose format `splitRemoteRef` rejects.
19233
+ //
19234
+ // Still not a path in the working tree, so the on-disk checks must not run
19235
+ // against it. They would find nothing at `<projectRoot>/https://…`, report
19236
+ // the entry as missing, and `--fix` would DELETE it — the exact failure
19237
+ // this module exists to prevent, arriving at the one moment the key is the
19238
+ // only remaining record of where the bytes went.
19239
+ //
19240
+ // Nothing is being hidden by this: a malformed key is already reported, by
19241
+ // the record schema's own "Invalid remote URL format". That is an error for
19242
+ // a person to look at, not a file for `--fix` to go missing.
19243
+ return {
19244
+ localPath: key,
19245
+ remote: true
19246
+ };
19247
+ }
19248
+ return {
19249
+ localPath: key,
19250
+ remote: false
19251
+ };
19252
+ }
19253
+
19254
+ /**
19255
+ * The media path a validation error is about, if it is about media at all.
19256
+ *
19257
+ * There is no schema in hand here — a `ValidationError` carries only the value
19258
+ * it flagged — so the shape is all there is to go on.
19259
+ */
19260
+ function getValidationErrorFileRef(validationError) {
19261
+ const maybePath = validationError.value && typeof validationError.value === "object" && "path" in validationError.value && typeof validationError.value.path === "string" ? validationError.value.path : undefined;
19262
+ if (!maybePath) {
19263
+ return null;
19264
+ }
19265
+ return maybePath;
19266
+ }
19267
+
19268
+ const textEncoder$1 = new TextEncoder();
19269
+ async function checkRemoteRef(remoteHost, ref, projectRoot, schema, metadata) {
19270
+ const remoteRefDataRes = Internal.remote.splitRemoteRef(ref);
19271
+ if (remoteRefDataRes.status === "error") {
19272
+ return remoteRefDataRes;
19273
+ }
19274
+ const fileHash = remoteRefDataRes.fileHash;
19275
+ if (!fileHash) {
19276
+ return {
19277
+ status: "error",
19278
+ error: `File hash is missing in remote ref: ${ref}`
19279
+ };
19280
+ }
19281
+ const relativeFilePath = remoteRefDataRes.filePath;
19282
+ if (!relativeFilePath) {
19283
+ return {
19284
+ status: "error",
19285
+ error: `File path is missing in remote ref: ${ref}`
19286
+ };
19287
+ }
19288
+ if (!relativeFilePath.startsWith("public/")) {
19289
+ return {
19290
+ status: "error",
19291
+ error: `File path must be within the public/ directory (e.g. public/path/to/file.txt). Got: ${relativeFilePath}`
19292
+ };
19293
+ }
19294
+ const coreVersion = Internal.VERSION.core || "unknown";
19295
+ const fileExt = getFileExt(relativeFilePath);
19296
+ const currentValidationHash = Internal.remote.getValidationHash(coreVersion, schema, fileExt, metadata,
19297
+ // TODO: validate
19298
+ fileHash, textEncoder$1);
19299
+ const validationHashFromRemoteRefValues = Internal.remote.getValidationHash(remoteRefDataRes.version, schema, getFileExt(remoteRefDataRes.filePath), metadata,
19300
+ // TODO: validate
19301
+ fileHash, textEncoder$1);
19302
+ if (
19303
+ // Current validation hash is the same as the remote validation hash
19304
+ // We assume the uploaded file exists and is correct
19305
+ currentValidationHash === remoteRefDataRes.validationHash &&
19306
+ // This can happen if the version or fileExt has been tampered with
19307
+ // (or if the way it is computed has changed)
19308
+ validationHashFromRemoteRefValues === remoteRefDataRes.validationHash) {
19309
+ return {
19310
+ status: "success"
19311
+ };
19312
+ }
19313
+ // Validation hash does not match, so we need to re-validate the remote content
19314
+ const fileBufferRes = await getFileBufferFromRemote(ref, fileExt, remoteRefDataRes.fileHash, projectRoot);
19315
+
19316
+ // We could not download the remote file for some reason (for example, the file hash is wrong)
19317
+ if (fileBufferRes.status === "error") {
19318
+ return fileBufferRes;
19319
+ }
19320
+
19321
+ // At this point we have the file buffer and we know the correct file hash
19322
+ // We must create a new ref since something has changed
19323
+
19324
+ let currentMetadata;
19325
+ try {
19326
+ if (schema.type === "image") {
19327
+ currentMetadata = await extractImageMetadata(remoteRefDataRes.filePath, fileBufferRes.fileBuffer);
19328
+ } else if (schema.type === "file") {
19329
+ currentMetadata = await extractFileMetadata(remoteRefDataRes.filePath, fileBufferRes.fileBuffer);
19330
+ } else {
19331
+ const exhaustiveCheck = schema;
19332
+ return {
19333
+ status: "error",
19334
+ error: `Unknown schema type: ${JSON.stringify(exhaustiveCheck)}`
19335
+ };
19336
+ }
19337
+ } catch (err) {
19338
+ return {
19339
+ status: "error",
19340
+ error: `Failed to extract metadata from remote file: ${err instanceof Error ? err.message : "Unknown error"}. Cached file: ${fileBufferRes.cachedFilePath}`
19341
+ };
19342
+ }
19343
+ const updatedMetadata = {
19344
+ ...metadata,
19345
+ ...currentMetadata
19346
+ };
19347
+ const nextValidationHash = Internal.remote.getValidationHash(coreVersion, schema, fileExt, updatedMetadata, fileBufferRes.fileHash, textEncoder$1);
19348
+ if (!updatedMetadata.mimeType) {
19349
+ return {
19350
+ status: "error",
19351
+ error: `MIME type is missing in metadata: ${JSON.stringify(updatedMetadata)}`
19352
+ };
19353
+ }
19354
+ const newFileExt = Internal.mimeTypeToFileExt(updatedMetadata.mimeType);
19355
+ const newFilePath = relativeFilePath.slice(0, -fileExt.length) + newFileExt;
19356
+ return {
19357
+ status: "fix-required",
19358
+ metadata: updatedMetadata,
19359
+ ref: Internal.remote.createRemoteRef(remoteHost, {
19360
+ publicProjectId: remoteRefDataRes.projectId,
19361
+ coreVersion,
19362
+ bucket: remoteRefDataRes.bucket,
19363
+ validationHash: nextValidationHash,
19364
+ fileHash: fileBufferRes.fileHash,
19365
+ filePath: newFilePath
19366
+ })
19367
+ };
19368
+ }
19369
+ function getCachedRemoteFileDir(projectRoot) {
19370
+ // store in projectRoot/.val/remote-file-cache
19371
+ const remoteFileCacheDir = path__default.join(projectRoot, ".val", "remote-file-cache");
19372
+ return remoteFileCacheDir;
19373
+ }
19374
+ function getCachedRemoteFilePath(fileExt, currentFileHash, remoteFileCacheDir) {
19375
+ const remoteFilePath = path__default.join(remoteFileCacheDir, currentFileHash + "." + fileExt);
19376
+ return remoteFilePath;
19377
+ }
19378
+ async function getFileBufferFromRemote(ref, fileExt, currentFileHash, projectRoot) {
19379
+ const remoteFileCacheDir = getCachedRemoteFileDir(projectRoot);
19380
+ const remoteFilePath = getCachedRemoteFilePath(fileExt, currentFileHash, remoteFileCacheDir);
19381
+ try {
19382
+ const fileBuffer = await fs.promises.readFile(remoteFilePath);
19383
+ const computedFileHash = Internal.remote.getFileHash(fileBuffer);
19384
+ if (computedFileHash !== currentFileHash) {
19385
+ await fs.promises.unlink(remoteFilePath);
19386
+ throw Error(`Cached file hash does not match the expected hash: ${computedFileHash} !== ${currentFileHash}`);
19387
+ }
19388
+ } catch {
19389
+ try {
19390
+ await fs.promises.mkdir(remoteFileCacheDir, {
19391
+ recursive: true
19392
+ });
19393
+ await downloadFileFromRemote(ref, remoteFilePath);
19394
+ } catch (err) {
19395
+ try {
19396
+ // try to delete in case of partial download
19397
+ await fs.promises.unlink(remoteFilePath);
19398
+ } catch {
19399
+ //
19400
+ }
19401
+ return {
19402
+ status: "error",
19403
+ error: `Failed to download remote file: ${err instanceof Error ? err.message : "Unknown error"}`
19404
+ };
19405
+ }
19406
+ }
19407
+ const fileBuffer = await fs.promises.readFile(remoteFilePath);
19408
+ const computedFileHash = Internal.remote.getFileHash(fileBuffer);
19409
+ return {
19410
+ status: "success",
19411
+ fileBuffer,
19412
+ fileHash: computedFileHash,
19413
+ cachedFilePath: remoteFilePath
19414
+ };
19415
+ }
19416
+ async function downloadFileFromRemote(ref, filePath) {
19417
+ return new Promise((resolve, reject) => {
19418
+ const url = new URL(ref);
19419
+ const client = url.protocol === "https:" ? https$1 : http$1;
19420
+ const request = client.get(url, response => {
19421
+ if (response.statusCode && response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) {
19422
+ // Handle redirects
19423
+ return downloadFileFromRemote(response.headers.location, filePath).then(resolve).catch(reject);
19424
+ }
19425
+ if (response.statusCode == 404) {
19426
+ return reject(new Error(`${ref}. File not found. The URL is most likely incorrect.`));
19427
+ }
19428
+ if (response.statusCode !== 200) {
19429
+ return reject(new Error(`${ref}. Failed to download file. HTTP Status: ${response.statusCode}`));
19430
+ }
19431
+ const writeStream = fs.createWriteStream(filePath);
19432
+ response.pipe(writeStream);
19433
+ writeStream.on("finish", () => resolve({
19434
+ status: "success",
19435
+ filePath
19436
+ }));
19437
+ writeStream.on("error", err => reject(new Error(`${ref}. Error writing file: ${err.message}`)));
19438
+ });
19439
+ request.on("error", err => reject(new Error(`${ref}. Download error: ${err.message}`)));
19440
+ request.end();
19441
+ });
19442
+ }
19443
+
19444
+ const textEncoder = new TextEncoder();
19445
+
19446
+ /**
19447
+ * Everything an upload to Val Remote needs before it has any bytes: the
19448
+ * developer's token, the project's public id and a bucket. Opened once per
19449
+ * fix, so a video's dozen files go up under one session and into one bucket
19450
+ * rather than a bucket each.
19451
+ */
19452
+
19453
+ async function openRemoteUploadSession(ctx) {
19454
+ const fail = errorMessage => ({
19455
+ success: false,
19456
+ result: {
19457
+ success: false,
19458
+ errorMessage
19459
+ }
19460
+ });
19461
+ const patFile = getPersonalAccessTokenPath(ctx.projectRoot);
19462
+ if (!ctx.fs.fileExists(patFile)) {
19463
+ return fail(`File: ${path__default.join(ctx.projectRoot, ctx.file)} has remote files that are not uploaded and you are not logged in.\n\nFix this error by logging in:\n\t"npx val login"\n`);
19464
+ }
19465
+ const patFileContent = ctx.fs.readFile(patFile);
19466
+ if (patFileContent === undefined) {
19467
+ return fail(`Could not read personal access token file at ${patFile}`);
19468
+ }
19469
+ const parsedPatFile = parsePersonalAccessTokenFile(patFileContent);
19470
+ if (!parsedPatFile.success) {
19471
+ return fail(`Error parsing personal access token file: ${parsedPatFile.error}. You need to login again.`);
19472
+ }
19473
+ const {
19474
+ pat
19475
+ } = parsedPatFile.data;
19476
+ const projectName = ctx.project;
19477
+ let publicProjectId = ctx.publicProjectId;
19478
+ let remoteFileBuckets = ctx.remoteFileBuckets;
19479
+ let remoteFilesCounter = ctx.remoteFilesCounter;
19480
+ if (!publicProjectId || !remoteFileBuckets) {
19481
+ if (!projectName) {
19482
+ return fail("Project name not found. Add project name to val.config or set the VAL_PROJECT environment variable");
19483
+ }
19484
+ const settingsRes = await ctx.remote.getSettings(projectName, {
19485
+ pat
19486
+ });
19487
+ if (!settingsRes.success) {
19488
+ return fail(`Could not get public project id: ${settingsRes.message}.`);
19489
+ }
19490
+ publicProjectId = settingsRes.data.publicProjectId;
19491
+ remoteFileBuckets = settingsRes.data.remoteFileBuckets.map(b => b.bucket);
19492
+ }
19493
+ if (!publicProjectId) {
19494
+ return fail("Could not get public project id");
19495
+ }
19496
+ if (!projectName) {
19497
+ return fail(`Could not get project. Check that your val.config has the 'project' field set, or set it using the VAL_PROJECT environment variable`);
19498
+ }
19499
+ remoteFilesCounter += 1;
19500
+ const bucket = remoteFileBuckets[remoteFilesCounter % remoteFileBuckets.length];
19501
+ if (!bucket) {
19502
+ return fail(`Internal error: could not allocate a bucket for the remote file located at ${ctx.sourcePath}`);
19503
+ }
19504
+ return {
19505
+ success: true,
19506
+ session: {
19507
+ pat,
19508
+ projectName,
19509
+ publicProjectId,
19510
+ bucket,
19511
+ remoteFileBuckets,
19512
+ remoteFilesCounter
19513
+ }
19514
+ };
19515
+ }
19516
+
19517
+ /**
19518
+ * Upload one file's bytes and return the ref they are served at.
19519
+ *
19520
+ * `relativeFilePath` is the file's path under the project (`public/...`),
19521
+ * which the ref encodes; the bytes need not be the bytes on disk there — a
19522
+ * video's playlists are uploaded REWRITTEN, naming the refs of what they list.
19523
+ */
19524
+ async function uploadBytesToRemote(ctx, session, relativeFilePath, fileBuffer, metadata, schema) {
19525
+ if (!relativeFilePath.startsWith("public/")) {
19526
+ return {
19527
+ success: false,
19528
+ error: `File path must be within the public/ directory (e.g. public/path/to/file.txt). Got: ${relativeFilePath}`
19529
+ };
19530
+ }
19531
+ const fileHash = Internal.remote.getFileHash(fileBuffer);
19532
+ const coreVersion = Internal.VERSION.core || "unknown";
19533
+ const fileExt = getFileExt(relativeFilePath);
19534
+ const ref = Internal.remote.createRemoteRef(ctx.remote.remoteHost, {
19535
+ publicProjectId: session.publicProjectId,
19536
+ coreVersion,
19537
+ bucket: session.bucket,
19538
+ validationHash: Internal.remote.getValidationHash(coreVersion, schema, fileExt, metadata, fileHash, textEncoder),
19539
+ fileHash,
19540
+ filePath: relativeFilePath
19541
+ });
19542
+ const remoteFileUpload = await ctx.remote.uploadFile(session.projectName, session.bucket, fileHash, fileExt, fileBuffer, {
19543
+ pat: session.pat
19544
+ });
19545
+ if (!remoteFileUpload.success) {
19546
+ return {
19547
+ success: false,
19548
+ error: `Could not upload remote file: '${ref}'. Error: ${remoteFileUpload.error}`
19549
+ };
19550
+ }
19551
+ return {
19552
+ success: true,
19553
+ ref
19554
+ };
19555
+ }
19556
+
19557
+ /**
19558
+ * Every file a video value names, as refs (`/public/…`, or a remote URL as
19559
+ * written): the video, its poster, each caption track — and, for a LOCAL HLS
19560
+ * stream, every file its playlists name, followed from the master down through
19561
+ * each media playlist to the segment files, init sections and audio tracks.
19562
+ *
19563
+ * Followed rather than "everything in the master's directory": the Studio
19564
+ * gives each stream a directory of its own, but nothing stops a hand-placed
19565
+ * `/public/val/clip.m3u8`, and the directory of THAT one is every file in
19566
+ * `/public/val`. A file in a stream's directory that no playlist names is not
19567
+ * used by the stream either, so calling it unused is right.
19568
+ *
19569
+ * A remote stream's playlists are on the content host, so its master is all
19570
+ * that is named here.
19571
+ *
19572
+ * The one place that answers this, so `list-unused-files` and anything else
19573
+ * asking "is this file used" agree on what a video holds.
19574
+ */
19575
+ function filesOfVideo(video, options) {
19576
+ if (!isObject(video) || typeof video.path !== "string") {
19577
+ return [];
19578
+ }
19579
+ const refs = new Set([video.path]);
19580
+ if (isObject(video.poster) && typeof video.poster.path === "string") {
19581
+ refs.add(video.poster.path);
19582
+ }
19583
+ if (Array.isArray(video.captions)) {
19584
+ for (const track of video.captions) {
19585
+ if (isObject(track) && typeof track.path === "string") {
19586
+ refs.add(track.path);
19587
+ }
19588
+ }
19589
+ }
19590
+ const mimeType = typeof video.mimeType === "string" ? video.mimeType : undefined;
19591
+ if (!Internal.isRemoteMediaPath(video.path) && Internal.media.isHlsVideo({
19592
+ path: video.path,
19593
+ mimeType
19594
+ })) {
19595
+ const readFile = options.readFile ?? readFileOrUndefined$1;
19596
+ const pending = [video.path.split("?")[0]];
19597
+ const visited = new Set();
19598
+ while (pending.length > 0) {
19599
+ var _readFile;
19600
+ const playlist = pending.pop();
19601
+ if (visited.has(playlist)) {
19602
+ continue;
19603
+ }
19604
+ visited.add(playlist);
19605
+ const text = (_readFile = readFile(path__default.join(options.projectRoot, ...playlist.split("/")))) === null || _readFile === void 0 ? void 0 : _readFile.toString("utf-8");
19606
+ if (text === undefined) {
19607
+ continue;
19608
+ }
19609
+ mapHlsUris(text, uri => {
19610
+ const ref = localRefOf(uri, playlist);
19611
+ if (ref !== undefined) {
19612
+ refs.add(ref);
19613
+ if (ref.toLowerCase().endsWith(".m3u8")) {
19614
+ pending.push(ref);
19615
+ }
19616
+ }
19617
+ return uri;
19618
+ });
19619
+ }
19620
+ }
19621
+ return [...refs];
19622
+ }
19623
+
19624
+ /** A playlist URI as a local ref, when it is relative; otherwise undefined. */
19625
+ function localRefOf(uri, playlist) {
19626
+ if (/^[a-z][a-z0-9+.-]*:/i.test(uri) || uri.startsWith("/")) {
19627
+ return undefined;
19628
+ }
19629
+ const relative = uri.split(/[?#]/)[0];
19630
+ if (relative === "") {
19631
+ return undefined;
19632
+ }
19633
+ return path__default.posix.join(path__default.posix.dirname(playlist), relative);
19634
+ }
19635
+ function isObject(value) {
19636
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19637
+ }
19638
+ function readFileOrUndefined$1(absolutePath) {
19639
+ try {
19640
+ return fs.readFileSync(absolutePath);
19641
+ } catch {
19642
+ return undefined;
19643
+ }
19644
+ }
19645
+
19646
+ /**
19647
+ * `video:upload-remote` and `video:download-remote`: move a video between the
19648
+ * repository and Val Remote.
19649
+ *
19650
+ * A video is the one media value that names several files — the video, its
19651
+ * poster, its caption tracks, and for an HLS stream every playlist and segment
19652
+ * its master names — so one fix moves all of them, and the patch then rewrites
19653
+ * every `path` the value holds. Moving only some would leave a video that is
19654
+ * half on each side, which validation rejects and no page can play.
19655
+ *
19656
+ * HLS is the part that is not a copy. The content host serves a file by its
19657
+ * HASH, so a relative name in a playlist resolves to nothing there: on the way
19658
+ * UP every playlist is rewritten to name the refs of what it lists, bottom-up
19659
+ * (a playlist's ref is the hash of its rewritten bytes, so what it names must
19660
+ * be uploaded first). On the way DOWN the same playlists are rewritten back to
19661
+ * relative names, which is what lets a published stream be plain static files.
19662
+ */
19663
+ function isRecord$2(value) {
19664
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19665
+ }
19666
+ function isPlaylist$1(ref) {
19667
+ return ref.split("?")[0].toLowerCase().endsWith(".m3u8");
19668
+ }
19669
+
19670
+ /** The paths a video value holds, each with where in the value it sits. */
19671
+ function videoPathsOf(video) {
19672
+ if (!isRecord$2(video) || typeof video.path !== "string") {
19673
+ return [];
19674
+ }
19675
+ const found = [{
19676
+ at: ["path"],
19677
+ path: video.path
19678
+ }];
19679
+ if (isRecord$2(video.poster) && typeof video.poster.path === "string") {
19680
+ found.push({
19681
+ at: ["poster", "path"],
19682
+ path: video.poster.path
19683
+ });
19684
+ }
19685
+ if (Array.isArray(video.captions)) {
19686
+ video.captions.forEach((track, index) => {
19687
+ if (isRecord$2(track) && typeof track.path === "string") {
19688
+ found.push({
19689
+ at: ["captions", String(index), "path"],
19690
+ path: track.path
19691
+ });
19692
+ }
19693
+ });
19694
+ }
19695
+ return found;
19696
+ }
19697
+
19698
+ /**
19699
+ * The patch that points a video at where its files now are: one `add` per
19700
+ * path that moved, so the authored fields beside them — the description, the
19701
+ * times, the caption labels — are never rewritten.
19702
+ */
19703
+ function rewriteVideoPathsPatch(sourcePath, video, moved) {
19704
+ const base = sourceToPatchPath(sourcePath);
19705
+ const patch = [];
19706
+ for (const {
19707
+ at,
19708
+ path: current
19709
+ } of videoPathsOf(video)) {
19710
+ const to = moved[current];
19711
+ if (to !== undefined && to !== current) {
19712
+ patch.push({
19713
+ op: "add",
19714
+ path: base.concat(at),
19715
+ value: to
19716
+ });
19717
+ }
19718
+ }
19719
+ return patch;
19720
+ }
19721
+
19722
+ /** A relative playlist URI as a `/public/...` ref, or undefined if it is not one. */
19723
+ function resolvePlaylistUri(uri, playlist) {
19724
+ if (/^[a-z][a-z0-9+.-]*:/i.test(uri) || uri.startsWith("/")) {
19725
+ return undefined;
19726
+ }
19727
+ const relative = uri.split(/[?#]/)[0];
19728
+ if (relative === "") {
19729
+ return undefined;
19730
+ }
19731
+ return path__default.posix.join(path__default.posix.dirname(playlist), relative);
19732
+ }
19733
+ function playlistUris(text) {
19734
+ const uris = [];
19735
+ mapHlsUris(text, uri => {
19736
+ if (!uris.includes(uri)) uris.push(uri);
19737
+ return uri;
19738
+ });
19739
+ return uris;
19740
+ }
19741
+
19742
+ /** What a file is to the video that names it, which decides its hash basis. */
19743
+
19744
+ /**
19745
+ * What a file's validation hash is computed from — the same as the Studio
19746
+ * computes for an upload (`createVideoPatch`), so a video moved by the CLI and
19747
+ * one uploaded in the Studio carry refs of the same kind.
19748
+ */
19749
+ function metadataOf(localRef, role, video) {
19750
+ const mimeType = Internal.filenameToMimeType(localRef);
19751
+ if (role === "video") {
19752
+ return {
19753
+ mimeType,
19754
+ width: video.width,
19755
+ height: video.height
19756
+ };
19757
+ }
19758
+ if (role === "poster" && isRecord$2(video.poster)) {
19759
+ return {
19760
+ mimeType: video.poster.mimeType ?? mimeType,
19761
+ width: video.poster.width,
19762
+ height: video.poster.height
19763
+ };
19764
+ }
19765
+ return {
19766
+ mimeType
19767
+ };
19768
+ }
19769
+
19770
+ /**
19771
+ * Places a video's local files on Val Remote, each once, and remembers where.
19772
+ *
19773
+ * The one implementation of "upload a video" for every fix that does it: a
19774
+ * video field (`video:upload-remote`), and an entry of an `s.videoset()`
19775
+ * (`videos:upload-remote`). What differs between the two is which files go up
19776
+ * and what their refs are hashed against, so those are the arguments.
19777
+ *
19778
+ * A playlist goes up AFTER everything it names, rewritten to name their refs:
19779
+ * the content host serves a file by its hash, so a relative name in a playlist
19780
+ * resolves to nothing there — and a playlist's own ref is the hash of its
19781
+ * rewritten bytes, so what it names must have refs first.
19782
+ */
19783
+ function createVideoUploader(ctx, session, schema, metadataFor) {
19784
+ const moved = new Map();
19785
+ const events = [];
19786
+ const put = async (localRef, role) => {
19787
+ const already = moved.get(localRef);
19788
+ if (already !== undefined) {
19789
+ return already;
19790
+ }
19791
+ const absolute = path__default.join(ctx.projectRoot, localRef);
19792
+ const buffer = ctx.fs.readBuffer(absolute);
19793
+ if (buffer === undefined) {
19794
+ throw new Error(`Error reading file: ${absolute}`);
19795
+ }
19796
+ let bytes = buffer;
19797
+ if (isPlaylist$1(localRef)) {
19798
+ // Bottom-up: what this playlist names goes up first, so the refs it is
19799
+ // rewritten to exist — and so its own hash is of the rewritten bytes.
19800
+ const text = buffer.toString("utf-8");
19801
+ const refs = new Map();
19802
+ for (const uri of playlistUris(text)) {
19803
+ const target = resolvePlaylistUri(uri, localRef);
19804
+ if (target !== undefined) {
19805
+ refs.set(uri, await put(target, "stream"));
19806
+ }
19807
+ }
19808
+ bytes = Buffer.from(mapHlsUris(text, uri => refs.get(uri) ?? uri), "utf-8");
19809
+ }
19810
+ const uploaded = await uploadBytesToRemote(ctx, session, localRef.replace(/^\//, ""), bytes, metadataFor(localRef, role), schema);
19811
+ if (!uploaded.success) {
19812
+ throw new Error(uploaded.error);
19813
+ }
19814
+ moved.set(localRef, uploaded.ref);
19815
+ events.push({
19816
+ type: "remote-uploaded",
19817
+ ref: uploaded.ref
19818
+ });
19819
+ return uploaded.ref;
19820
+ };
19821
+ return {
19822
+ put,
19823
+ moved,
19824
+ events
19825
+ };
19826
+ }
19827
+
19828
+ /**
19829
+ * The first of `refs` — and of every file an HLS stream among them names —
19830
+ * that is not on disk, as an absolute path.
19831
+ *
19832
+ * Asked before anything goes up: a missing segment found after the master's
19833
+ * siblings were uploaded leaves bytes on the content host that nothing names.
19834
+ */
19835
+ function firstMissingVideoFile(ctx, refs) {
19836
+ for (const ref of refs) {
19837
+ const files = filesOfVideo({
19838
+ path: ref.path,
19839
+ mimeType: ref.mimeType
19840
+ }, {
19841
+ projectRoot: ctx.projectRoot,
19842
+ readFile: absolute => ctx.fs.readBuffer(absolute)
19843
+ });
19844
+ for (const file of files) {
19845
+ const absolute = path__default.join(ctx.projectRoot, file);
19846
+ if (!ctx.fs.fileExists(absolute)) {
19847
+ return absolute;
19848
+ }
19849
+ }
19850
+ }
19851
+ return undefined;
19852
+ }
19853
+ function resolveVideo(ctx) {
19854
+ var _resolved$schema;
19855
+ const [, modulePath] = Internal.splitModuleFilePathAndModulePath(ctx.sourcePath);
19856
+ if (!ctx.valModule.source || !ctx.valModule.schema) {
19857
+ return {
19858
+ success: false,
19859
+ result: {
19860
+ success: false,
19861
+ errorMessage: `Could not resolve source or schema for ${ctx.sourcePath}`
19862
+ }
19863
+ };
19864
+ }
19865
+ const resolved = Internal.resolvePath(modulePath, ctx.valModule.source, ctx.valModule.schema);
19866
+ const video = resolved.source;
19867
+ if (((_resolved$schema = resolved.schema) === null || _resolved$schema === void 0 ? void 0 : _resolved$schema.type) !== "video" || !isRecord$2(video) || typeof video.path !== "string") {
19868
+ return {
19869
+ success: false,
19870
+ result: {
19871
+ success: false,
19872
+ errorMessage: `Expected a video at ${ctx.sourcePath}`
19873
+ }
19874
+ };
19875
+ }
19876
+ return {
19877
+ success: true,
19878
+ video,
19879
+ schema: resolved.schema
19880
+ };
19881
+ }
19882
+
19883
+ /**
19884
+ * The paths of a video FIELD that its fix moves.
19885
+ *
19886
+ * All of them for a video of its own. For a field picked from an
19887
+ * `s.videoset()` (`referencedModule`), only the poster and the captions: the
19888
+ * video file is the set's — its key there — and moving it from here would
19889
+ * leave the field naming a file the set does not have. The set's own fix
19890
+ * (`videos:upload-remote`) moves it, and rewrites the fields that name it.
19891
+ */
19892
+ function movablePathsOf(video, schema) {
19893
+ const setBacked = schema.referencedModule !== undefined;
19894
+ return videoPathsOf(video).filter(({
19895
+ at
19896
+ }) => !setBacked || at[0] !== "path");
19897
+ }
19898
+ async function handleVideoUploadRemote(ctx) {
19899
+ if (!ctx.fix) {
19900
+ return {
19901
+ success: false,
19902
+ errorMessage: `Video needs to be uploaded to Val Remote (use --fix to upload)`
19903
+ };
19904
+ }
19905
+ const resolved = resolveVideo(ctx);
19906
+ if (!resolved.success) {
19907
+ return resolved.result;
19908
+ }
19909
+ const {
19910
+ video,
19911
+ schema
19912
+ } = resolved;
19913
+ if (ctx.remoteFiles[ctx.sourcePath]) {
19914
+ return {
19915
+ success: true,
19916
+ shouldApplyPatch: true,
19917
+ events: [{
19918
+ type: "remote-already-uploaded",
19919
+ filePath: String(video.path)
19920
+ }]
19921
+ };
19922
+ }
19923
+ const toUpload = movablePathsOf(video, schema).filter(({
19924
+ path: ref
19925
+ }) => !Internal.isRemoteMediaPath(ref));
19926
+ // Every file is checked before any goes up: a missing caption found after
19927
+ // the video was uploaded leaves bytes on the content host that nothing names.
19928
+ const missing = firstMissingVideoFile(ctx, toUpload.map(({
19929
+ at,
19930
+ path: ref
19931
+ }) => ({
19932
+ path: ref,
19933
+ ...(at[0] === "path" && typeof video.mimeType === "string" ? {
19934
+ mimeType: video.mimeType
19935
+ } : {})
19936
+ })));
19937
+ if (missing !== undefined) {
19938
+ return {
19939
+ success: false,
19940
+ errorMessage: `File ${missing} does not exist`
17906
19941
  };
17907
19942
  }
17908
- if (isRemoteUrl(key)) {
17909
- // A URL that is not a ref this version can read: truncated by a hand edit,
17910
- // a path outside `public/`, a `..` segment — or written by a core version
17911
- // whose format `splitRemoteRef` rejects.
17912
- //
17913
- // Still not a path in the working tree, so the on-disk checks must not run
17914
- // against it. They would find nothing at `<projectRoot>/https://…`, report
17915
- // the entry as missing, and `--fix` would DELETE it — the exact failure
17916
- // this module exists to prevent, arriving at the one moment the key is the
17917
- // only remaining record of where the bytes went.
17918
- //
17919
- // Nothing is being hidden by this: a malformed key is already reported, by
17920
- // the record schema's own "Invalid remote URL format". That is an error for
17921
- // a person to look at, not a file for `--fix` to go missing.
19943
+ const opened = await openRemoteUploadSession(ctx);
19944
+ if (!opened.success) {
19945
+ return opened.result;
19946
+ }
19947
+ const {
19948
+ session
19949
+ } = opened;
19950
+ const uploader = createVideoUploader(ctx, session, schema, (localRef, role) => metadataOf(localRef, role, video));
19951
+ try {
19952
+ for (const {
19953
+ at,
19954
+ path: ref
19955
+ } of toUpload) {
19956
+ await uploader.put(ref, at[0] === "poster" ? "poster" : at[0] === "captions" ? "caption" : "video");
19957
+ }
19958
+ } catch (err) {
19959
+ return {
19960
+ success: false,
19961
+ errorMessage: err instanceof Error ? err.message : String(err)
19962
+ };
19963
+ }
19964
+ const refs = Object.fromEntries(uploader.moved);
19965
+ ctx.remoteFiles[ctx.sourcePath] = {
19966
+ ref: refs[String(video.path)] ?? String(video.path),
19967
+ refs
19968
+ };
19969
+ return {
19970
+ success: true,
19971
+ shouldApplyPatch: true,
19972
+ publicProjectId: session.publicProjectId,
19973
+ remoteFileBuckets: session.remoteFileBuckets,
19974
+ remoteFilesCounter: session.remoteFilesCounter,
19975
+ events: uploader.events
19976
+ };
19977
+ }
19978
+ async function handleVideoDownloadRemote(ctx) {
19979
+ if (!ctx.fix) {
19980
+ return {
19981
+ success: false,
19982
+ errorMessage: `Video ${ctx.sourcePath} needs to be downloaded (use --fix to download)`
19983
+ };
19984
+ }
19985
+ const resolved = resolveVideo(ctx);
19986
+ if (!resolved.success) {
19987
+ return resolved.result;
19988
+ }
19989
+ const {
19990
+ video,
19991
+ schema
19992
+ } = resolved;
19993
+ const moved = new Map();
19994
+ const fetchTo = async ref => {
19995
+ const already = moved.get(ref);
19996
+ if (already !== undefined) {
19997
+ return already;
19998
+ }
19999
+ const split = Internal.remote.splitRemoteRef(ref);
20000
+ if (split.status === "error") {
20001
+ throw new Error(`Not a Val Remote ref: ${ref} (${split.error})`);
20002
+ }
20003
+ if (!split.filePath.startsWith("public/")) {
20004
+ throw new Error(`Cannot download ${ref}: its file path must start with public/ (got ${split.filePath})`);
20005
+ }
20006
+ const localRef = `/${split.filePath}`;
20007
+ const absolute = path__default.join(ctx.projectRoot, split.filePath);
20008
+ await fs.promises.mkdir(path__default.dirname(absolute), {
20009
+ recursive: true
20010
+ });
20011
+ const res = await downloadFileFromRemote(ref, absolute);
20012
+ if (res.status === "error") {
20013
+ throw new Error(res.error);
20014
+ }
20015
+ moved.set(ref, localRef);
20016
+ if (isPlaylist$1(localRef)) {
20017
+ // Back to relative names: a local stream is plain static files, and the
20018
+ // draft endpoint rewrites relative names, not refs.
20019
+ const text = fs.readFileSync(absolute, "utf-8");
20020
+ const local = new Map();
20021
+ for (const uri of playlistUris(text)) {
20022
+ if (Internal.remote.splitRemoteRef(uri).status === "success") {
20023
+ const target = await fetchTo(uri);
20024
+ local.set(uri, path__default.posix.relative(path__default.posix.dirname(localRef), target));
20025
+ }
20026
+ }
20027
+ fs.writeFileSync(absolute, mapHlsUris(text, uri => local.get(uri) ?? uri), "utf-8");
20028
+ }
20029
+ return localRef;
20030
+ };
20031
+ try {
20032
+ for (const {
20033
+ path: ref
20034
+ } of movablePathsOf(video, schema)) {
20035
+ if (Internal.isRemoteMediaPath(ref)) {
20036
+ await fetchTo(ref);
20037
+ }
20038
+ }
20039
+ } catch (err) {
20040
+ return {
20041
+ success: false,
20042
+ errorMessage: err instanceof Error ? err.message : String(err)
20043
+ };
20044
+ }
20045
+ const refs = Object.fromEntries(moved);
20046
+ ctx.remoteFiles[ctx.sourcePath] = {
20047
+ ref: refs[String(video.path)] ?? String(video.path),
20048
+ refs
20049
+ };
20050
+ return {
20051
+ success: true,
20052
+ shouldApplyPatch: true,
20053
+ events: [{
20054
+ type: "remote-downloading",
20055
+ sourcePath: ctx.sourcePath
20056
+ }]
20057
+ };
20058
+ }
20059
+
20060
+ /**
20061
+ * What is out of step between a gallery's entries and its directory.
20062
+ *
20063
+ * Two questions, and they treat a remote entry differently — which is the whole
20064
+ * reason this is separate from the handler around it:
20065
+ *
20066
+ * - **Missing**: an entry with no bytes at its local path. Asked of LOCAL
20067
+ * entries only. A remote entry's bytes live on the content host, and nothing
20068
+ * puts a copy in the working tree: `saveOrUploadFiles` uploads the remote
20069
+ * descriptors and copies only the local ones into the tree, so a remote entry
20070
+ * added through the Studio (or over MCP) has no local file by design, and
20071
+ * demanding one would mean committing remote bytes to git — which is what
20072
+ * remote storage exists to avoid. Whether those bytes really are on the host
20073
+ * is a different check, `image:check-remote`, which already runs for exactly
20074
+ * these entries.
20075
+ * - **Untracked**: a file in the directory that no entry claims. Asked of every
20076
+ * entry, remote included, and that is why they are normalised to their local
20077
+ * path: `val validate --fix` promotes a local file to a remote ref and leaves
20078
+ * the file where it was, so a remote entry can perfectly well have one.
20079
+ *
20080
+ * An entry can claim more than its key. A video set's HLS stream is keyed by
20081
+ * its master playlist, and the media playlists and segments it names are the
20082
+ * same entry — so `filesOfEntry` says what else an entry holds, and those are
20083
+ * not untracked either.
20084
+ *
20085
+ * Its own module rather than a part of `fixHandlers.ts`, so the video set's
20086
+ * fixes can use it without importing the handler registry they are part of.
20087
+ */
20088
+ function checkGalleryFiles(input) {
20089
+ const {
20090
+ dir,
20091
+ projectRoot,
20092
+ fs,
20093
+ filesOfEntry
20094
+ } = input;
20095
+ const entries = input.entryKeys.map(key => ({
20096
+ key,
20097
+ entry: galleryEntryOf(key)
20098
+ }));
20099
+ const trackedFiles = new Set();
20100
+ for (const {
20101
+ key,
20102
+ entry
20103
+ } of entries) {
20104
+ trackedFiles.add(entry.localPath);
20105
+ for (const file of (filesOfEntry === null || filesOfEntry === void 0 ? void 0 : filesOfEntry(entry, key)) ?? []) {
20106
+ trackedFiles.add(file);
20107
+ }
20108
+ }
20109
+ const missingTrackedFiles = entries.filter(({
20110
+ entry
20111
+ }) => !entry.remote && !fs.fileExists(path__default.join(projectRoot, entry.localPath))).map(({
20112
+ entry
20113
+ }) => entry.localPath);
20114
+ return {
20115
+ missingTrackedFiles,
20116
+ untrackedFiles: filesInDirectory({
20117
+ dir,
20118
+ projectRoot,
20119
+ fs
20120
+ }).filter(f => !trackedFiles.has(f))
20121
+ };
20122
+ }
20123
+
20124
+ /**
20125
+ * The LOCAL entries whose key is there but some of what they hold is not: a
20126
+ * stream missing a segment plays up to the gap and then stops. Separate from
20127
+ * `checkGalleryFiles`' "missing" because a fix does not remove these — the
20128
+ * entry still names a video someone uploaded and may have the rest of.
20129
+ */
20130
+ function incompleteGalleryEntries(input) {
20131
+ const exists = file => input.fs.fileExists(path__default.join(input.projectRoot, file));
20132
+ const incomplete = [];
20133
+ for (const key of input.entryKeys) {
20134
+ const entry = galleryEntryOf(key);
20135
+ if (entry.remote || !exists(entry.localPath)) {
20136
+ continue;
20137
+ }
20138
+ const missing = input.filesOfEntry(entry, key).filter(file => file !== entry.localPath && !exists(file));
20139
+ if (missing.length > 0) {
20140
+ incomplete.push({
20141
+ key,
20142
+ missing
20143
+ });
20144
+ }
20145
+ }
20146
+ return incomplete;
20147
+ }
20148
+
20149
+ /** Every file under `dir`, as `/public/…` refs; none for a directory not there. */
20150
+ function filesInDirectory({
20151
+ dir,
20152
+ projectRoot,
20153
+ fs
20154
+ }) {
20155
+ const filesInDir = [];
20156
+ try {
20157
+ const found = fs.readDirectory(path__default.join(projectRoot, dir), undefined, undefined, ["**/*"]);
20158
+ for (const entry of found) {
20159
+ filesInDir.push("/" + path__default.relative(projectRoot, entry).split(path__default.sep).join("/"));
20160
+ }
20161
+ } catch {
20162
+ // directory doesn't exist — no untracked files possible
20163
+ }
20164
+ return filesInDir;
20165
+ }
20166
+
20167
+ /**
20168
+ * The fixes of an `s.videoset()` — the video twin of an image gallery.
20169
+ *
20170
+ * A set is a record keyed by each video's file path (an HLS stream by its
20171
+ * master playlist), so most of this is the gallery fixes again with the key as
20172
+ * the file. Three things are not, and they are why this is a module of its own
20173
+ * rather than another branch in `fixHandlers.ts`:
20174
+ *
20175
+ * - **An entry is several files.** A stream's key is its master playlist, and
20176
+ * the media playlists and segments it names belong to the same entry. They
20177
+ * are tracked by it, uploaded with it, and none of them is an entry itself.
20178
+ * - **The set's directory holds files that are not entries.** A field picked
20179
+ * from the set (`s.video(videosVal)`) keeps its own poster and caption
20180
+ * tracks, and the Studio puts them where the set keeps its videos. A file a
20181
+ * video field names is accounted for, not untracked.
20182
+ * - **Fields elsewhere name an entry by its key.** Uploading an entry renames
20183
+ * its key to the remote ref, and every `s.video(videosVal)` whose `path` was
20184
+ * the old key would then name a video the set does not have. So the upload
20185
+ * rewrites them too (`otherModulePatches`).
20186
+ *
20187
+ * Nothing here imports `fixHandlers.ts` at runtime: that module registers
20188
+ * these handlers, and a cycle would hand it undefined ones.
20189
+ */
20190
+
20191
+ /** The fields of a set entry that are read from the bytes, in the order written. */
20192
+ const VIDEO_METADATA_FIELDS$1 = ["mimeType", "width", "height", "duration"];
20193
+
20194
+ /** What of a `Service` the project-wide walks need. */
20195
+
20196
+ function isRecord$1(value) {
20197
+ return typeof value === "object" && value !== null && !Array.isArray(value);
20198
+ }
20199
+ function isPlaylist(ref) {
20200
+ return ref.split("?")[0].toLowerCase().endsWith(".m3u8");
20201
+ }
20202
+ function readFileOrUndefined(absolutePath) {
20203
+ try {
20204
+ return fs.readFileSync(absolutePath);
20205
+ } catch {
20206
+ return undefined;
20207
+ }
20208
+ }
20209
+
20210
+ /** See `Internal.videosetEntryVideoSchema`: the Studio hashes against it too. */
20211
+ function videosetEntryVideoSchema(record) {
20212
+ return Internal.videosetEntryVideoSchema(record);
20213
+ }
20214
+
20215
+ /** The key of the set entry at `sourcePath`: its last module path segment. */
20216
+ function entryKeyOf(sourcePath) {
20217
+ const [, modulePath] = Internal.splitModuleFilePathAndModulePath(sourcePath);
20218
+ const parts = Internal.splitModulePath(modulePath);
20219
+ return parts[parts.length - 1];
20220
+ }
20221
+
20222
+ /**
20223
+ * The patch path of `sourcePath`. Not `sourceToPatchPath`: a set's keys are
20224
+ * file paths, and their dots do not survive its `split(".")`.
20225
+ */
20226
+ function patchPathOf(sourcePath) {
20227
+ const [, modulePath] = Internal.splitModuleFilePathAndModulePath(sourcePath);
20228
+ return Internal.splitModulePath(modulePath);
20229
+ }
20230
+
20231
+ /**
20232
+ * Every file a set entry holds: its key's file and, for an HLS stream, every
20233
+ * playlist and segment its master names — read from the LOCAL copy, which a
20234
+ * remote entry promoted by `--fix` still has, and which is the only place a
20235
+ * stream's tree can be followed from at all.
20236
+ */
20237
+ function filesOfVideosetEntry(entry, metadata, options) {
20238
+ const fields = isRecord$1(metadata) ? metadata : {};
20239
+ const mimeType = typeof fields.mimeType === "string" ? fields.mimeType : undefined;
20240
+ // The entry's poster and captions are its defaults' files: the set holds
20241
+ // them as it holds the video, so they are tracked by the entry — a remote
20242
+ // one by the local path it was uploaded from, as the key is.
20243
+ return filesOfVideo({
20244
+ path: entry.localPath,
20245
+ mimeType,
20246
+ poster: fields.poster,
20247
+ captions: fields.captions
20248
+ }, options).map(ref => galleryEntryOf(ref).localPath);
20249
+ }
20250
+
20251
+ /**
20252
+ * An entry with every file it names that `moved` has a new ref for pointed
20253
+ * at that ref: the poster and the captions, which a remote set keeps on the
20254
+ * content host with the video.
20255
+ */
20256
+ function withMovedFiles(entry, moved) {
20257
+ const movedPath = file => isRecord$1(file) && typeof file.path === "string" && moved.has(file.path) ? {
20258
+ ...file,
20259
+ path: moved.get(file.path)
20260
+ } : file;
20261
+ return {
20262
+ ...entry,
20263
+ ...(entry.poster !== undefined ? {
20264
+ poster: movedPath(entry.poster)
20265
+ } : {}),
20266
+ ...(Array.isArray(entry.captions) ? {
20267
+ captions: entry.captions.map(movedPath)
20268
+ } : {})
20269
+ };
20270
+ }
20271
+
20272
+ /** The entry's poster and caption files that are still local. */
20273
+ function localFilesOfEntry(entry) {
20274
+ const files = [];
20275
+ if (isRecord$1(entry.poster) && typeof entry.poster.path === "string") {
20276
+ files.push({
20277
+ path: entry.poster.path,
20278
+ role: "poster"
20279
+ });
20280
+ }
20281
+ if (Array.isArray(entry.captions)) {
20282
+ for (const track of entry.captions) {
20283
+ if (isRecord$1(track) && typeof track.path === "string") {
20284
+ files.push({
20285
+ path: track.path,
20286
+ role: "caption"
20287
+ });
20288
+ }
20289
+ }
20290
+ }
20291
+ return files.filter(file => !Internal.isRemoteMediaPath(file.path));
20292
+ }
20293
+
20294
+ /**
20295
+ * The untracked files of a set's directory, sorted into the ones `--fix` can
20296
+ * make entries of and the ones a person has to decide about.
20297
+ *
20298
+ * - `videos`: an untracked stream (keyed by its master playlist — the media
20299
+ * playlists and segments it names are part of it and listed nowhere), and a
20300
+ * progressive video the set accepts.
20301
+ * - `others`: everything else — a poster or caption no video field names, a
20302
+ * media playlist without a master, a video of a type the set does not
20303
+ * accept. `--fix` does not add these: none of them is a video the set could
20304
+ * hold, and deleting someone's file is not a fix.
20305
+ */
20306
+ function classifyUntrackedVideosetFiles({
20307
+ untracked,
20308
+ accept,
20309
+ projectRoot,
20310
+ readFile = readFileOrUndefined
20311
+ }) {
20312
+ const masters = untracked.filter(file => {
20313
+ var _readFile;
20314
+ if (!isPlaylist(file)) {
20315
+ return false;
20316
+ }
20317
+ const text = (_readFile = readFile(path__default.join(projectRoot, file))) === null || _readFile === void 0 ? void 0 : _readFile.toString("utf-8");
20318
+ return text !== undefined && isHlsMasterPlaylist(text);
20319
+ });
20320
+ const partOfAStream = new Set();
20321
+ for (const master of masters) {
20322
+ for (const file of filesOfVideo({
20323
+ path: master
20324
+ }, {
20325
+ projectRoot,
20326
+ readFile
20327
+ })) {
20328
+ if (file !== master) {
20329
+ partOfAStream.add(file);
20330
+ }
20331
+ }
20332
+ }
20333
+ const videos = [];
20334
+ const others = [];
20335
+ for (const file of untracked) {
20336
+ if (partOfAStream.has(file)) {
20337
+ continue;
20338
+ }
20339
+ if (masters.includes(file)) {
20340
+ videos.push(file);
20341
+ continue;
20342
+ }
20343
+ const mimeType = Internal.filenameToMimeType(file);
20344
+ if (mimeType !== undefined && mimeType.startsWith("video/") && Internal.mimeTypeMatchesAccept(mimeType, accept)) {
20345
+ videos.push(file);
20346
+ } else {
20347
+ others.push(file);
20348
+ }
20349
+ }
20350
+ return {
20351
+ videos,
20352
+ others
20353
+ };
20354
+ }
20355
+
20356
+ /** Whether a serialized schema has a video field anywhere in it. */
20357
+ function hasVideoField(schema) {
20358
+ if (Array.isArray(schema)) {
20359
+ return schema.some(hasVideoField);
20360
+ }
20361
+ if (!isRecord$1(schema)) {
20362
+ return false;
20363
+ }
20364
+ if (schema.type === "video") {
20365
+ return true;
20366
+ }
20367
+ return Object.values(schema).some(hasVideoField);
20368
+ }
20369
+ /**
20370
+ * Every video field in the project, with its value.
20371
+ *
20372
+ * Validated reads for the modules that have one, because only those come back
20373
+ * with their `.jsonValues()` entries loaded — an unvalidated read hands back
20374
+ * each entry as a marker, and a field inside one would be invisible. Modules
20375
+ * without a video are read once, unvalidated, to find that out.
20376
+ */
20377
+ async function videoFieldsOf(service) {
20378
+ const found = [];
20379
+ for (const moduleFilePath of service.getModuleFilePaths()) {
20380
+ const shallow = await service.get(moduleFilePath, "", {
20381
+ validate: false
20382
+ });
20383
+ if (!hasVideoField(shallow.schema)) {
20384
+ continue;
20385
+ }
20386
+ const loaded = await service.get(moduleFilePath, "", {
20387
+ validate: true
20388
+ });
20389
+ if (loaded.source === undefined || !loaded.schema) {
20390
+ continue;
20391
+ }
20392
+ traverseSchemaSource(loaded.source, loaded.schema, moduleFilePath, ({
20393
+ source,
20394
+ schema,
20395
+ path: sourcePath
20396
+ }) => {
20397
+ if (schema.type === "video") {
20398
+ found.push({
20399
+ moduleFilePath,
20400
+ sourcePath,
20401
+ source,
20402
+ schema
20403
+ });
20404
+ }
20405
+ });
20406
+ }
20407
+ return found;
20408
+ }
20409
+
20410
+ /**
20411
+ * The files video fields name — a video of its own, and the poster and
20412
+ * captions of every field — as `/public/…` refs, a remote one by the local
20413
+ * path it was uploaded from.
20414
+ */
20415
+ async function filesNamedByVideoFields(service, options) {
20416
+ const files = new Set();
20417
+ for (const field of await videoFieldsOf(service)) {
20418
+ for (const ref of filesOfVideo(field.source, options)) {
20419
+ // A remote ref by the path it encodes: `--fix` uploads a poster and
20420
+ // leaves the file where it was, exactly as it does a set's entry, and
20421
+ // that file is the field's — not something the set forgot.
20422
+ files.add(galleryEntryOf(ref).localPath);
20423
+ }
20424
+ }
20425
+ return files;
20426
+ }
20427
+
20428
+ /**
20429
+ * The patches that point every `s.video(set)` field at a set entry's new key.
20430
+ *
20431
+ * One `add` on each field's `path`, so the description, poster, times and
20432
+ * captions beside it are never rewritten. A field of another set, or of no
20433
+ * set, is left alone even when its path is the same string: it names its own
20434
+ * file.
20435
+ */
20436
+ async function videosetReferencePatches(service, setModuleFilePath, renamed) {
20437
+ const byModule = new Map();
20438
+ for (const field of await videoFieldsOf(service)) {
20439
+ if (field.schema.referencedModule !== setModuleFilePath) {
20440
+ continue;
20441
+ }
20442
+ const value = field.source;
20443
+ const current = isRecord$1(value) ? value.path : undefined;
20444
+ if (typeof current !== "string" || !(current in renamed)) {
20445
+ continue;
20446
+ }
20447
+ const patch = byModule.get(field.moduleFilePath) ?? [];
20448
+ patch.push({
20449
+ op: "add",
20450
+ path: patchPathOf(field.sourcePath).concat("path"),
20451
+ value: renamed[current]
20452
+ });
20453
+ byModule.set(field.moduleFilePath, patch);
20454
+ }
20455
+ return [...byModule].map(([moduleFilePath, patch]) => ({
20456
+ moduleFilePath,
20457
+ patch
20458
+ }));
20459
+ }
20460
+
20461
+ /** The record at `sourcePath` and its entries, or why it could not be read. */
20462
+ function resolveVideoset(module, sourcePath) {
20463
+ var _resolved$schema;
20464
+ if (module.source === undefined || !module.schema) {
20465
+ return {
20466
+ success: false,
20467
+ errorMessage: `Could not resolve source or schema for ${sourcePath}`
20468
+ };
20469
+ }
20470
+ const [, modulePath] = Internal.splitModuleFilePathAndModulePath(sourcePath);
20471
+ const resolved = Internal.resolvePath(modulePath, module.source, module.schema);
20472
+ if (((_resolved$schema = resolved.schema) === null || _resolved$schema === void 0 ? void 0 : _resolved$schema.type) !== "record" || resolved.schema.mediaType !== "videos") {
20473
+ var _resolved$schema2;
20474
+ return {
20475
+ success: false,
20476
+ errorMessage: `Expected a video set at ${sourcePath}, got ${((_resolved$schema2 = resolved.schema) === null || _resolved$schema2 === void 0 ? void 0 : _resolved$schema2.type) ?? "nothing"}`
20477
+ };
20478
+ }
20479
+ return {
20480
+ success: true,
20481
+ record: resolved.schema,
20482
+ entries: isRecord$1(resolved.source) ? resolved.source : {}
20483
+ };
20484
+ }
20485
+
20486
+ /**
20487
+ * `videos:add-metadata`: the entry's KEY is its file, and it must be on disk
20488
+ * (or on Val Remote, read over HTTP) and a kind Val can read the size and
20489
+ * length of here — the same preconditions as `video:add-metadata`, asked of
20490
+ * the key instead of `path`.
20491
+ */
20492
+ async function handleVideosetMetadata(ctx) {
20493
+ const key = entryKeyOf(ctx.sourcePath);
20494
+ if (key === undefined) {
20495
+ return {
20496
+ success: false,
20497
+ errorMessage: `Expected a video set entry at ${ctx.sourcePath}`
20498
+ };
20499
+ }
20500
+ const absolute = path__default.join(ctx.projectRoot, key);
20501
+ if (!galleryEntryOf(key).remote && !ctx.fs.fileExists(absolute)) {
17922
20502
  return {
17923
- localPath: key,
17924
- remote: true
20503
+ success: false,
20504
+ errorMessage: `File ${absolute} does not exist`
20505
+ };
20506
+ }
20507
+ const entry = ctx.validationError.value;
20508
+ const missing = ["width", "height", "duration"].filter(field => !isRecord$1(entry) || entry[field] === undefined);
20509
+ if (missing.length > 0 && !canReadVideoMetadata(key)) {
20510
+ return {
20511
+ success: false,
20512
+ errorMessage: unreadableVideoMetadataMessage(key, missing)
17925
20513
  };
17926
20514
  }
17927
20515
  return {
17928
- localPath: key,
17929
- remote: false
20516
+ success: true,
20517
+ shouldApplyPatch: true
17930
20518
  };
17931
20519
  }
17932
20520
 
17933
20521
  /**
17934
- * The media path a validation error is about, if it is about media at all.
17935
- *
17936
- * There is no schema in hand here — a `ValidationError` carries only the value
17937
- * it flagged — so the shape is all there is to go on.
20522
+ * `videos:check-remote`: a key that is wrong as a key — a remote URL in a set
20523
+ * that is not `.remote()`, one that does not parse, one outside the set's
20524
+ * directory. There is nothing to look up and nothing to move, so the error is
20525
+ * reported as it is, for a person: only they know which of the set's options
20526
+ * or the key is the mistake.
17938
20527
  */
17939
- function getValidationErrorFileRef(validationError) {
17940
- const maybePath = validationError.value && typeof validationError.value === "object" && "path" in validationError.value && typeof validationError.value.path === "string" ? validationError.value.path : undefined;
17941
- if (!maybePath) {
17942
- return null;
17943
- }
17944
- return maybePath;
20528
+ async function handleVideosetCheckRemote(ctx) {
20529
+ return {
20530
+ success: false,
20531
+ errorMessage: ctx.validationError.message
20532
+ };
17945
20533
  }
17946
20534
 
17947
- const textEncoder$1 = new TextEncoder();
17948
- async function checkRemoteRef(remoteHost, ref, projectRoot, schema, metadata) {
17949
- const remoteRefDataRes = Internal.remote.splitRemoteRef(ref);
17950
- if (remoteRefDataRes.status === "error") {
17951
- return remoteRefDataRes;
20535
+ /**
20536
+ * `videos:upload-remote`: an entry of a `.remote()` set still keyed by a local
20537
+ * path. Every file it holds goes up — a stream bottom-up, as the Studio places
20538
+ * one — and `createFixPatch` renames the key to the ref, the same way
20539
+ * `images:upload-remote` does. The fields that name the entry by its old key
20540
+ * are rewritten too: without that they name a video the set no longer has.
20541
+ *
20542
+ * The entry's poster and captions — its defaults' files — go up with it, and
20543
+ * are what is left to do for an entry whose key is already remote: the key
20544
+ * stays, and the entry is written back with their refs.
20545
+ */
20546
+ async function handleVideosetUploadRemote(ctx) {
20547
+ if (!ctx.fix) {
20548
+ return {
20549
+ success: false,
20550
+ // No sourcePath in the message: the reported location already points at it.
20551
+ errorMessage: `Video needs to be uploaded to Val Remote (use --fix to upload)`
20552
+ };
17952
20553
  }
17953
- const fileHash = remoteRefDataRes.fileHash;
17954
- if (!fileHash) {
20554
+ const key = ctx.validationError.value;
20555
+ if (typeof key !== "string") {
17955
20556
  return {
17956
- status: "error",
17957
- error: `File hash is missing in remote ref: ${ref}`
20557
+ success: false,
20558
+ errorMessage: `Expected a local file path for the video set entry at ${ctx.sourcePath}`
17958
20559
  };
17959
20560
  }
17960
- const relativeFilePath = remoteRefDataRes.filePath;
17961
- if (!relativeFilePath) {
20561
+ if (ctx.remoteFiles[ctx.sourcePath]) {
17962
20562
  return {
17963
- status: "error",
17964
- error: `File path is missing in remote ref: ${ref}`
20563
+ success: true,
20564
+ shouldApplyPatch: true,
20565
+ events: [{
20566
+ type: "remote-already-uploaded",
20567
+ filePath: key
20568
+ }]
17965
20569
  };
17966
20570
  }
17967
- if (!relativeFilePath.startsWith("public/")) {
20571
+ const set = resolveVideoset(ctx.valModule, Internal.parentOfSourcePath(ctx.sourcePath));
20572
+ if (!set.success) {
20573
+ return set;
20574
+ }
20575
+ const entry = set.entries[key];
20576
+ if (!isRecord$1(entry)) {
17968
20577
  return {
17969
- status: "error",
17970
- error: `File path must be within the public/ directory (e.g. public/path/to/file.txt). Got: ${relativeFilePath}`
20578
+ success: false,
20579
+ errorMessage: `The video set has no entry '${key}' at ${ctx.sourcePath}`
17971
20580
  };
17972
20581
  }
17973
- const coreVersion = Internal.VERSION.core || "unknown";
17974
- const fileExt = getFileExt(relativeFilePath);
17975
- const currentValidationHash = Internal.remote.getValidationHash(coreVersion, schema, fileExt, metadata,
17976
- // TODO: validate
17977
- fileHash, textEncoder$1);
17978
- const validationHashFromRemoteRefValues = Internal.remote.getValidationHash(remoteRefDataRes.version, schema, getFileExt(remoteRefDataRes.filePath), metadata,
17979
- // TODO: validate
17980
- fileHash, textEncoder$1);
17981
- if (
17982
- // Current validation hash is the same as the remote validation hash
17983
- // We assume the uploaded file exists and is correct
17984
- currentValidationHash === remoteRefDataRes.validationHash &&
17985
- // This can happen if the version or fileExt has been tampered with
17986
- // (or if the way it is computed has changed)
17987
- validationHashFromRemoteRefValues === remoteRefDataRes.validationHash) {
20582
+ // The key is local (the entry goes up whole), or the key is already on the
20583
+ // content host and only the entry's poster or captions are still here.
20584
+ const keyIsLocal = !Internal.isRemoteMediaPath(key);
20585
+ const entryFiles = localFilesOfEntry(entry);
20586
+ const missing = firstMissingVideoFile(ctx, [...(keyIsLocal ? [{
20587
+ path: key,
20588
+ ...(typeof entry.mimeType === "string" ? {
20589
+ mimeType: entry.mimeType
20590
+ } : {})
20591
+ }] : []), ...entryFiles.map(file => ({
20592
+ path: file.path
20593
+ }))]);
20594
+ if (missing !== undefined) {
17988
20595
  return {
17989
- status: "success"
20596
+ success: false,
20597
+ errorMessage: `File ${missing} does not exist`
17990
20598
  };
17991
20599
  }
17992
- // Validation hash does not match, so we need to re-validate the remote content
17993
- const fileBufferRes = await getFileBufferFromRemote(ref, fileExt, remoteRefDataRes.fileHash, projectRoot);
17994
-
17995
- // We could not download the remote file for some reason (for example, the file hash is wrong)
17996
- if (fileBufferRes.status === "error") {
17997
- return fileBufferRes;
20600
+ const opened = await openRemoteUploadSession(ctx);
20601
+ if (!opened.success) {
20602
+ return opened.result;
17998
20603
  }
17999
-
18000
- // At this point we have the file buffer and we know the correct file hash
18001
- // We must create a new ref since something has changed
18002
-
18003
- let currentMetadata;
20604
+ const {
20605
+ session
20606
+ } = opened;
20607
+ const uploader = createVideoUploader(ctx, session, videosetEntryVideoSchema(set.record), (localRef, role) => metadataOf(localRef, role, entry));
20608
+ let ref;
18004
20609
  try {
18005
- if (schema.type === "image") {
18006
- currentMetadata = await extractImageMetadata(remoteRefDataRes.filePath, fileBufferRes.fileBuffer);
18007
- } else if (schema.type === "file") {
18008
- currentMetadata = await extractFileMetadata(remoteRefDataRes.filePath, fileBufferRes.fileBuffer);
18009
- } else {
18010
- const exhaustiveCheck = schema;
18011
- return {
18012
- status: "error",
18013
- error: `Unknown schema type: ${JSON.stringify(exhaustiveCheck)}`
18014
- };
20610
+ ref = keyIsLocal ? await uploader.put(key, "video") : key;
20611
+ for (const file of entryFiles) {
20612
+ await uploader.put(file.path, file.role);
18015
20613
  }
18016
20614
  } catch (err) {
18017
20615
  return {
18018
- status: "error",
18019
- error: `Failed to extract metadata from remote file: ${err instanceof Error ? err.message : "Unknown error"}. Cached file: ${fileBufferRes.cachedFilePath}`
20616
+ success: false,
20617
+ errorMessage: err instanceof Error ? err.message : String(err)
18020
20618
  };
18021
20619
  }
18022
- const updatedMetadata = {
18023
- ...metadata,
18024
- ...currentMetadata
20620
+ ctx.remoteFiles[ctx.sourcePath] = {
20621
+ ref,
20622
+ metadata: withMovedFiles(entry, uploader.moved),
20623
+ refs: Object.fromEntries(uploader.moved)
18025
20624
  };
18026
- const nextValidationHash = Internal.remote.getValidationHash(coreVersion, schema, fileExt, updatedMetadata, fileBufferRes.fileHash, textEncoder$1);
18027
- if (!updatedMetadata.mimeType) {
20625
+ const otherModulePatches = ref === key ? [] : await videosetReferencePatches(ctx.service, ctx.moduleFilePath, {
20626
+ [key]: ref
20627
+ });
20628
+ return {
20629
+ success: true,
20630
+ shouldApplyPatch: true,
20631
+ publicProjectId: session.publicProjectId,
20632
+ remoteFileBuckets: session.remoteFileBuckets,
20633
+ remoteFilesCounter: session.remoteFilesCounter,
20634
+ events: uploader.events,
20635
+ ...(otherModulePatches.length > 0 ? {
20636
+ otherModulePatches
20637
+ } : {})
20638
+ };
20639
+ }
20640
+
20641
+ /**
20642
+ * `videos:check-all-files`: the set's entries against its directory.
20643
+ *
20644
+ * What only this handler can answer is which untracked files are accounted
20645
+ * for ELSEWHERE — a poster or caption a video field names — because that needs
20646
+ * every module in the project. Those are fine. An untracked file that is not
20647
+ * a video and that no field names is for a person to look at, and is reported
20648
+ * here. Everything `--fix` can do something about — an entry whose file has
20649
+ * gone, a video in the directory the set does not list — is left to
20650
+ * `createFixPatch` (see {@link videosetCheckAllFilesPatch}), which reports it
20651
+ * per entry, or repairs it.
20652
+ */
20653
+ async function handleVideosetCheckAllFiles(ctx) {
20654
+ const value = ctx.validationError.value;
20655
+ const dir = isRecord$1(value) ? value.dir : undefined;
20656
+ if (typeof dir !== "string") {
18028
20657
  return {
18029
- status: "error",
18030
- error: `MIME type is missing in metadata: ${JSON.stringify(updatedMetadata)}`
20658
+ success: false,
20659
+ errorMessage: `Unexpected value in check-all-files for ${ctx.sourcePath}`
18031
20660
  };
18032
20661
  }
18033
- const newFileExt = Internal.mimeTypeToFileExt(updatedMetadata.mimeType);
18034
- const newFilePath = relativeFilePath.slice(0, -fileExt.length) + newFileExt;
18035
- return {
18036
- status: "fix-required",
18037
- metadata: updatedMetadata,
18038
- ref: Internal.remote.createRemoteRef(remoteHost, {
18039
- publicProjectId: remoteRefDataRes.projectId,
18040
- coreVersion,
18041
- bucket: remoteRefDataRes.bucket,
18042
- validationHash: nextValidationHash,
18043
- fileHash: fileBufferRes.fileHash,
18044
- filePath: newFilePath
20662
+ const set = resolveVideoset(ctx.valModule, ctx.sourcePath);
20663
+ if (!set.success) {
20664
+ return set;
20665
+ }
20666
+ const readFile = absolute => ctx.fs.readBuffer(absolute);
20667
+ const incompleteEntries = incompleteGalleryEntries({
20668
+ entryKeys: Object.keys(set.entries),
20669
+ projectRoot: ctx.projectRoot,
20670
+ fs: ctx.fs,
20671
+ filesOfEntry: (entry, key) => filesOfVideosetEntry(entry, set.entries[key], {
20672
+ projectRoot: ctx.projectRoot,
20673
+ readFile
20674
+ })
20675
+ });
20676
+ const {
20677
+ untrackedFiles
20678
+ } = checkGalleryFiles({
20679
+ entryKeys: Object.keys(set.entries),
20680
+ dir,
20681
+ projectRoot: ctx.projectRoot,
20682
+ fs: ctx.fs,
20683
+ filesOfEntry: (entry, key) => filesOfVideosetEntry(entry, set.entries[key], {
20684
+ projectRoot: ctx.projectRoot,
20685
+ readFile
18045
20686
  })
20687
+ });
20688
+ if (incompleteEntries.length > 0) {
20689
+ return {
20690
+ success: false,
20691
+ errorMessage: incompleteMessage(incompleteEntries)
20692
+ };
20693
+ }
20694
+ if (untrackedFiles.length === 0) {
20695
+ return {
20696
+ success: true,
20697
+ shouldApplyPatch: true
20698
+ };
20699
+ }
20700
+ const named = await filesNamedByVideoFields(ctx.service, {
20701
+ projectRoot: ctx.projectRoot,
20702
+ readFile
20703
+ });
20704
+ const {
20705
+ others
20706
+ } = classifyUntrackedVideosetFiles({
20707
+ untracked: untrackedFiles.filter(file => !named.has(file)),
20708
+ accept: set.record.accept ?? "video/*",
20709
+ projectRoot: ctx.projectRoot,
20710
+ readFile
20711
+ });
20712
+ if (others.length > 0) {
20713
+ return {
20714
+ success: false,
20715
+ errorMessage: `Video set in ${ctx.moduleFilePath} has files in '${dir}' that are not in the set, and that no video field uses: ${others.join(", ")}. They are not videos the set accepts, so --fix will not add them: move them out of the directory or remove them.`
20716
+ };
20717
+ }
20718
+ return {
20719
+ success: true,
20720
+ shouldApplyPatch: true
18046
20721
  };
18047
20722
  }
18048
- function getCachedRemoteFileDir(projectRoot) {
18049
- // store in projectRoot/.val/remote-file-cache
18050
- const remoteFileCacheDir = path__default.join(projectRoot, ".val", "remote-file-cache");
18051
- return remoteFileCacheDir;
18052
- }
18053
- function getCachedRemoteFilePath(fileExt, currentFileHash, remoteFileCacheDir) {
18054
- const remoteFilePath = path__default.join(remoteFileCacheDir, currentFileHash + "." + fileExt);
18055
- return remoteFilePath;
18056
- }
18057
- async function getFileBufferFromRemote(ref, fileExt, currentFileHash, projectRoot) {
18058
- const remoteFileCacheDir = getCachedRemoteFileDir(projectRoot);
18059
- const remoteFilePath = getCachedRemoteFilePath(fileExt, currentFileHash, remoteFileCacheDir);
18060
- try {
18061
- const fileBuffer = await fs.promises.readFile(remoteFilePath);
18062
- const computedFileHash = Internal.remote.getFileHash(fileBuffer);
18063
- if (computedFileHash !== currentFileHash) {
18064
- await fs.promises.unlink(remoteFilePath);
18065
- throw Error(`Cached file hash does not match the expected hash: ${computedFileHash} !== ${currentFileHash}`);
20723
+
20724
+ /**
20725
+ * The `createFixPatch` half of `videos:check-all-files`: drop the entries
20726
+ * whose file has gone, and add the videos in the directory that the set does
20727
+ * not list — with what is read from their bytes, or not at all.
20728
+ *
20729
+ * What is stored for an entry that IS on disk is not compared against its
20730
+ * bytes, unlike an image gallery's. The Studio reads a video's size and length
20731
+ * in the browser from the file as it was picked, and that is not what a header
20732
+ * parse of what is on disk says: a stream's largest rendition is not the
20733
+ * upload's size whenever the upload was larger than the largest rendition, and
20734
+ * two readers round a duration differently. Correcting one from the other
20735
+ * would rewrite every streamed video in the project, every run. A missing
20736
+ * value is `videos:add-metadata`'s, and is reported on the entry.
20737
+ */
20738
+ async function videosetCheckAllFilesPatch({
20739
+ projectRoot,
20740
+ apply,
20741
+ sourcePath,
20742
+ validationError,
20743
+ moduleSource,
20744
+ moduleSchema
20745
+ }) {
20746
+ const patch = [];
20747
+ const remainingErrors = [];
20748
+ const fail = message => ({
20749
+ patch,
20750
+ remainingErrors: [{
20751
+ ...validationError,
20752
+ message,
20753
+ fixes: undefined
20754
+ }]
20755
+ });
20756
+ const value = validationError.value;
20757
+ const dir = isRecord$1(value) ? value.dir : undefined;
20758
+ if (typeof dir !== "string") {
20759
+ return fail(`Unexpected value in check-all-files for ${sourcePath}`);
20760
+ }
20761
+ if (moduleSource === undefined || moduleSchema === undefined) {
20762
+ return fail("Unexpected error while checking a video set (no module source or schema)");
20763
+ }
20764
+ const set = resolveVideoset({
20765
+ source: moduleSource,
20766
+ schema: moduleSchema
20767
+ }, sourcePath);
20768
+ if (!set.success) {
20769
+ return fail(set.errorMessage);
20770
+ }
20771
+ const recordPath = patchPathOf(sourcePath);
20772
+ const incompleteEntries = incompleteGalleryEntries({
20773
+ entryKeys: Object.keys(set.entries),
20774
+ projectRoot,
20775
+ fs: ts.sys,
20776
+ filesOfEntry: (entry, key) => filesOfVideosetEntry(entry, set.entries[key], {
20777
+ projectRoot
20778
+ })
20779
+ });
20780
+ const {
20781
+ missingTrackedFiles,
20782
+ untrackedFiles
20783
+ } = checkGalleryFiles({
20784
+ entryKeys: Object.keys(set.entries),
20785
+ dir,
20786
+ projectRoot,
20787
+ // The host `createDefaultValFSHost` gives the handlers, and so the same
20788
+ // listing the handler half of this check saw.
20789
+ fs: ts.sys,
20790
+ filesOfEntry: (entry, key) => filesOfVideosetEntry(entry, set.entries[key], {
20791
+ projectRoot
20792
+ })
20793
+ });
20794
+ if (incompleteEntries.length > 0) {
20795
+ remainingErrors.push({
20796
+ ...validationError,
20797
+ message: incompleteMessage(incompleteEntries),
20798
+ fixes: undefined
20799
+ });
20800
+ }
20801
+ for (const missing of missingTrackedFiles) {
20802
+ if (apply) {
20803
+ const removePath = recordPath.concat(missing);
20804
+ if (isNotRoot(removePath)) {
20805
+ patch.push({
20806
+ op: "remove",
20807
+ path: removePath
20808
+ });
20809
+ }
20810
+ } else {
20811
+ remainingErrors.push({
20812
+ ...validationError,
20813
+ message: `Video '${missing}' is in the set, but its file does not exist. Use --fix to remove it from the set.`,
20814
+ sourcePath: Internal.createValPathOfItem(sourcePath, missing),
20815
+ keyError: true
20816
+ });
18066
20817
  }
18067
- } catch {
20818
+ }
20819
+ const {
20820
+ videos
20821
+ } = classifyUntrackedVideosetFiles({
20822
+ untracked: untrackedFiles,
20823
+ accept: set.record.accept ?? "video/*",
20824
+ projectRoot
20825
+ });
20826
+ for (const file of videos) {
20827
+ let metadata;
18068
20828
  try {
18069
- await fs.promises.mkdir(remoteFileCacheDir, {
18070
- recursive: true
20829
+ metadata = await extractVideoMetadataFromFile(path__default.join(projectRoot, file));
20830
+ } catch (err) {
20831
+ remainingErrors.push({
20832
+ ...validationError,
20833
+ message: `Video '${file}' is in '${dir}' but not in the set, and its metadata could not be read: ${err instanceof Error ? err.message : String(err)}`,
20834
+ fixes: undefined
20835
+ });
20836
+ continue;
20837
+ }
20838
+ const unreadable = VIDEO_METADATA_FIELDS$1.filter(field => metadata[field] === undefined);
20839
+ if (unreadable.length > 0) {
20840
+ // All or nothing, as for `video:add-metadata`: an entry with a mime type
20841
+ // and no size is no closer to valid, and reads as one someone finished.
20842
+ remainingErrors.push({
20843
+ ...validationError,
20844
+ message: `Video '${file}' is in '${dir}' but not in the set. ${unreadableVideoMetadataMessage(file, unreadable)}`,
20845
+ fixes: undefined
20846
+ });
20847
+ continue;
20848
+ }
20849
+ if (!apply) {
20850
+ remainingErrors.push({
20851
+ ...validationError,
20852
+ message: `Video '${file}' is in '${dir}' but not in the set. Use --fix to add it.`
20853
+ });
20854
+ continue;
20855
+ }
20856
+ const entry = {};
20857
+ for (const field of VIDEO_METADATA_FIELDS$1) {
20858
+ const read = metadata[field];
20859
+ if (read !== undefined) {
20860
+ entry[field] = read;
20861
+ }
20862
+ }
20863
+ // What an upload writes when nobody has described the video yet.
20864
+ entry.alt = null;
20865
+ const addPath = recordPath.concat(file);
20866
+ if (isNotRoot(addPath)) {
20867
+ patch.push({
20868
+ op: "add",
20869
+ path: addPath,
20870
+ value: entry
20871
+ });
20872
+ }
20873
+ }
20874
+ return {
20875
+ patch,
20876
+ remainingErrors
20877
+ };
20878
+ }
20879
+
20880
+ /**
20881
+ * The `createFixPatch` half of `videos:add-metadata`: read what is missing
20882
+ * from the file at the entry's KEY, and write only that, one op per field —
20883
+ * `alt` and anything already there are someone's, and stay.
20884
+ */
20885
+ async function videosetAddMetadataPatch({
20886
+ projectRoot,
20887
+ sourcePath,
20888
+ validationError,
20889
+ moduleSource,
20890
+ moduleSchema
20891
+ }) {
20892
+ const fail = message => ({
20893
+ patch: [],
20894
+ remainingErrors: [{
20895
+ ...validationError,
20896
+ message,
20897
+ fixes: undefined
20898
+ }]
20899
+ });
20900
+ const key = entryKeyOf(sourcePath);
20901
+ if (key === undefined) {
20902
+ return fail(`Expected a video set entry at ${sourcePath}`);
20903
+ }
20904
+ let current = validationError.value;
20905
+ if (moduleSource !== undefined && moduleSchema !== undefined) {
20906
+ const parent = resolveVideoset({
20907
+ source: moduleSource,
20908
+ schema: moduleSchema
20909
+ }, Internal.parentOfSourcePath(sourcePath));
20910
+ if (!parent.success) {
20911
+ return fail(`Could not add video metadata: ${parent.errorMessage}`);
20912
+ }
20913
+ current = parent.entries[key];
20914
+ }
20915
+ if (!isRecord$1(current)) {
20916
+ return fail("Video set entry is not an object!");
20917
+ }
20918
+ let metadata;
20919
+ try {
20920
+ metadata = galleryEntryOf(key).remote ? await extractVideoMetadataFromUrl(key, nameForTypeOf(key)) : await extractVideoMetadataFromFile(path__default.join(projectRoot, key));
20921
+ } catch (err) {
20922
+ return fail(`Failed to read video metadata from ${key}: ${err instanceof Error ? err.message : String(err)}`);
20923
+ }
20924
+ const entry = current;
20925
+ const missing = VIDEO_METADATA_FIELDS$1.filter(field => entry[field] === undefined);
20926
+ const unreadable = missing.filter(field => metadata[field] === undefined);
20927
+ if (unreadable.length > 0) {
20928
+ return fail(unreadableVideoMetadataMessage(key, unreadable));
20929
+ }
20930
+ const entryPath = patchPathOf(sourcePath);
20931
+ const patch = [];
20932
+ for (const field of missing) {
20933
+ const read = metadata[field];
20934
+ if (read !== undefined) {
20935
+ patch.push({
20936
+ op: "add",
20937
+ path: entryPath.concat(field),
20938
+ value: read
18071
20939
  });
18072
- await downloadFileFromRemote(ref, remoteFilePath);
18073
- } catch (err) {
18074
- try {
18075
- // try to delete in case of partial download
18076
- await fs.promises.unlink(remoteFilePath);
18077
- } catch {
18078
- //
18079
- }
18080
- return {
18081
- status: "error",
18082
- error: `Failed to download remote file: ${err instanceof Error ? err.message : "Unknown error"}`
18083
- };
18084
20940
  }
18085
20941
  }
18086
- const fileBuffer = await fs.promises.readFile(remoteFilePath);
18087
- const computedFileHash = Internal.remote.getFileHash(fileBuffer);
18088
20942
  return {
18089
- status: "success",
18090
- fileBuffer,
18091
- fileHash: computedFileHash,
18092
- cachedFilePath: remoteFilePath
20943
+ patch,
20944
+ remainingErrors: []
18093
20945
  };
18094
20946
  }
18095
- async function downloadFileFromRemote(ref, filePath) {
18096
- return new Promise((resolve, reject) => {
18097
- const url = new URL(ref);
18098
- const client = url.protocol === "https:" ? https$1 : http$1;
18099
- const request = client.get(url, response => {
18100
- if (response.statusCode && response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) {
18101
- // Handle redirects
18102
- return downloadFileFromRemote(response.headers.location, filePath).then(resolve).catch(reject);
18103
- }
18104
- if (response.statusCode == 404) {
18105
- return reject(new Error(`${ref}. File not found. The URL is most likely incorrect.`));
18106
- }
18107
- if (response.statusCode !== 200) {
18108
- return reject(new Error(`${ref}. Failed to download file. HTTP Status: ${response.statusCode}`));
18109
- }
18110
- const writeStream = fs.createWriteStream(filePath);
18111
- response.pipe(writeStream);
18112
- writeStream.on("finish", () => resolve({
18113
- status: "success",
18114
- filePath
18115
- }));
18116
- writeStream.on("error", err => reject(new Error(`${ref}. Error writing file: ${err.message}`)));
18117
- });
18118
- request.on("error", err => reject(new Error(`${ref}. Download error: ${err.message}`)));
18119
- request.end();
18120
- });
20947
+
20948
+ /**
20949
+ * What to say about streams whose master is there and some of whose files are
20950
+ * not. Not fixable: the entry still names a video someone uploaded, and only
20951
+ * they have the rest of it.
20952
+ */
20953
+ function incompleteMessage(incomplete) {
20954
+ return incomplete.map(({
20955
+ key,
20956
+ missing
20957
+ }) => `Video '${key}' is missing ${missing.length === 1 ? "a file it names" : `${missing.length} files it names`}: ${missing.join(", ")}. It stops playing where they are. Upload it again, or put the files back.`).join(" ");
18121
20958
  }
18122
20959
 
18123
20960
  // A remaining error may optionally carry a more specific `sourcePath` than the
@@ -18283,6 +21120,86 @@ async function createFixPatch(config, apply, sourcePath, validationError, remote
18283
21120
  value: fileMetadata.mimeType ?? null
18284
21121
  });
18285
21122
  }
21123
+ } else if (fix === "video:add-metadata") {
21124
+ // Only the fields that are MISSING, one op each: a video's `alt`,
21125
+ // `poster`, `captions` and times are authored and sit in the same
21126
+ // object, and a field already there is not re-read (see the comment on
21127
+ // the fix code in core — reading a video is not cheap).
21128
+ const current = currentVideoValue(sourcePath, validationError, moduleSource, moduleSchema);
21129
+ if (current.status === "error") {
21130
+ remainingErrors.push({
21131
+ ...validationError,
21132
+ message: current.message,
21133
+ fixes: undefined
21134
+ });
21135
+ continue;
21136
+ }
21137
+ const fileRef = current.value.path;
21138
+ if (typeof fileRef !== "string") {
21139
+ remainingErrors.push({
21140
+ ...validationError,
21141
+ message: `Cannot read video metadata: the video has no path`,
21142
+ fixes: undefined
21143
+ });
21144
+ continue;
21145
+ }
21146
+ let metadata;
21147
+ try {
21148
+ metadata = await getVideoMetadata(config.projectRoot, fileRef);
21149
+ } catch (err) {
21150
+ remainingErrors.push({
21151
+ ...validationError,
21152
+ message: `Failed to read video metadata from ${fileRef}: ${err instanceof Error ? err.message : String(err)}`,
21153
+ fixes: undefined
21154
+ });
21155
+ continue;
21156
+ }
21157
+ const missing = VIDEO_METADATA_FIELDS.filter(field => current.value[field] === undefined);
21158
+ const unreadable = missing.filter(field => metadata[field] === undefined);
21159
+ if (unreadable.length > 0) {
21160
+ // All or nothing: a video with a mime type but no size is no closer
21161
+ // to valid, and a half-written value reads as one someone finished.
21162
+ remainingErrors.push({
21163
+ ...validationError,
21164
+ message: unreadableVideoMetadataMessage(fileRef, unreadable),
21165
+ fixes: undefined
21166
+ });
21167
+ continue;
21168
+ }
21169
+ const patchPath = sourceToPatchPath(sourcePath);
21170
+ for (const field of missing) {
21171
+ const value = metadata[field];
21172
+ if (value !== undefined) {
21173
+ patch.push({
21174
+ op: "add",
21175
+ path: patchPath.concat(field),
21176
+ value
21177
+ });
21178
+ }
21179
+ }
21180
+ } else if (fix === "videos:add-metadata") {
21181
+ // A set entry's twin of `video:add-metadata`: the file is the entry's
21182
+ // KEY, and only what is missing is written.
21183
+ const fixed = await videosetAddMetadataPatch({
21184
+ projectRoot: config.projectRoot,
21185
+ sourcePath,
21186
+ validationError,
21187
+ moduleSource,
21188
+ moduleSchema
21189
+ });
21190
+ patch.push(...fixed.patch);
21191
+ remainingErrors.push(...fixed.remainingErrors);
21192
+ } else if (fix === "videos:check-all-files") {
21193
+ const fixed = await videosetCheckAllFilesPatch({
21194
+ projectRoot: config.projectRoot,
21195
+ apply,
21196
+ sourcePath,
21197
+ validationError,
21198
+ moduleSource,
21199
+ moduleSchema
21200
+ });
21201
+ patch.push(...fixed.patch);
21202
+ remainingErrors.push(...fixed.remainingErrors);
18286
21203
  } else if (fix === "image:upload-remote" || fix === "file:upload-remote") {
18287
21204
  const remoteFile = remoteFiles[sourcePath];
18288
21205
  let metadata = remoteFile.metadata;
@@ -18312,10 +21229,30 @@ async function createFixPatch(config, apply, sourcePath, validationError, remote
18312
21229
  path: sourceToPatchPath(sourcePath)
18313
21230
  });
18314
21231
  }
18315
- } else if (fix === "images:upload-remote" || fix === "files:upload-remote") {
21232
+ } else if (fix === "video:upload-remote" || fix === "video:download-remote") {
21233
+ var _remoteFiles$sourcePa;
21234
+ // The handler moved the files (`videoRemote.ts`); what is left is to
21235
+ // point each path the value holds at where its file now is. Read from
21236
+ // the module rather than the error, which carries the value as it was
21237
+ // validated.
21238
+ const moved = (_remoteFiles$sourcePa = remoteFiles[sourcePath]) === null || _remoteFiles$sourcePa === void 0 ? void 0 : _remoteFiles$sourcePa.refs;
21239
+ if (!moved) {
21240
+ remainingErrors.push({
21241
+ ...validationError,
21242
+ message: fix === "video:upload-remote" ? "Cannot point the video at Val Remote: its files were not uploaded" : "Cannot point the video at its local files: they were not downloaded",
21243
+ fixes: undefined
21244
+ });
21245
+ continue;
21246
+ }
21247
+ const current = moduleSource !== undefined && moduleSchema !== undefined ? Internal.resolvePath(Internal.splitModuleFilePathAndModulePath(sourcePath)[1], moduleSource, moduleSchema).source : validationError.value;
21248
+ patch.push(...rewriteVideoPathsPatch(sourcePath, current, moved));
21249
+ } else if (fix === "images:upload-remote" || fix === "files:upload-remote" || fix === "videos:upload-remote") {
18316
21250
  // Gallery entry: the record is keyed by the file path, so uploading to
18317
21251
  // remote means renaming the key from the local path to the remote URL
18318
- // (remove the old key, add the new one with the same metadata).
21252
+ // (remove the old key, add the new one with the same metadata). A video
21253
+ // set's entry is renamed to its MASTER playlist's ref for a stream: the
21254
+ // playlists and segments it names went up with it, and are named by the
21255
+ // uploaded master, not by the set.
18319
21256
  const remoteFile = remoteFiles[sourcePath];
18320
21257
  if (!remoteFile) {
18321
21258
  remainingErrors.push({
@@ -18674,6 +21611,52 @@ function getRemoteValueFromValidationError(v) {
18674
21611
  metadata
18675
21612
  };
18676
21613
  }
21614
+
21615
+ /** The fields of a video that are read from its bytes, in the order written. */
21616
+ const VIDEO_METADATA_FIELDS = ["mimeType", "width", "height", "duration"];
21617
+
21618
+ /**
21619
+ * The video a `video:add-metadata` error is about, read from the module at its
21620
+ * path when the module is at hand — the schema there decides that it IS a
21621
+ * video — and from the error's own value otherwise.
21622
+ */
21623
+ function currentVideoValue(sourcePath, validationError, moduleSource, moduleSchema) {
21624
+ if (moduleSource !== undefined && moduleSchema !== undefined) {
21625
+ const [, modulePath] = Internal.splitModuleFilePathAndModulePath(sourcePath);
21626
+ const resolved = Internal.resolvePath(modulePath, moduleSource, moduleSchema);
21627
+ if (resolved.schema.type !== "video") {
21628
+ return {
21629
+ status: "error",
21630
+ message: `Could not add video metadata: schema at ${sourcePath} is '${resolved.schema.type}', not a video`
21631
+ };
21632
+ }
21633
+ const value = mediaValueOf(resolved.source);
21634
+ return value ? {
21635
+ status: "ok",
21636
+ value
21637
+ } : {
21638
+ status: "error",
21639
+ message: "Video is not an object!"
21640
+ };
21641
+ }
21642
+ const value = mediaValueOf(validationError.value);
21643
+ return value ? {
21644
+ status: "ok",
21645
+ value
21646
+ } : {
21647
+ status: "error",
21648
+ message: "Video is not an object!"
21649
+ };
21650
+ }
21651
+ async function getVideoMetadata(projectRoot, fileRef) {
21652
+ // Not read into memory: only the headers are, and a video is mostly not
21653
+ // headers. A remote video's headers are read over HTTP, with Range
21654
+ // requests, so it is not downloaded either.
21655
+ if (Internal.isRemoteMediaPath(fileRef)) {
21656
+ return extractVideoMetadataFromUrl(fileRef, nameForTypeOf(fileRef));
21657
+ }
21658
+ return extractVideoMetadataFromFile(path__default.join(projectRoot, fileRef));
21659
+ }
18677
21660
  async function getImageMetadata(projectRoot, validationError) {
18678
21661
  const fileRef = getValidationErrorFileRef(validationError);
18679
21662
  if (!fileRef) {
@@ -18847,10 +21830,17 @@ function formatOpsError(error, sourceFile) {
18847
21830
  * What stays in the CLI is the driver: the `runValidation` async generator that
18848
21831
  * walks every module, decides what to report, and renders it to a terminal.
18849
21832
  */
18850
- const textEncoder = new TextEncoder();
18851
21833
 
18852
21834
  // Types for handler system
18853
21835
 
21836
+ /**
21837
+ * Where a fix moved a media value's file. `refs` is for a value that names
21838
+ * SEVERAL files — a video's poster, captions and stream — keyed by the path
21839
+ * the value held, so the patch can rewrite each one where it is.
21840
+ */
21841
+
21842
+ /** A patch, and the module it is for. */
21843
+
18854
21844
  // Handler functions
18855
21845
  async function handleFileMetadata(ctx) {
18856
21846
  var _fileSource$source;
@@ -18884,6 +21874,53 @@ async function handleFileMetadata(ctx) {
18884
21874
  };
18885
21875
  }
18886
21876
 
21877
+ /**
21878
+ * `video:add-metadata`: the bytes must be on disk, or on Val Remote (read
21879
+ * over HTTP, headers only — see `remoteVideoMetadata.ts`), and they must be a
21880
+ * kind of file Val can read the size and length of here: mp4/mov boxes,
21881
+ * WebM/Matroska headers and HLS playlists. Anything else is refused with what
21882
+ * to do instead, unless all that is missing is the mime type, which the
21883
+ * extension answers.
21884
+ */
21885
+ async function handleVideoMetadata(ctx) {
21886
+ const exists = isRemoteVideoAt(ctx) ? {
21887
+ success: true,
21888
+ shouldApplyPatch: true
21889
+ } : await handleFileMetadata(ctx);
21890
+ if (!exists.success) {
21891
+ return exists;
21892
+ }
21893
+ const [, modulePath] = Internal.splitModuleFilePathAndModulePath(ctx.sourcePath);
21894
+ if (!ctx.valModule.source || !ctx.valModule.schema) {
21895
+ return exists;
21896
+ }
21897
+ const video = Internal.resolvePath(modulePath, ctx.valModule.source, ctx.valModule.schema).source;
21898
+ if (!isRecord(video) || typeof video.path !== "string") {
21899
+ return exists;
21900
+ }
21901
+ const missing = ["width", "height", "duration"].filter(field => video[field] === undefined);
21902
+ if (missing.length > 0 && !canReadVideoMetadata(video.path)) {
21903
+ return {
21904
+ success: false,
21905
+ errorMessage: unreadableVideoMetadataMessage(video.path, missing)
21906
+ };
21907
+ }
21908
+ return exists;
21909
+ }
21910
+
21911
+ /** Whether the video at the error's path is on Val Remote. */
21912
+ function isRemoteVideoAt(ctx) {
21913
+ if (!ctx.valModule.source || !ctx.valModule.schema) {
21914
+ return false;
21915
+ }
21916
+ const [, modulePath] = Internal.splitModuleFilePathAndModulePath(ctx.sourcePath);
21917
+ const video = Internal.resolvePath(modulePath, ctx.valModule.source, ctx.valModule.schema).source;
21918
+ return isRecord(video) && typeof video.path === "string" && Internal.isRemoteMediaPath(video.path);
21919
+ }
21920
+ function isRecord(value) {
21921
+ return typeof value === "object" && value !== null && !Array.isArray(value);
21922
+ }
21923
+
18887
21924
  // Shared upload core used by both the single-field (handleRemoteFileUpload)
18888
21925
  // and gallery (handleRemoteGalleryFileUpload) handlers. The two differ only in
18889
21926
  // how they derive the local file ref, metadata and serialized image/file
@@ -18896,30 +21933,6 @@ async function uploadRemoteFileCore(ctx, fileRef, metadata, schema) {
18896
21933
  errorMessage: `File ${filePath} does not exist`
18897
21934
  };
18898
21935
  }
18899
- const patFile = getPersonalAccessTokenPath(ctx.projectRoot);
18900
- if (!ctx.fs.fileExists(patFile)) {
18901
- return {
18902
- success: false,
18903
- errorMessage: `File: ${path__default.join(ctx.projectRoot, ctx.file)} has remote images that are not uploaded and you are not logged in.\n\nFix this error by logging in:\n\t"npx val login"\n`
18904
- };
18905
- }
18906
- const patFileContent = ctx.fs.readFile(patFile);
18907
- if (patFileContent === undefined) {
18908
- return {
18909
- success: false,
18910
- errorMessage: `Could not read personal access token file at ${patFile}`
18911
- };
18912
- }
18913
- const parsedPatFile = parsePersonalAccessTokenFile(patFileContent);
18914
- if (!parsedPatFile.success) {
18915
- return {
18916
- success: false,
18917
- errorMessage: `Error parsing personal access token file: ${parsedPatFile.error}. You need to login again.`
18918
- };
18919
- }
18920
- const {
18921
- pat
18922
- } = parsedPatFile.data;
18923
21936
  if (ctx.remoteFiles[ctx.sourcePath]) {
18924
21937
  return {
18925
21938
  success: true,
@@ -18929,49 +21942,13 @@ async function uploadRemoteFileCore(ctx, fileRef, metadata, schema) {
18929
21942
  }]
18930
21943
  };
18931
21944
  }
18932
- const projectName = ctx.project;
18933
- let publicProjectId = ctx.publicProjectId;
18934
- let remoteFileBuckets = ctx.remoteFileBuckets;
18935
- let remoteFilesCounter = ctx.remoteFilesCounter;
18936
- if (!publicProjectId || !remoteFileBuckets) {
18937
- if (!projectName) {
18938
- return {
18939
- success: false,
18940
- errorMessage: "Project name not found. Add project name to val.config or set the VAL_PROJECT environment variable"
18941
- };
18942
- }
18943
- const settingsRes = await ctx.remote.getSettings(projectName, {
18944
- pat
18945
- });
18946
- if (!settingsRes.success) {
18947
- return {
18948
- success: false,
18949
- errorMessage: `Could not get public project id: ${settingsRes.message}.`
18950
- };
18951
- }
18952
- publicProjectId = settingsRes.data.publicProjectId;
18953
- remoteFileBuckets = settingsRes.data.remoteFileBuckets.map(b => b.bucket);
18954
- }
18955
- if (!publicProjectId) {
18956
- return {
18957
- success: false,
18958
- errorMessage: "Could not get public project id"
18959
- };
18960
- }
18961
- if (!projectName) {
18962
- return {
18963
- success: false,
18964
- errorMessage: `Could not get project. Check that your val.config has the 'project' field set, or set it using the VAL_PROJECT environment variable`
18965
- };
18966
- }
18967
- remoteFilesCounter += 1;
18968
- const bucket = remoteFileBuckets[remoteFilesCounter % remoteFileBuckets.length];
18969
- if (!bucket) {
18970
- return {
18971
- success: false,
18972
- errorMessage: `Internal error: could not allocate a bucket for the remote file located at ${ctx.sourcePath}`
18973
- };
21945
+ const opened = await openRemoteUploadSession(ctx);
21946
+ if (!opened.success) {
21947
+ return opened.result;
18974
21948
  }
21949
+ const {
21950
+ session
21951
+ } = opened;
18975
21952
  const fileBuffer = ctx.fs.readBuffer(filePath);
18976
21953
  if (fileBuffer === undefined) {
18977
21954
  return {
@@ -18980,32 +21957,16 @@ async function uploadRemoteFileCore(ctx, fileRef, metadata, schema) {
18980
21957
  };
18981
21958
  }
18982
21959
  const relativeFilePath = path__default.relative(ctx.projectRoot, filePath).split(path__default.sep).join("/");
18983
- if (!relativeFilePath.startsWith("public/")) {
18984
- return {
18985
- success: false,
18986
- errorMessage: `File path must be within the public/ directory (e.g. public/path/to/file.txt). Got: ${relativeFilePath}`
18987
- };
18988
- }
18989
- const fileHash = Internal.remote.getFileHash(fileBuffer);
18990
- const coreVersion = Internal.VERSION.core || "unknown";
18991
- const fileExt = getFileExt(filePath);
18992
- const ref = Internal.remote.createRemoteRef(ctx.remote.remoteHost, {
18993
- publicProjectId,
18994
- coreVersion,
18995
- bucket,
18996
- validationHash: Internal.remote.getValidationHash(coreVersion, schema, fileExt, metadata, fileHash, textEncoder),
18997
- fileHash,
18998
- filePath: relativeFilePath
18999
- });
19000
- const remoteFileUpload = await ctx.remote.uploadFile(projectName, bucket, fileHash, fileExt, fileBuffer, {
19001
- pat
19002
- });
19003
- if (!remoteFileUpload.success) {
21960
+ const uploaded = await uploadBytesToRemote(ctx, session, relativeFilePath, fileBuffer, metadata, schema);
21961
+ if (!uploaded.success) {
19004
21962
  return {
19005
21963
  success: false,
19006
- errorMessage: `Could not upload remote file: '${ref}'. Error: ${remoteFileUpload.error}`
21964
+ errorMessage: uploaded.error
19007
21965
  };
19008
21966
  }
21967
+ const {
21968
+ ref
21969
+ } = uploaded;
19009
21970
  ctx.remoteFiles[ctx.sourcePath] = {
19010
21971
  ref,
19011
21972
  metadata
@@ -19013,9 +21974,9 @@ async function uploadRemoteFileCore(ctx, fileRef, metadata, schema) {
19013
21974
  return {
19014
21975
  success: true,
19015
21976
  shouldApplyPatch: true,
19016
- publicProjectId,
19017
- remoteFileBuckets,
19018
- remoteFilesCounter,
21977
+ publicProjectId: session.publicProjectId,
21978
+ remoteFileBuckets: session.remoteFileBuckets,
21979
+ remoteFilesCounter: session.remoteFilesCounter,
19019
21980
  events: [{
19020
21981
  type: "remote-uploading",
19021
21982
  ref
@@ -19216,50 +22177,6 @@ async function handleUniqueFolderCheck(ctx) {
19216
22177
  success: true
19217
22178
  };
19218
22179
  }
19219
-
19220
- /**
19221
- * What is out of step between a gallery's entries and its directory.
19222
- *
19223
- * Two questions, and they treat a remote entry differently — which is the whole
19224
- * reason this is separate from the handler around it:
19225
- *
19226
- * - **Missing**: an entry with no bytes at its local path. Asked of LOCAL
19227
- * entries only. A remote entry's bytes live on the content host, and nothing
19228
- * puts a copy in the working tree: `saveOrUploadFiles` uploads the remote
19229
- * descriptors and copies only the local ones into the tree, so a remote entry
19230
- * added through the Studio (or over MCP) has no local file by design, and
19231
- * demanding one would mean committing remote bytes to git — which is what
19232
- * remote storage exists to avoid. Whether those bytes really are on the host
19233
- * is a different check, `image:check-remote`, which already runs for exactly
19234
- * these entries.
19235
- * - **Untracked**: a file in the directory that no entry claims. Asked of every
19236
- * entry, remote included, and that is why they are normalised to their local
19237
- * path: `val validate --fix` promotes a local file to a remote ref and leaves
19238
- * the file where it was, so a remote entry can perfectly well have one.
19239
- */
19240
- function checkGalleryFiles(input) {
19241
- const {
19242
- dir,
19243
- projectRoot,
19244
- fs
19245
- } = input;
19246
- const entries = input.entryKeys.map(galleryEntryOf);
19247
- const trackedFiles = new Set(entries.map(entry => entry.localPath));
19248
- const missingTrackedFiles = entries.filter(entry => !entry.remote && !fs.fileExists(path__default.join(projectRoot, entry.localPath))).map(entry => entry.localPath);
19249
- const filesInDir = [];
19250
- try {
19251
- const found = fs.readDirectory(path__default.join(projectRoot, dir), undefined, undefined, ["**/*"]);
19252
- for (const entry of found) {
19253
- filesInDir.push("/" + path__default.relative(projectRoot, entry).split(path__default.sep).join("/"));
19254
- }
19255
- } catch {
19256
- // directory doesn't exist — no untracked files possible
19257
- }
19258
- return {
19259
- missingTrackedFiles,
19260
- untrackedFiles: filesInDir.filter(f => !trackedFiles.has(f))
19261
- };
19262
- }
19263
22180
  async function handleCheckAllFiles(ctx) {
19264
22181
  const value = ctx.validationError.value;
19265
22182
  if (!value || typeof value.dir !== "string") {
@@ -19406,12 +22323,20 @@ const currentFixHandlers = {
19406
22323
  "image:add-metadata": handleFileMetadata,
19407
22324
  "file:check-metadata": handleFileMetadata,
19408
22325
  "file:add-metadata": handleFileMetadata,
22326
+ "video:add-metadata": handleVideoMetadata,
19409
22327
  "image:upload-remote": handleRemoteFileUpload,
19410
22328
  "file:upload-remote": handleRemoteFileUpload,
19411
22329
  "images:upload-remote": handleRemoteGalleryFileUpload,
19412
22330
  "files:upload-remote": handleRemoteGalleryFileUpload,
19413
22331
  "image:download-remote": handleRemoteFileDownload,
19414
22332
  "file:download-remote": handleRemoteFileDownload,
22333
+ "video:upload-remote": handleVideoUploadRemote,
22334
+ "video:download-remote": handleVideoDownloadRemote,
22335
+ "videos:add-metadata": handleVideosetMetadata,
22336
+ "videos:upload-remote": handleVideosetUploadRemote,
22337
+ "videos:check-remote": handleVideosetCheckRemote,
22338
+ "videos:check-unique-folder": handleUniqueFolderCheck,
22339
+ "videos:check-all-files": handleVideosetCheckAllFiles,
19415
22340
  "image:check-remote": handleRemoteFileCheck,
19416
22341
  "images:check-remote": handleRemoteFileCheck,
19417
22342
  "file:check-remote": handleRemoteFileCheck,
@@ -19607,20 +22532,15 @@ function createPrettierFormatter(prettier, options) {
19607
22532
  }
19608
22533
 
19609
22534
  /**
19610
- * NOTE: this is intentionally NOT `SharedValConfig` from `@valbuild/shared`.
19611
- * That schema requires `files.directory` to be exactly `/public/val`, whereas
19612
- * this one accepts any path beneath `/public`. Unifying them would change which
19613
- * configs are accepted, so they are kept separate on purpose.
22535
+ * NOTE: this is intentionally NOT `SharedValConfig` from `@valbuild/shared`,
22536
+ * which leaves `files` out: `files.remote` decides how the schemas are built,
22537
+ * so it is read where `val.config.ts` is, not shared with the client.
19614
22538
  */
19615
22539
  const ValConfigSchema = z$1.object({
19616
22540
  project: z$1.string().optional(),
19617
22541
  root: z$1.string().optional(),
19618
22542
  files: z$1.object({
19619
- directory: z$1.string().refine(val => (val === "/public" || val.startsWith("/public/") && !val.endsWith("/")) &&
19620
- // Reject path traversal so the directory cannot escape /public
19621
- !val.split("/").some(segment => segment === "." || segment === ".."), {
19622
- message: "files.directory must start with '/public', must not end with '/' and must not contain '.' or '..' segments"
19623
- })
22543
+ remote: z$1.boolean().optional()
19624
22544
  }).optional(),
19625
22545
  gitCommit: z$1.string().optional(),
19626
22546
  gitBranch: z$1.string().optional(),
@@ -20109,7 +23029,7 @@ async function replaySnapshot(snapshotDir) {
20109
23029
  const serverOps = new ValOpsFS(process.env.VAL_CONTENT_URL || DEFAULT_CONTENT_HOST, root, valModules,
20110
23030
  // The snapshot's own val.config, as evaluated by loadValModules - no need to
20111
23031
  // re-read it, and this way the replay uses exactly the config the snapshot
20112
- // carries (files.directory in particular).
23032
+ // carries.
20113
23033
  {
20114
23034
  config: valModules.config
20115
23035
  });
@@ -20188,4 +23108,4 @@ function readCapturedReport(snapshotDir) {
20188
23108
  return JSON.parse(fs.readFileSync(reportPath, "utf-8"));
20189
23109
  }
20190
23110
 
20191
- export { DEFAULT_LOGIN_EXPIRES_IN_SECONDS, DEFAULT_LOGIN_HOST, DEFAULT_LOGIN_POLL_INTERVAL_SECONDS, EXTERNAL_RESULT, InMemoryPatchStore, Service, ValFSHost, ValLoginError, ValModuleLoader, ValOpsFS, ValOpsHttp, ValOpsMemory, ValSourceFileHandler, analyzeValModule, awaitValLoginConfirmation, checkRemoteRef, classifyJsonValuesOp, compareWithCapturedReport, createDefaultValFSHost, createFixPatch, createJsonEntryPathMap, createModulePathMap, createPrettierFormatter, createService, createValApiRouter, createValModuleFileInspector, createValOps, createValServer, currentFixHandlers, decodeJwtWithoutVerifying, defineExternal, describePatchStoreProblems, downloadFileFromRemote, encodeJwt, err, evalValConfigFile, extractFileMetadata, extractImageMetadata, extractJsonValuesEntry, findAndEvalValConfigFile, findDefaultExport, findJsonEntryFilePath, fixHandlers, formatPatchSourceError, formatSyntaxErrorTree, getCachedRemoteFileDir, getCachedRemoteFilePath, getCompilerOptions, getExpire, getFileExt, getModulePathRange, getPersonalAccessTokenPath, getSettings, getValidationErrorFileRef, handleCheckAllFiles, handleExternalUpload, handleFileMetadata, handleJsonValuesExtractEntry, handleRemoteFileCheck, handleRemoteFileDownload, handleRemoteFileUpload, handleRemoteGalleryFileUpload, handleUniqueFolderCheck, initHandlerOptions, isExternalResult, loadValModules, ok, parsePersonalAccessTokenFile, patchSourceFile, persistPersonalAccessToken, planJsonValuesEntryExtraction, readCapturedReport, readPatchStore, rebaseContentOp, replaySnapshot, resolveRemoteFileAuth, safeReadGit, startValLogin, uploadRemoteFile, validateMetadata, verifyJwt };
23111
+ export { APP_MODE_REQUIRES_REMOTE_FILES, DEFAULT_LOGIN_EXPIRES_IN_SECONDS, DEFAULT_LOGIN_HOST, DEFAULT_LOGIN_POLL_INTERVAL_SECONDS, EXTERNAL_RESULT, InMemoryPatchStore, Service, ValFSHost, ValLoginError, ValModuleLoader, ValOpsFS, ValOpsHttp, ValOpsMemory, ValSourceFileHandler, analyzeValModule, awaitValLoginConfirmation, checkRemoteRef, classifyJsonValuesOp, compareWithCapturedReport, createDefaultValFSHost, createFixPatch, createJsonEntryPathMap, createModulePathMap, createPrettierFormatter, createService, createValApiRouter, createValModuleFileInspector, createValOps, createValServer, currentFixHandlers, decodeJwtWithoutVerifying, defineExternal, describePatchStoreProblems, downloadFileFromRemote, encodeJwt, err, evalValConfigFile, extractFileMetadata, extractImageMetadata, extractJsonValuesEntry, extractVideoMetadata, extractVideoMetadataFromFile, filesOfVideo, filesOfVideosetEntry, findAndEvalValConfigFile, findDefaultExport, findJsonEntryFilePath, fixHandlers, formatPatchSourceError, formatSyntaxErrorTree, getCachedRemoteFileDir, getCachedRemoteFilePath, getCompilerOptions, getExpire, getFileExt, getModulePathRange, getPersonalAccessTokenPath, getSettings, getValidationErrorFileRef, handleCheckAllFiles, handleExternalUpload, handleFileMetadata, handleJsonValuesExtractEntry, handleRemoteFileCheck, handleRemoteFileDownload, handleRemoteFileUpload, handleRemoteGalleryFileUpload, handleUniqueFolderCheck, handleVideosetCheckAllFiles, handleVideosetCheckRemote, handleVideosetMetadata, handleVideosetUploadRemote, initHandlerOptions, isExternalResult, loadValModules, ok, parsePersonalAccessTokenFile, patchSourceFile, persistPersonalAccessToken, planJsonValuesEntryExtraction, readCapturedReport, readPatchStore, rebaseContentOp, replaySnapshot, resolveRemoteFileAuth, safeReadGit, startValLogin, uploadRemoteFile, validateMetadata, verifyJwt, videosetEntryVideoSchema };