@proteinjs/db-file 1.8.4 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/generated/index.d.ts.map +1 -1
  3. package/dist/generated/index.js +3 -1
  4. package/dist/generated/index.js.map +1 -1
  5. package/dist/index.d.ts +4 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +4 -0
  8. package/dist/index.js.map +1 -1
  9. package/dist/src/DbFileStorageDriver.d.ts +7 -0
  10. package/dist/src/DbFileStorageDriver.d.ts.map +1 -1
  11. package/dist/src/DbFileStorageDriver.js +69 -41
  12. package/dist/src/DbFileStorageDriver.js.map +1 -1
  13. package/dist/src/FileCopyForOthers.d.ts +52 -0
  14. package/dist/src/FileCopyForOthers.d.ts.map +1 -0
  15. package/dist/src/FileCopyForOthers.js +62 -0
  16. package/dist/src/FileCopyForOthers.js.map +1 -0
  17. package/dist/src/FileStorage.d.ts +145 -11
  18. package/dist/src/FileStorage.d.ts.map +1 -1
  19. package/dist/src/FileStorage.js +537 -41
  20. package/dist/src/FileStorage.js.map +1 -1
  21. package/dist/src/FileStorageDriver.d.ts +11 -0
  22. package/dist/src/FileStorageDriver.d.ts.map +1 -1
  23. package/dist/src/FileStorageError.d.ts +62 -0
  24. package/dist/src/FileStorageError.d.ts.map +1 -0
  25. package/dist/src/FileStorageError.js +118 -0
  26. package/dist/src/FileStorageError.js.map +1 -0
  27. package/dist/src/FileVariantMaker.d.ts +61 -0
  28. package/dist/src/FileVariantMaker.d.ts.map +1 -0
  29. package/dist/src/FileVariantMaker.js +62 -0
  30. package/dist/src/FileVariantMaker.js.map +1 -0
  31. package/dist/src/routes/FileResponder.d.ts +41 -0
  32. package/dist/src/routes/FileResponder.d.ts.map +1 -0
  33. package/dist/src/routes/FileResponder.js +135 -0
  34. package/dist/src/routes/FileResponder.js.map +1 -0
  35. package/dist/src/routes/getFile.d.ts +5 -13
  36. package/dist/src/routes/getFile.d.ts.map +1 -1
  37. package/dist/src/routes/getFile.js +20 -56
  38. package/dist/src/routes/getFile.js.map +1 -1
  39. package/dist/src/routes/getFileVariant.d.ts +20 -0
  40. package/dist/src/routes/getFileVariant.d.ts.map +1 -0
  41. package/dist/src/routes/getFileVariant.js +112 -0
  42. package/dist/src/routes/getFileVariant.js.map +1 -0
  43. package/dist/src/routes/getFileVariantRoute.d.ts +7 -0
  44. package/dist/src/routes/getFileVariantRoute.d.ts.map +1 -0
  45. package/dist/src/routes/getFileVariantRoute.js +9 -0
  46. package/dist/src/routes/getFileVariantRoute.js.map +1 -0
  47. package/dist/src/tables/FileTable.d.ts +55 -2
  48. package/dist/src/tables/FileTable.d.ts.map +1 -1
  49. package/dist/src/tables/FileTable.js +8 -0
  50. package/dist/src/tables/FileTable.js.map +1 -1
  51. package/dist/test/DbFileStorageDriverMissingBytes.test.d.ts +2 -0
  52. package/dist/test/DbFileStorageDriverMissingBytes.test.d.ts.map +1 -0
  53. package/dist/test/DbFileStorageDriverMissingBytes.test.js +184 -0
  54. package/dist/test/DbFileStorageDriverMissingBytes.test.js.map +1 -0
  55. package/dist/test/FileByteAccess.test.js +6 -3
  56. package/dist/test/FileByteAccess.test.js.map +1 -1
  57. package/dist/test/FileCopyForOthers.test.d.ts +2 -0
  58. package/dist/test/FileCopyForOthers.test.d.ts.map +1 -0
  59. package/dist/test/FileCopyForOthers.test.js +1143 -0
  60. package/dist/test/FileCopyForOthers.test.js.map +1 -0
  61. package/dist/test/FileMediaMetadata.test.js +60 -5
  62. package/dist/test/FileMediaMetadata.test.js.map +1 -1
  63. package/dist/test/FileStorageError.test.d.ts +2 -0
  64. package/dist/test/FileStorageError.test.d.ts.map +1 -0
  65. package/dist/test/FileStorageError.test.js +68 -0
  66. package/dist/test/FileStorageError.test.js.map +1 -0
  67. package/dist/test/FileTestEnvironment.d.ts.map +1 -1
  68. package/dist/test/FileTestEnvironment.js +3 -0
  69. package/dist/test/FileTestEnvironment.js.map +1 -1
  70. package/dist/test/FileVariants.test.d.ts +2 -0
  71. package/dist/test/FileVariants.test.d.ts.map +1 -0
  72. package/dist/test/FileVariants.test.js +1008 -0
  73. package/dist/test/FileVariants.test.js.map +1 -0
  74. package/dist/test/GetFileRoute.test.js +29 -0
  75. package/dist/test/GetFileRoute.test.js.map +1 -1
  76. package/generated/index.ts +3 -1
  77. package/index.ts +4 -0
  78. package/package.json +5 -5
  79. package/src/DbFileStorageDriver.ts +32 -21
  80. package/src/FileCopyForOthers.ts +71 -0
  81. package/src/FileStorage.ts +351 -18
  82. package/src/FileStorageDriver.ts +12 -0
  83. package/src/FileStorageError.ts +123 -0
  84. package/src/FileVariantMaker.ts +84 -0
  85. package/src/routes/FileResponder.ts +85 -0
  86. package/src/routes/getFile.ts +9 -44
  87. package/src/routes/getFileVariant.ts +53 -0
  88. package/src/routes/getFileVariantRoute.ts +7 -0
  89. package/src/tables/FileTable.ts +57 -1
  90. package/test/DbFileStorageDriverMissingBytes.test.ts +85 -0
  91. package/test/FileByteAccess.test.ts +7 -1
  92. package/test/FileCopyForOthers.test.ts +702 -0
  93. package/test/FileMediaMetadata.test.ts +44 -0
  94. package/test/FileStorageError.test.ts +79 -0
  95. package/test/FileTestEnvironment.ts +3 -0
  96. package/test/FileVariants.test.ts +604 -0
  97. package/test/GetFileRoute.test.ts +19 -0
@@ -1,4 +1,15 @@
1
1
  "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
2
13
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
14
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
15
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -35,14 +46,27 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
35
46
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
47
  }
37
48
  };
49
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
50
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
51
+ if (ar || !(i in from)) {
52
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
53
+ ar[i] = from[i];
54
+ }
55
+ }
56
+ return to.concat(ar || Array.prototype.slice.call(from));
57
+ };
38
58
  Object.defineProperty(exports, "__esModule", { value: true });
39
59
  exports.FileStorage = exports.getFileStorage = void 0;
60
+ var db_1 = require("@proteinjs/db");
40
61
  var user_1 = require("@proteinjs/user");
41
62
  var tables_1 = require("./tables/tables");
42
63
  var FileStorageService_1 = require("./services/FileStorageService");
43
64
  var FileReachabilityResolver_1 = require("./FileReachabilityResolver");
65
+ var FileCopyForOthers_1 = require("./FileCopyForOthers");
66
+ var FileVariantMaker_1 = require("./FileVariantMaker");
44
67
  var reflection_1 = require("@proteinjs/reflection");
45
68
  var logger_1 = require("@proteinjs/logger");
69
+ var service_1 = require("@proteinjs/service");
46
70
  var DbFileStorageDriver_1 = require("./DbFileStorageDriver");
47
71
  /**
48
72
  * A convenience factory function so code using this is portable (can be used in server or browser).
@@ -64,6 +88,7 @@ var FileStorage = /** @class */ (function () {
64
88
  allUsers: true,
65
89
  },
66
90
  };
91
+ this.logger = new logger_1.Logger({ name: this.constructor.name });
67
92
  }
68
93
  /**
69
94
  * The `FileStorageDriver` for this process — provided by the `DefaultFileStorageDriverFactory`
@@ -114,44 +139,156 @@ var FileStorage = /** @class */ (function () {
114
139
  * Retrieves the metadata of a given file — THE file-read access decision every serving path
115
140
  * derives from (`/file/:id`, signed-URL minting, the browser service).
116
141
  *
117
- * Two legs: the caller's own file resolves by the SCOPED read; when that misses, the
118
- * shared-content leg asks the registered {@link FileReachabilityResolver}s whether the caller
119
- * can read a row that REFERENCES the file (a shared thought's media node) — content access
120
- * confers file access, through the content's own grant-filtered read, never by widening file
121
- * scope. No resolver vouching means the miss stands. Reads only: writes/deletes stay scoped.
142
+ * Three legs, cheapest first: the caller's own file resolves by the SCOPED read. When that
143
+ * misses, the derived leg: a VARIANT the seam made (`File.variantOf`) is readable by whoever
144
+ * can read its original — this same decision, asked of the original — so a variant derived
145
+ * after the content was placed (no content row names it) is reachable by exactly the readers
146
+ * of the file it was made from; one system point read decides whether the row is a variant at
147
+ * all. Last, the shared-content leg asks the registered {@link FileReachabilityResolver}s
148
+ * whether the caller can read a row that REFERENCES the file (a shared thought's media node) —
149
+ * content access confers file access, through the content's own grant-filtered read, never by
150
+ * widening file scope. No leg vouching means the miss stands. Reads only: writes/deletes stay
151
+ * scoped.
122
152
  * @param fileId - The `id` of the file.
123
153
  * @returns The file metadata, or `undefined` when the caller can neither own nor reach it.
124
154
  */
125
155
  FileStorage.prototype.getFile = function (fileId) {
156
+ var _a;
126
157
  return __awaiter(this, void 0, void 0, function () {
127
- var db, file, _i, _a, resolver;
128
- return __generator(this, function (_b) {
129
- switch (_b.label) {
158
+ var db, file, row, _i, _b, resolver;
159
+ return __generator(this, function (_c) {
160
+ switch (_c.label) {
130
161
  case 0:
131
162
  db = (0, user_1.getScopedDb)();
132
163
  return [4 /*yield*/, db.get(tables_1.tables.File, { id: fileId })];
133
164
  case 1:
134
- file = _b.sent();
165
+ file = _c.sent();
135
166
  if (file) {
136
167
  return [2 /*return*/, file];
137
168
  }
138
- _i = 0, _a = (0, FileReachabilityResolver_1.getFileReachabilityResolvers)();
139
- _b.label = 2;
169
+ return [4 /*yield*/, (0, user_1.getScopedDbAsSystem)().get(tables_1.tables.File, { id: fileId })];
140
170
  case 2:
141
- if (!(_i < _a.length)) return [3 /*break*/, 6];
142
- resolver = _a[_i];
171
+ row = _c.sent();
172
+ if (!row) {
173
+ return [2 /*return*/, undefined];
174
+ }
175
+ if (!((_a = row.variantOf) === null || _a === void 0 ? void 0 : _a._id)) return [3 /*break*/, 4];
176
+ return [4 /*yield*/, this.getFile(row.variantOf._id)];
177
+ case 3:
178
+ // A variant's reachability is its original's — the copy for others carries no `variantOf`,
179
+ // so its own id stays nobody's but the owner's.
180
+ return [2 /*return*/, (_c.sent()) ? row : undefined];
181
+ case 4:
182
+ _i = 0, _b = (0, FileReachabilityResolver_1.getFileReachabilityResolvers)();
183
+ _c.label = 5;
184
+ case 5:
185
+ if (!(_i < _b.length)) return [3 /*break*/, 8];
186
+ resolver = _b[_i];
143
187
  return [4 /*yield*/, resolver.canReadViaReference(fileId)];
188
+ case 6:
189
+ if (_c.sent()) {
190
+ // Reachability established through the caller's grant-filtered content read — the row
191
+ // itself lives in the owner's scope, so it is served via system read.
192
+ return [2 /*return*/, row];
193
+ }
194
+ _c.label = 7;
195
+ case 7:
196
+ _i++;
197
+ return [3 /*break*/, 5];
198
+ case 8: return [2 /*return*/, undefined];
199
+ }
200
+ });
201
+ });
202
+ };
203
+ /**
204
+ * The variant of this kind of a file — the derived File the row names, or one made now, ONCE,
205
+ * by the registered {@link FileVariantMaker} (the read path's door, behind
206
+ * `GET /file/:id/variant/:kind`: a file made before the seam existed, or by a producer that did
207
+ * not derive it, gets its variant on the first request from a surface that draws it; every
208
+ * later request is served the same row without the maker). Server-only, like `getSignedUrl` —
209
+ * the browser asks by URL, never by service call. Access is the original's ({@link getFile});
210
+ * the variant is stored as the owner's own File whoever's read made it, and is served like any
211
+ * File afterwards — with the same non-owner copy rule.
212
+ * @returns The variant's File row, or `undefined` when the caller cannot read the original, no
213
+ * maker is registered, the maker does not apply to this file for this kind, or the
214
+ * maker could not make it of these bytes (the consumer then draws the original).
215
+ */
216
+ FileStorage.prototype.getVariant = function (fileId, kind) {
217
+ var _a;
218
+ return __awaiter(this, void 0, void 0, function () {
219
+ var file, named, maker, variantId, _b;
220
+ return __generator(this, function (_c) {
221
+ switch (_c.label) {
222
+ case 0: return [4 /*yield*/, this.getFile(fileId)];
223
+ case 1:
224
+ file = _c.sent();
225
+ if (!file) {
226
+ return [2 /*return*/, undefined];
227
+ }
228
+ named = (_a = file[kind]) === null || _a === void 0 ? void 0 : _a._id;
229
+ if (!named) return [3 /*break*/, 3];
230
+ return [4 /*yield*/, (0, user_1.getScopedDbAsSystem)().get(tables_1.tables.File, { id: named })];
231
+ case 2: return [2 /*return*/, _c.sent()];
144
232
  case 3:
145
- if (!_b.sent()) return [3 /*break*/, 5];
146
- return [4 /*yield*/, (0, user_1.getScopedDbAsSystem)().get(tables_1.tables.File, { id: fileId })];
147
- case 4:
148
- // Reachability established through the caller's grant-filtered content read — the row
149
- // itself lives in the owner's scope, so it is served via system read.
150
- return [2 /*return*/, _b.sent()];
233
+ maker = (0, FileVariantMaker_1.getFileVariantMaker)();
234
+ if (!maker || !maker.appliesTo(file, kind)) {
235
+ return [2 /*return*/, undefined];
236
+ }
237
+ return [4 /*yield*/, this.deriveOnce(file, kind)];
238
+ case 4:
239
+ variantId = _c.sent();
240
+ if (!variantId) return [3 /*break*/, 6];
241
+ return [4 /*yield*/, (0, user_1.getScopedDbAsSystem)().get(tables_1.tables.File, { id: variantId })];
151
242
  case 5:
243
+ _b = _c.sent();
244
+ return [3 /*break*/, 7];
245
+ case 6:
246
+ _b = undefined;
247
+ _c.label = 7;
248
+ case 7: return [2 /*return*/, _b];
249
+ }
250
+ });
251
+ });
252
+ };
253
+ /**
254
+ * Make and store every variant the registered maker applies to, with the original's bytes in
255
+ * hand (the ingest's door — one decode of bytes just stored, never a re-read). Each is named on
256
+ * the row; a kind the maker does not apply to is left unset (the read path may derive it later
257
+ * if the maker's rule changes). With no maker registered nothing is made.
258
+ * @returns The caller's file row with each variant made here named on it (the row as the caller
259
+ * holds it, not a re-read — an unset column stays unset), and the variant Files made.
260
+ */
261
+ FileStorage.prototype.deriveVariants = function (file, bytes) {
262
+ var _a;
263
+ return __awaiter(this, void 0, void 0, function () {
264
+ var maker, variants, named, _i, FILE_VARIANT_KINDS_1, kind, variantId, _b, _c;
265
+ return __generator(this, function (_d) {
266
+ switch (_d.label) {
267
+ case 0:
268
+ maker = (0, FileVariantMaker_1.getFileVariantMaker)();
269
+ variants = {};
270
+ named = {};
271
+ if (!maker) return [3 /*break*/, 5];
272
+ _i = 0, FILE_VARIANT_KINDS_1 = FileVariantMaker_1.FILE_VARIANT_KINDS;
273
+ _d.label = 1;
274
+ case 1:
275
+ if (!(_i < FILE_VARIANT_KINDS_1.length)) return [3 /*break*/, 5];
276
+ kind = FILE_VARIANT_KINDS_1[_i];
277
+ if (!(!((_a = file[kind]) === null || _a === void 0 ? void 0 : _a._id) && maker.appliesTo(file, kind))) return [3 /*break*/, 4];
278
+ return [4 /*yield*/, this.makeVariant(file, kind, bytes)];
279
+ case 2:
280
+ variantId = _d.sent();
281
+ _b = variants;
282
+ _c = kind;
283
+ return [4 /*yield*/, (0, user_1.getScopedDbAsSystem)().get(tables_1.tables.File, { id: variantId })];
284
+ case 3:
285
+ _b[_c] = _d.sent();
286
+ named[kind] = new db_1.Reference(tables_1.tables.File.name, variantId);
287
+ _d.label = 4;
288
+ case 4:
152
289
  _i++;
153
- return [3 /*break*/, 2];
154
- case 6: return [2 /*return*/, file];
290
+ return [3 /*break*/, 1];
291
+ case 5: return [2 /*return*/, { file: __assign(__assign({}, file), named), variants: variants }];
155
292
  }
156
293
  });
157
294
  });
@@ -164,26 +301,63 @@ var FileStorage = /** @class */ (function () {
164
301
  * exactly as reachable as the row that names them. The gate lives here because this is the
165
302
  * browser-facing service boundary (`FileStorageService` is `allUsers`) and the driver byte ops
166
303
  * below are deliberately unscoped. Server-side doors that make their OWN documented access
167
- * decision (the avatar route, issue/ticket attachment doors) read bytes through
168
- * `FileStorage.getDriver()` instead.
304
+ * decision (an attachment door keyed by a record's linkage, say) serve through
305
+ * {@link getAuthorizedFileData} — the same owner-or-copy bytes, without this gate.
306
+ *
307
+ * WHICH bytes: the owner's read serves the original; anyone else's — a read that reached the
308
+ * file through the shared-content leg — serves the {@link FileCopyForOthers} copy
309
+ * ({@link servedFileId}): the same substitution `getSignedUrl` makes, so the proxy route, the
310
+ * signed-URL route and every server-side reader of this door agree.
169
311
  * @param fileId - The `id` of the file.
170
312
  * @returns The file data as a single string.
171
- * @throws When the file row does not exist or is not readable by the caller — the same named
172
- * miss either way, so existence is not leaked to unauthorized callers.
313
+ * @throws ServiceRefusal (404, `File not found`) when the file row does not exist or is not
314
+ * readable by the caller, and when the caller is not the owner and no copy can be made
315
+ * ({@link servedFileId}) — ONE answer for all three ({@link notFound}), so no door tells
316
+ * a missing file from one this caller may not have.
173
317
  */
174
318
  FileStorage.prototype.getFileData = function (fileId) {
175
319
  return __awaiter(this, void 0, void 0, function () {
176
- var file;
177
- return __generator(this, function (_a) {
178
- switch (_a.label) {
320
+ var file, _a, _b;
321
+ return __generator(this, function (_c) {
322
+ switch (_c.label) {
179
323
  case 0: return [4 /*yield*/, this.getFile(fileId)];
180
324
  case 1:
181
- file = _a.sent();
325
+ file = _c.sent();
182
326
  if (!file) {
183
- throw new Error("File not found: ".concat(fileId));
327
+ throw FileStorage.notFound();
184
328
  }
185
- return [4 /*yield*/, FileStorage.getDriver().getFileData(fileId)];
186
- case 2: return [2 /*return*/, _a.sent()];
329
+ _b = (_a = FileStorage.getDriver()).getFileData;
330
+ return [4 /*yield*/, this.servedFileId(file)];
331
+ case 2: return [4 /*yield*/, _b.apply(_a, [_c.sent()])];
332
+ case 3: return [2 /*return*/, _c.sent()];
333
+ }
334
+ });
335
+ });
336
+ };
337
+ /**
338
+ * The bytes THIS caller is served for a file a server-side door has ALREADY decided the caller
339
+ * may read, by its own documented rule (an attachment door keyed by a record's linkage, say —
340
+ * a read neither the caller's scope nor a {@link FileReachabilityResolver} would open). The
341
+ * door vouches for access; this decides WHICH bytes, exactly as {@link getFileData} does: the
342
+ * original for the file's owner, the {@link FileCopyForOthers} copy for anyone else — the same
343
+ * copy, made once and named on the row, that every other door serves them. Server-only (not
344
+ * part of the browser-facing `FileStorageService`), so the rule that opens the file stays the
345
+ * door's.
346
+ * @param file - The file's row, as the door read it (its `scope` names the owner).
347
+ * @returns The file data as a single string.
348
+ * @throws ServiceRefusal (404) when the caller is not the owner and no copy can be made — the same
349
+ * refusal every door gives ({@link servedFileId}).
350
+ */
351
+ FileStorage.prototype.getAuthorizedFileData = function (file) {
352
+ return __awaiter(this, void 0, void 0, function () {
353
+ var _a, _b;
354
+ return __generator(this, function (_c) {
355
+ switch (_c.label) {
356
+ case 0:
357
+ _b = (_a = FileStorage.getDriver()).getFileData;
358
+ return [4 /*yield*/, this.servedFileId(file)];
359
+ case 1: return [4 /*yield*/, _b.apply(_a, [_c.sent()])];
360
+ case 2: return [2 /*return*/, _c.sent()];
187
361
  }
188
362
  });
189
363
  });
@@ -192,30 +366,35 @@ var FileStorage = /** @class */ (function () {
192
366
  * Mint a short-lived, read-only URL for the file's bytes (server-only; not part of the
193
367
  * browser-facing `FileStorageService`). A signed URL is a bearer capability, so minting
194
368
  * verifies the caller can read the file row (the two-legged {@link getFile} read — own scope
195
- * or shared-content reachability) before signing.
369
+ * or shared-content reachability) before signing — and signs the bytes THAT caller is served:
370
+ * the original for the owner, the {@link FileCopyForOthers} copy for anyone else.
196
371
  * @param fileId - The `id` of the file.
197
372
  * @param options.ttlMs - How long the URL stays valid; the driver applies its default when omitted.
198
373
  * @returns The signed URL, or `undefined` when the driver has no external URL space
199
374
  * (`DbFileStorageDriver`) — the caller then serves bytes through the proxy route.
200
- * @throws When the file row does not exist or is not readable by the caller.
375
+ * @throws ServiceRefusal (404, `File not found`) when the file row does not exist or is not
376
+ * readable by the caller, and when the caller is not the owner and no copy can be made —
377
+ * the one answer {@link getFileData} gives ({@link notFound}).
201
378
  */
202
379
  FileStorage.prototype.getSignedUrl = function (fileId, options) {
203
380
  return __awaiter(this, void 0, void 0, function () {
204
- var file, driver;
205
- return __generator(this, function (_a) {
206
- switch (_a.label) {
381
+ var file, driver, _a, _b;
382
+ return __generator(this, function (_c) {
383
+ switch (_c.label) {
207
384
  case 0: return [4 /*yield*/, this.getFile(fileId)];
208
385
  case 1:
209
- file = _a.sent();
386
+ file = _c.sent();
210
387
  if (!file) {
211
- throw new Error("File not found: ".concat(fileId));
388
+ throw FileStorage.notFound();
212
389
  }
213
390
  driver = FileStorage.getDriver();
214
391
  if (!driver.getSignedUrl) {
215
392
  return [2 /*return*/, undefined];
216
393
  }
217
- return [4 /*yield*/, driver.getSignedUrl(fileId, options)];
218
- case 2: return [2 /*return*/, _a.sent()];
394
+ _b = (_a = driver).getSignedUrl;
395
+ return [4 /*yield*/, this.servedFileId(file)];
396
+ case 2: return [4 /*yield*/, _b.apply(_a, [_c.sent(), options])];
397
+ case 3: return [2 /*return*/, _c.sent()];
219
398
  }
220
399
  });
221
400
  });
@@ -227,6 +406,10 @@ var FileStorage = /** @class */ (function () {
227
406
  * (the same authorization a scoped row update enforces). Deliberately STRICTER than
228
407
  * {@link getFileData}: the {@link FileReachabilityResolver} leg widens READS only, so a
229
408
  * share recipient who can read the bytes still cannot write them.
409
+ *
410
+ * New bytes make every derived File stale — the copy others were served, the preview, the
411
+ * stage variant: each is dropped here — the row forgets it, then its row (and, through the
412
+ * delete watcher, its bytes) goes — and the next read that wants one makes a fresh one.
230
413
  * @param fileId - The `id` of the file.
231
414
  * @param data - The new data string to replace the existing data.
232
415
  * @throws When the file row does not exist or is not writable by the caller — the same named
@@ -247,6 +430,9 @@ var FileStorage = /** @class */ (function () {
247
430
  }
248
431
  return [4 /*yield*/, FileStorage.getDriver().updateFileData(fileId, data)];
249
432
  case 2:
433
+ _a.sent();
434
+ return [4 /*yield*/, this.dropDerivedFiles(file)];
435
+ case 3:
250
436
  _a.sent();
251
437
  return [2 /*return*/];
252
438
  }
@@ -300,6 +486,316 @@ var FileStorage = /** @class */ (function () {
300
486
  });
301
487
  });
302
488
  };
489
+ /**
490
+ * The id whose bytes this caller is served: the file's own for its owner, or for a file with
491
+ * no maker (or one the maker does not apply to); otherwise the {@link FileCopyForOthers} copy —
492
+ * the one already named on the row, or made now, once, and named for every later read.
493
+ *
494
+ * ONE REFUSAL, EVERY DOOR: when no copy can be made (the seam's {@link FileCopyRefused}), the file
495
+ * is served to no one but its owner, so to this caller it is not there — a
496
+ * `ServiceRefusal(404, 'File not found')`, thrown here so the browser service, `GET /file/:id` in
497
+ * both its shapes and the server-side door answer the same by construction: the service router
498
+ * answers 404 `{ error: 'File not found' }`, the executor logs one WARN (a refusal, never a
499
+ * failure), the route answers `404 File not found` — the same answer, at every door, as a row the
500
+ * caller cannot read ({@link notFound}). The refusal carries no reason, file id or owner: the
501
+ * maker's reason is the server's, logged here in one WARN, so nothing a caller reads tells a
502
+ * refused copy from a file that is not there.
503
+ */
504
+ FileStorage.prototype.servedFileId = function (file) {
505
+ var _a;
506
+ return __awaiter(this, void 0, void 0, function () {
507
+ var maker, error_1;
508
+ return __generator(this, function (_b) {
509
+ switch (_b.label) {
510
+ case 0:
511
+ if (this.ownedByCaller(file)) {
512
+ return [2 /*return*/, file.id];
513
+ }
514
+ if ((_a = file.copyForOthers) === null || _a === void 0 ? void 0 : _a._id) {
515
+ return [2 /*return*/, file.copyForOthers._id];
516
+ }
517
+ maker = (0, FileCopyForOthers_1.getFileCopyForOthers)();
518
+ if (!maker || !maker.appliesTo(file)) {
519
+ return [2 /*return*/, file.id];
520
+ }
521
+ _b.label = 1;
522
+ case 1:
523
+ _b.trys.push([1, 3, , 4]);
524
+ return [4 /*yield*/, this.makeCopyForOthers(file)];
525
+ case 2: return [2 /*return*/, _b.sent()];
526
+ case 3:
527
+ error_1 = _b.sent();
528
+ if (FileCopyForOthers_1.FileCopyRefused.is(error_1)) {
529
+ this.logger.warn({
530
+ message: 'No copy of a file can be made for anyone but its owner; refused as not found',
531
+ obj: { fileId: error_1.fileId, reason: error_1.reason },
532
+ });
533
+ throw FileStorage.notFound();
534
+ }
535
+ throw error_1;
536
+ case 4: return [2 /*return*/];
537
+ }
538
+ });
539
+ });
540
+ };
541
+ /**
542
+ * Whether the caller is the file's owner — the row's `scope` is the owner (the scoped read
543
+ * {@link getFile} makes first is exactly `scope = the caller`), so a row {@link getFile} handed
544
+ * back whose scope is someone else's was reached through the shared-content leg. A row with no
545
+ * owner recorded serves as itself: there is no one to withhold it from.
546
+ */
547
+ FileStorage.prototype.ownedByCaller = function (file) {
548
+ return !file.scope || file.scope === new user_1.UserRepo().getUser().id;
549
+ };
550
+ /**
551
+ * Makes the copy (the maker's bytes, from the original's), stores it as a File in the owner's
552
+ * scope and names it on the original's row. Two non-owners reading at once may both get here:
553
+ * the row's word wins — decided in ONE transaction (the read of the row and the write of its
554
+ * word together, so racing writers are serialized and the loser's transaction, retried, finds
555
+ * the winner named) — and a copy that lost is deleted after the commit, the first is served.
556
+ */
557
+ FileStorage.prototype.makeCopyForOthers = function (file) {
558
+ return __awaiter(this, void 0, void 0, function () {
559
+ var maker, driver, original, _a, _b, copyBytes, cause_1, system, copy, named;
560
+ var _this = this;
561
+ return __generator(this, function (_c) {
562
+ switch (_c.label) {
563
+ case 0:
564
+ maker = (0, FileCopyForOthers_1.getFileCopyForOthers)();
565
+ driver = FileStorage.getDriver();
566
+ _b = (_a = Buffer).from;
567
+ return [4 /*yield*/, driver.getFileData(file.id)];
568
+ case 1:
569
+ original = _b.apply(_a, [_c.sent(), 'base64']);
570
+ _c.label = 2;
571
+ case 2:
572
+ _c.trys.push([2, 4, , 5]);
573
+ return [4 /*yield*/, maker.make(file, original)];
574
+ case 3:
575
+ copyBytes = _c.sent();
576
+ return [3 /*break*/, 5];
577
+ case 4:
578
+ cause_1 = _c.sent();
579
+ // The maker's contract: a throw means no copy can be made — the file is the owner's alone.
580
+ throw new FileCopyForOthers_1.FileCopyRefused(file.id, cause_1);
581
+ case 5:
582
+ system = (0, db_1.getDbAsSystem)();
583
+ return [4 /*yield*/, system.insert(tables_1.tables.File, __assign(__assign(__assign(__assign({ name: file.name, type: file.type, size: copyBytes.length }, (file.width !== undefined && file.width !== null ? { width: file.width } : {})), (file.height !== undefined && file.height !== null ? { height: file.height } : {})), (file.durationMs !== undefined && file.durationMs !== null ? { durationMs: file.durationMs } : {})), { scope: file.scope }))];
584
+ case 6:
585
+ copy = _c.sent();
586
+ return [4 /*yield*/, driver.createFile(copy, copyBytes.toString('base64'))];
587
+ case 7:
588
+ _c.sent();
589
+ return [4 /*yield*/, system.runTransaction(function () { return __awaiter(_this, void 0, void 0, function () {
590
+ var current;
591
+ var _a;
592
+ return __generator(this, function (_b) {
593
+ switch (_b.label) {
594
+ case 0: return [4 /*yield*/, system.get(tables_1.tables.File, { id: file.id })];
595
+ case 1:
596
+ current = _b.sent();
597
+ if ((_a = current === null || current === void 0 ? void 0 : current.copyForOthers) === null || _a === void 0 ? void 0 : _a._id) {
598
+ return [2 /*return*/, current.copyForOthers._id];
599
+ }
600
+ return [4 /*yield*/, system.update(tables_1.tables.File, { id: file.id, copyForOthers: new db_1.Reference(tables_1.tables.File.name, copy.id) })];
601
+ case 2:
602
+ _b.sent();
603
+ return [2 /*return*/, copy.id];
604
+ }
605
+ });
606
+ }); })];
607
+ case 8:
608
+ named = _c.sent();
609
+ if (!(named !== copy.id)) return [3 /*break*/, 10];
610
+ // Outside the transaction: the row's delete takes the bytes with it (the delete watcher), a
611
+ // side effect that must not ride a transaction the runner may retry.
612
+ return [4 /*yield*/, system.delete(tables_1.tables.File, { id: copy.id })];
613
+ case 9:
614
+ // Outside the transaction: the row's delete takes the bytes with it (the delete watcher), a
615
+ // side effect that must not ride a transaction the runner may retry.
616
+ _c.sent();
617
+ _c.label = 10;
618
+ case 10: return [2 /*return*/, named];
619
+ }
620
+ });
621
+ });
622
+ };
623
+ /**
624
+ * The read path's derivation, ONCE per file and kind at a time in this process: the readers
625
+ * that ask for the same absent variant while one derives (a shared document opened by many on
626
+ * one tick — every face asks the same URL) wait for that derivation's answer instead of each
627
+ * reading the original, encoding it and storing an object the row's word would then discard.
628
+ * Across processes the row's word in one transaction ({@link makeVariant}) still decides: this
629
+ * bounds the cost, that bounds the outcome. A maker that cannot make the variant of these
630
+ * bytes (a picture its decoder cannot read) answers `undefined` — nothing is stored, the reader
631
+ * draws the file itself, the next reader asks again — said in the log, never as a failed read;
632
+ * any other failure (the store, the database) is the reader's as it would be for any File.
633
+ */
634
+ FileStorage.prototype.deriveOnce = function (file, kind) {
635
+ var _this = this;
636
+ var key = "".concat(file.id, ":").concat(kind);
637
+ var running = FileStorage.derivations.get(key);
638
+ if (running) {
639
+ return running;
640
+ }
641
+ var derivation = (function () { return __awaiter(_this, void 0, void 0, function () {
642
+ var original, _a, _b, error_2;
643
+ return __generator(this, function (_c) {
644
+ switch (_c.label) {
645
+ case 0:
646
+ _b = (_a = Buffer).from;
647
+ return [4 /*yield*/, FileStorage.getDriver().getFileData(file.id)];
648
+ case 1:
649
+ original = _b.apply(_a, [_c.sent(), 'base64']);
650
+ _c.label = 2;
651
+ case 2:
652
+ _c.trys.push([2, 4, , 5]);
653
+ return [4 /*yield*/, this.makeVariant(file, kind, original)];
654
+ case 3: return [2 /*return*/, _c.sent()];
655
+ case 4:
656
+ error_2 = _c.sent();
657
+ if (!FileVariantMaker_1.FileVariantNotMade.is(error_2)) {
658
+ throw error_2;
659
+ }
660
+ new logger_1.Logger({ name: 'FileStorage' }).warn({
661
+ message: "No ".concat(kind, " variant could be made of file ").concat(file.id, "; the file itself is served"),
662
+ obj: { reason: error_2.reason },
663
+ });
664
+ return [2 /*return*/, undefined];
665
+ case 5: return [2 /*return*/];
666
+ }
667
+ });
668
+ }); })().finally(function () { return FileStorage.derivations.delete(key); });
669
+ FileStorage.derivations.set(key, derivation);
670
+ return derivation;
671
+ };
672
+ /**
673
+ * Makes the variant (the maker's answer from the original's bytes), stores it as a File in the
674
+ * OWNER's scope naming its original, and names it on the original's row. Two readers may derive
675
+ * the same kind at once: the row's word wins — decided in ONE transaction, exactly as the copy
676
+ * for others is named — and the variant that lost is deleted after the commit. The maker's own
677
+ * failure (it could not make the variant of these bytes) is thrown as {@link FileVariantNotMade}
678
+ * with the maker's reason, so the doors can tell it from a failure of the store or the database;
679
+ * nothing is stored on it.
680
+ * @returns The id of the variant the row names.
681
+ */
682
+ FileStorage.prototype.makeVariant = function (file, kind, bytes) {
683
+ return __awaiter(this, void 0, void 0, function () {
684
+ var maker, driver, made, cause_2, system, variant, named;
685
+ var _this = this;
686
+ return __generator(this, function (_a) {
687
+ switch (_a.label) {
688
+ case 0:
689
+ maker = (0, FileVariantMaker_1.getFileVariantMaker)();
690
+ driver = FileStorage.getDriver();
691
+ _a.label = 1;
692
+ case 1:
693
+ _a.trys.push([1, 3, , 4]);
694
+ return [4 /*yield*/, maker.make(file, bytes, kind)];
695
+ case 2:
696
+ made = _a.sent();
697
+ return [3 /*break*/, 4];
698
+ case 3:
699
+ cause_2 = _a.sent();
700
+ // The maker's contract: a throw means no variant can be made of these bytes.
701
+ throw new FileVariantMaker_1.FileVariantNotMade(file.id, kind, cause_2);
702
+ case 4:
703
+ system = (0, db_1.getDbAsSystem)();
704
+ return [4 /*yield*/, system.insert(tables_1.tables.File, __assign(__assign(__assign({ name: "(".concat(kind, ") ").concat(file.name), type: made.type, size: made.bytes.length }, (made.width !== undefined ? { width: made.width } : {})), (made.height !== undefined ? { height: made.height } : {})), { variantOf: new db_1.Reference(tables_1.tables.File.name, file.id), scope: file.scope }))];
705
+ case 5:
706
+ variant = _a.sent();
707
+ return [4 /*yield*/, driver.createFile(variant, made.bytes.toString('base64'))];
708
+ case 6:
709
+ _a.sent();
710
+ return [4 /*yield*/, system.runTransaction(function () { return __awaiter(_this, void 0, void 0, function () {
711
+ var current;
712
+ var _a;
713
+ var _b;
714
+ return __generator(this, function (_c) {
715
+ switch (_c.label) {
716
+ case 0: return [4 /*yield*/, system.get(tables_1.tables.File, { id: file.id })];
717
+ case 1:
718
+ current = _c.sent();
719
+ if ((_b = current === null || current === void 0 ? void 0 : current[kind]) === null || _b === void 0 ? void 0 : _b._id) {
720
+ return [2 /*return*/, current[kind]._id];
721
+ }
722
+ return [4 /*yield*/, system.update(tables_1.tables.File, (_a = { id: file.id }, _a[kind] = new db_1.Reference(tables_1.tables.File.name, variant.id), _a))];
723
+ case 2:
724
+ _c.sent();
725
+ return [2 /*return*/, variant.id];
726
+ }
727
+ });
728
+ }); })];
729
+ case 7:
730
+ named = _a.sent();
731
+ if (!(named !== variant.id)) return [3 /*break*/, 9];
732
+ // Outside the transaction: the row's delete takes the bytes with it (the delete watcher), a
733
+ // side effect that must not ride a transaction the runner may retry.
734
+ return [4 /*yield*/, system.delete(tables_1.tables.File, { id: variant.id })];
735
+ case 8:
736
+ // Outside the transaction: the row's delete takes the bytes with it (the delete watcher), a
737
+ // side effect that must not ride a transaction the runner may retry.
738
+ _a.sent();
739
+ _a.label = 9;
740
+ case 9: return [2 /*return*/, named];
741
+ }
742
+ });
743
+ });
744
+ };
745
+ /**
746
+ * The row forgets each derived File first (nothing serves a copy or a variant the row no longer
747
+ * names), then their rows go — the bytes with them, through the delete watcher: the copy for
748
+ * others and every variant kind, one rule.
749
+ */
750
+ FileStorage.prototype.dropDerivedFiles = function (file) {
751
+ return __awaiter(this, void 0, void 0, function () {
752
+ var seats, stale, system, forgotten, _i, stale_1, seat, _a, stale_2, seat;
753
+ return __generator(this, function (_b) {
754
+ switch (_b.label) {
755
+ case 0:
756
+ seats = __spreadArray(['copyForOthers'], FileVariantMaker_1.FILE_VARIANT_KINDS, true);
757
+ stale = seats.filter(function (seat) { var _a; return !!((_a = file[seat]) === null || _a === void 0 ? void 0 : _a._id); });
758
+ if (stale.length === 0) {
759
+ return [2 /*return*/];
760
+ }
761
+ system = (0, db_1.getDbAsSystem)();
762
+ forgotten = { id: file.id };
763
+ for (_i = 0, stale_1 = stale; _i < stale_1.length; _i++) {
764
+ seat = stale_1[_i];
765
+ forgotten[seat] = null;
766
+ }
767
+ return [4 /*yield*/, system.update(tables_1.tables.File, forgotten)];
768
+ case 1:
769
+ _b.sent();
770
+ _a = 0, stale_2 = stale;
771
+ _b.label = 2;
772
+ case 2:
773
+ if (!(_a < stale_2.length)) return [3 /*break*/, 5];
774
+ seat = stale_2[_a];
775
+ return [4 /*yield*/, system.delete(tables_1.tables.File, { id: file[seat]._id })];
776
+ case 3:
777
+ _b.sent();
778
+ _b.label = 4;
779
+ case 4:
780
+ _a++;
781
+ return [3 /*break*/, 2];
782
+ case 5: return [2 /*return*/];
783
+ }
784
+ });
785
+ });
786
+ };
787
+ /**
788
+ * THE answer a byte door gives a caller who does not get the file's bytes — a row that is not
789
+ * there, one this caller cannot read, or a copy that cannot be made for them: a 404 refusal in
790
+ * the same words every time, never the id, so the answer reveals nothing about existence (the
791
+ * service router sends `{ error: 'File not found' }`, the executor logs it at WARN, the routes
792
+ * send `404 File not found`).
793
+ */
794
+ FileStorage.notFound = function () {
795
+ return new service_1.ServiceRefusal(404, 'File not found');
796
+ };
797
+ /** The read path's derivations running in this process, by file and kind — see {@link deriveOnce}. */
798
+ FileStorage.derivations = new Map();
303
799
  return FileStorage;
304
800
  }());
305
801
  exports.FileStorage = FileStorage;