@puzzle-ui/media 0.0.0-stage → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +305 -2
- package/ai/instructions.md +70 -0
- package/ai/manifest.json +10 -0
- package/dist/LICENSE +21 -0
- package/dist/adapters-Bon320yF.js +481 -0
- package/dist/adapters-Bon320yF.js.map +1 -0
- package/dist/adapters-C4N2gqSK.d.cts +63 -0
- package/dist/adapters-DXycRsjJ.cjs +492 -0
- package/dist/adapters-DXycRsjJ.cjs.map +1 -0
- package/dist/adapters-DhPviL_C.d.ts +63 -0
- package/dist/browser/index.cjs +200 -0
- package/dist/browser/index.cjs.map +1 -0
- package/dist/browser/index.d.cts +89 -0
- package/dist/browser/index.d.ts +89 -0
- package/dist/browser/index.js +195 -0
- package/dist/browser/index.js.map +1 -0
- package/dist/image-processing-B1lRPpsg.cjs +444 -0
- package/dist/image-processing-B1lRPpsg.cjs.map +1 -0
- package/dist/image-processing-XkoQ8NT7.js +400 -0
- package/dist/image-processing-XkoQ8NT7.js.map +1 -0
- package/dist/image-worker.cjs +36 -0
- package/dist/image-worker.cjs.map +1 -0
- package/dist/image-worker.d.cts +1 -0
- package/dist/image-worker.d.ts +1 -0
- package/dist/image-worker.js +37 -0
- package/dist/image-worker.js.map +1 -0
- package/dist/index-8Seqy-LJ.d.ts +297 -0
- package/dist/index-BP0ikbAS.d.cts +297 -0
- package/dist/index.cjs +38 -0
- package/dist/index.d.cts +4 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/media-validation-By6karZu.cjs +361 -0
- package/dist/media-validation-By6karZu.cjs.map +1 -0
- package/dist/media-validation-OyjGVUq3.js +230 -0
- package/dist/media-validation-OyjGVUq3.js.map +1 -0
- package/dist/media.types-dzfu0Nep.d.cts +127 -0
- package/dist/media.types-dzfu0Nep.d.ts +127 -0
- package/dist/processing.types-CPaSB88L.d.ts +238 -0
- package/dist/processing.types-Dd2XT8Qr.d.cts +238 -0
- package/dist/src-8d6s1iWH.js +1286 -0
- package/dist/src-8d6s1iWH.js.map +1 -0
- package/dist/src-C7WU7ovP.cjs +1363 -0
- package/dist/src-C7WU7ovP.cjs.map +1 -0
- package/dist/testing/adapters.cjs +4 -0
- package/dist/testing/adapters.d.cts +2 -0
- package/dist/testing/adapters.d.ts +2 -0
- package/dist/testing/adapters.js +1 -0
- package/dist/testing/index.cjs +264 -0
- package/dist/testing/index.cjs.map +1 -0
- package/dist/testing/index.d.cts +14 -0
- package/dist/testing/index.d.ts +14 -0
- package/dist/testing/index.js +260 -0
- package/dist/testing/index.js.map +1 -0
- package/package.json +84 -4
|
@@ -0,0 +1,1286 @@
|
|
|
1
|
+
import { _ as MediaPermissionDeniedError, a as normalizeMediaObjectReference, c as validateMediaImageProfiles, d as MediaAssetConflictError, f as MediaCapabilityError, h as MediaNotFoundError, i as normalizeMediaHotspots, l as validateMediaVideoProfiles, n as normalizeMediaCrop, o as normalizeMediaTags, p as MediaChecksumMismatchError, r as normalizeMediaFocalPoint, s as validateMediaFileMetadata, t as normalizeMediaChecksum, u as InvalidMediaFileError, v as MediaProcessingError, x as MediaValidationError } from "./media-validation-OyjGVUq3.js";
|
|
2
|
+
// src/types/media.types.ts
|
|
3
|
+
const MEDIA_ASSET_STATUSES = [
|
|
4
|
+
"pending-upload",
|
|
5
|
+
"uploaded",
|
|
6
|
+
"processing",
|
|
7
|
+
"ready",
|
|
8
|
+
"failed",
|
|
9
|
+
"deleted"
|
|
10
|
+
];
|
|
11
|
+
const MEDIA_KINDS = [
|
|
12
|
+
"image",
|
|
13
|
+
"video",
|
|
14
|
+
"audio",
|
|
15
|
+
"document",
|
|
16
|
+
"other"
|
|
17
|
+
];
|
|
18
|
+
// src/services/collections.ts
|
|
19
|
+
const MEDIA_ASSETS_COLLECTION = "media_assets";
|
|
20
|
+
const MEDIA_FOLDERS_COLLECTION = "media_folders";
|
|
21
|
+
const MEDIA_ASSET_USAGES_COLLECTION = "media_asset_usages";
|
|
22
|
+
const registrations = /* @__PURE__ */ new WeakMap();
|
|
23
|
+
const isRecord = (value) => typeof value === "object" && value !== null;
|
|
24
|
+
const isDate = (value) => value instanceof Date && Number.isFinite(value.getTime());
|
|
25
|
+
const isStorageRecord = (value) => isRecord(value) && typeof value.id === "string" && typeof value.tenantId === "string" && isDate(value.createdAt) && isDate(value.updatedAt) && Number.isInteger(value.revision);
|
|
26
|
+
const isMediaAssetRecord = (value) => isStorageRecord(value) && typeof value.originalName === "string" && typeof value.displayName === "string" && typeof value.mimeType === "string" && Number.isSafeInteger(value.size) && (value.focalPoint === null || isRecord(value.focalPoint) && typeof value.focalPoint.x === "number" && Number.isFinite(value.focalPoint.x) && value.focalPoint.x >= 0 && value.focalPoint.x <= 1 && typeof value.focalPoint.y === "number" && Number.isFinite(value.focalPoint.y) && value.focalPoint.y >= 0 && value.focalPoint.y <= 1) && typeof value.object === "object" && value.object !== null && typeof value.object.key === "string";
|
|
27
|
+
const isMediaFolderRecord = (value) => isStorageRecord(value) && typeof value.name === "string" && (value.parentId === null || typeof value.parentId === "string");
|
|
28
|
+
const isMediaUsageRecord = (value) => isStorageRecord(value) && typeof value.assetId === "string" && typeof value.resourceType === "string" && typeof value.resourceId === "string" && typeof value.fieldKey === "string";
|
|
29
|
+
const registerMediaCollections = async (storage) => {
|
|
30
|
+
const existing = registrations.get(storage);
|
|
31
|
+
if (existing) {
|
|
32
|
+
await existing;
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
const registration = Promise.all([
|
|
36
|
+
storage.registerCollection({
|
|
37
|
+
name: MEDIA_ASSETS_COLLECTION,
|
|
38
|
+
schema: { validate: isMediaAssetRecord },
|
|
39
|
+
indexes: [
|
|
40
|
+
{
|
|
41
|
+
name: "by-tenant-folder",
|
|
42
|
+
fields: ["tenantId", "folderId"]
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
name: "by-tenant-status",
|
|
46
|
+
fields: ["tenantId", "status"]
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
name: "by-tenant-kind",
|
|
50
|
+
fields: ["tenantId", "kind"]
|
|
51
|
+
}
|
|
52
|
+
]
|
|
53
|
+
}),
|
|
54
|
+
storage.registerCollection({
|
|
55
|
+
name: MEDIA_FOLDERS_COLLECTION,
|
|
56
|
+
schema: { validate: isMediaFolderRecord },
|
|
57
|
+
indexes: [{
|
|
58
|
+
name: "unique-tenant-parent-name",
|
|
59
|
+
fields: [
|
|
60
|
+
"tenantId",
|
|
61
|
+
"parentId",
|
|
62
|
+
"name"
|
|
63
|
+
],
|
|
64
|
+
unique: true
|
|
65
|
+
}]
|
|
66
|
+
}),
|
|
67
|
+
storage.registerCollection({
|
|
68
|
+
name: MEDIA_ASSET_USAGES_COLLECTION,
|
|
69
|
+
schema: { validate: isMediaUsageRecord },
|
|
70
|
+
indexes: [{
|
|
71
|
+
name: "unique-asset-reference",
|
|
72
|
+
fields: [
|
|
73
|
+
"tenantId",
|
|
74
|
+
"assetId",
|
|
75
|
+
"resourceType",
|
|
76
|
+
"resourceId",
|
|
77
|
+
"fieldKey"
|
|
78
|
+
],
|
|
79
|
+
unique: true
|
|
80
|
+
}, {
|
|
81
|
+
name: "by-tenant-asset",
|
|
82
|
+
fields: ["tenantId", "assetId"]
|
|
83
|
+
}]
|
|
84
|
+
})
|
|
85
|
+
]).then(() => void 0);
|
|
86
|
+
registrations.set(storage, registration);
|
|
87
|
+
try {
|
|
88
|
+
await registration;
|
|
89
|
+
} catch (error) {
|
|
90
|
+
registrations.delete(storage);
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
// src/services/service-utils.ts
|
|
95
|
+
const createMediaId = (idFactory, prefix = "media") => {
|
|
96
|
+
if (idFactory) {
|
|
97
|
+
const id = idFactory();
|
|
98
|
+
if (typeof id !== "string" || id.trim() === "") throw new MediaValidationError("The configured ID factory returned an invalid ID.");
|
|
99
|
+
return id;
|
|
100
|
+
}
|
|
101
|
+
const randomUUID = globalThis.crypto?.randomUUID;
|
|
102
|
+
if (typeof randomUUID !== "function") throw new MediaCapabilityError("crypto.randomUUID");
|
|
103
|
+
return `${prefix}_${randomUUID.call(globalThis.crypto)}`;
|
|
104
|
+
};
|
|
105
|
+
const getMediaNow = (now) => {
|
|
106
|
+
const value = now?.() ?? /* @__PURE__ */ new Date();
|
|
107
|
+
if (!(value instanceof Date) || !Number.isFinite(value.getTime())) throw new MediaValidationError("The configured clock returned an invalid date.");
|
|
108
|
+
return value;
|
|
109
|
+
};
|
|
110
|
+
const assertTenantId = (tenantId) => {
|
|
111
|
+
if (typeof tenantId !== "string" || tenantId.trim() === "") throw new MediaValidationError("tenantId must be a non-empty string.");
|
|
112
|
+
};
|
|
113
|
+
const assertConditionalWrites = (storage) => {
|
|
114
|
+
assertStorageCapability(storage, "conditionalWrites");
|
|
115
|
+
};
|
|
116
|
+
const assertStorageCapability = (storage, capability) => {
|
|
117
|
+
if (!storage.getCapabilities().capabilities[capability]) throw new MediaCapabilityError(capability);
|
|
118
|
+
};
|
|
119
|
+
const makeStorageCondition = (expectedRevision) => {
|
|
120
|
+
if (!Number.isInteger(expectedRevision) || expectedRevision < 1) throw new MediaValidationError("expectedRevision must be a positive integer.");
|
|
121
|
+
return { expectedRevision };
|
|
122
|
+
};
|
|
123
|
+
const normalizeDisplayName = (value) => {
|
|
124
|
+
if (typeof value !== "string") throw new MediaValidationError("A media name must be a string.");
|
|
125
|
+
const name = value.replace(/[\u0000-\u001f\u007f]/g, "").trim();
|
|
126
|
+
if (name.length === 0 || name.length > 255) throw new MediaValidationError("A media name must contain 1 to 255 printable characters.");
|
|
127
|
+
return name;
|
|
128
|
+
};
|
|
129
|
+
const normalizeOriginalName = (value) => {
|
|
130
|
+
if (typeof value !== "string") throw new MediaValidationError("originalName must be a string.");
|
|
131
|
+
const name = (value.split(/[\\/]/).at(-1) ?? "").replace(/[\u0000-\u001f\u007f]/g, "").trim();
|
|
132
|
+
if (name.length === 0 || name.length > 1024) throw new MediaValidationError("originalName must be a non-empty file name.");
|
|
133
|
+
return name;
|
|
134
|
+
};
|
|
135
|
+
// src/services/asset.service.ts
|
|
136
|
+
const isPresent = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
|
|
137
|
+
const validatePageSize$1 = (first) => {
|
|
138
|
+
const value = first ?? 50;
|
|
139
|
+
if (!Number.isInteger(value) || value < 1 || value > 100) throw new MediaValidationError("first must be an integer from 1 to 100.");
|
|
140
|
+
return value;
|
|
141
|
+
};
|
|
142
|
+
const normalizeOptionalText = (value, field) => {
|
|
143
|
+
if (value === null) return null;
|
|
144
|
+
if (typeof value !== "string") throw new MediaValidationError(`${field} must be a string or null.`);
|
|
145
|
+
return value;
|
|
146
|
+
};
|
|
147
|
+
const objectKey = (object) => `${object.key}\u0000${object.versionId ?? ""}`;
|
|
148
|
+
const createMediaAssetService = (options) => {
|
|
149
|
+
const { storage, objectStorage } = options;
|
|
150
|
+
const ready = registerMediaCollections(storage);
|
|
151
|
+
const getAnyAsset = async (tenantId, assetId) => {
|
|
152
|
+
assertTenantId(tenantId);
|
|
153
|
+
const asset = await storage.findById(MEDIA_ASSETS_COLLECTION, assetId);
|
|
154
|
+
if (!asset || asset.tenantId !== tenantId) throw new MediaNotFoundError("Media asset");
|
|
155
|
+
return asset;
|
|
156
|
+
};
|
|
157
|
+
const getActiveAsset = async (tenantId, assetId) => {
|
|
158
|
+
const asset = await getAnyAsset(tenantId, assetId);
|
|
159
|
+
if (asset.status === "deleted") throw new MediaNotFoundError("Media asset");
|
|
160
|
+
return asset;
|
|
161
|
+
};
|
|
162
|
+
const ensureFolder = async (tenantId, folderId) => {
|
|
163
|
+
if (folderId === null) return;
|
|
164
|
+
const folder = await storage.findById(MEDIA_FOLDERS_COLLECTION, folderId);
|
|
165
|
+
if (!folder || folder.tenantId !== tenantId || folder.deletedAt) throw new MediaNotFoundError("Media folder");
|
|
166
|
+
};
|
|
167
|
+
const listUsage = async (tenantId, assetId) => {
|
|
168
|
+
await ready;
|
|
169
|
+
assertTenantId(tenantId);
|
|
170
|
+
return storage.findMany(MEDIA_ASSET_USAGES_COLLECTION, { where: {
|
|
171
|
+
tenantId: {
|
|
172
|
+
operator: "eq",
|
|
173
|
+
value: tenantId
|
|
174
|
+
},
|
|
175
|
+
assetId: {
|
|
176
|
+
operator: "eq",
|
|
177
|
+
value: assetId
|
|
178
|
+
}
|
|
179
|
+
} });
|
|
180
|
+
};
|
|
181
|
+
const create = async (input) => {
|
|
182
|
+
await ready;
|
|
183
|
+
assertTenantId(input.tenantId);
|
|
184
|
+
const metadata = validateMediaFileMetadata(input.metadata);
|
|
185
|
+
const originalName = normalizeOriginalName(input.originalName);
|
|
186
|
+
const displayName = normalizeDisplayName(input.displayName ?? originalName);
|
|
187
|
+
const object = normalizeMediaObjectReference(input.object);
|
|
188
|
+
const storedObject = await objectStorage.getObjectMetadata(object);
|
|
189
|
+
if (!storedObject || storedObject.tenantId !== input.tenantId) throw new MediaNotFoundError("Uploaded media object");
|
|
190
|
+
if (storedObject.size !== metadata.size || storedObject.mimeType.toLowerCase() !== metadata.mimeType) throw new InvalidMediaFileError("Asset metadata does not match the completed object upload.");
|
|
191
|
+
if (metadata.checksum && storedObject.checksum && storedObject.checksum.value !== metadata.checksum.value) throw new MediaChecksumMismatchError();
|
|
192
|
+
const verifiedMetadata = {
|
|
193
|
+
...metadata,
|
|
194
|
+
...storedObject.checksum ? { checksum: storedObject.checksum } : {}
|
|
195
|
+
};
|
|
196
|
+
const folderId = input.folderId ?? null;
|
|
197
|
+
await ensureFolder(input.tenantId, folderId);
|
|
198
|
+
const now = getMediaNow(options.now);
|
|
199
|
+
const insert = {
|
|
200
|
+
id: createMediaId(options.idFactory, "asset"),
|
|
201
|
+
tenantId: input.tenantId,
|
|
202
|
+
folderId,
|
|
203
|
+
originalName,
|
|
204
|
+
displayName,
|
|
205
|
+
...verifiedMetadata,
|
|
206
|
+
object,
|
|
207
|
+
status: "uploaded",
|
|
208
|
+
altText: normalizeOptionalText(input.altText ?? null, "altText"),
|
|
209
|
+
caption: normalizeOptionalText(input.caption ?? null, "caption"),
|
|
210
|
+
title: normalizeOptionalText(input.title ?? null, "title"),
|
|
211
|
+
description: normalizeOptionalText(input.description ?? null, "description"),
|
|
212
|
+
tags: normalizeMediaTags(input.tags ?? []),
|
|
213
|
+
crop: input.crop == null ? null : normalizeMediaCrop(input.crop),
|
|
214
|
+
focalPoint: input.focalPoint == null ? null : normalizeMediaFocalPoint(input.focalPoint),
|
|
215
|
+
hotspots: normalizeMediaHotspots(input.hotspots ?? []),
|
|
216
|
+
variants: [],
|
|
217
|
+
processingError: null,
|
|
218
|
+
processingJobId: null,
|
|
219
|
+
previousStatus: null,
|
|
220
|
+
createdAt: now,
|
|
221
|
+
updatedAt: now,
|
|
222
|
+
createdBy: input.actorId ?? null,
|
|
223
|
+
updatedBy: input.actorId ?? null,
|
|
224
|
+
deletedAt: null,
|
|
225
|
+
revision: 1
|
|
226
|
+
};
|
|
227
|
+
const asset = await storage.insert(MEDIA_ASSETS_COLLECTION, insert);
|
|
228
|
+
if (folderId !== null) try {
|
|
229
|
+
await ensureFolder(input.tenantId, folderId);
|
|
230
|
+
} catch {
|
|
231
|
+
await storage.delete(MEDIA_ASSETS_COLLECTION, asset.id, makeStorageCondition(asset.revision));
|
|
232
|
+
throw new MediaAssetConflictError("The destination folder changed while the asset was being created.");
|
|
233
|
+
}
|
|
234
|
+
return asset;
|
|
235
|
+
};
|
|
236
|
+
const get = async (tenantId, assetId, options) => {
|
|
237
|
+
await ready;
|
|
238
|
+
return options?.includeDeleted === true ? getAnyAsset(tenantId, assetId) : getActiveAsset(tenantId, assetId);
|
|
239
|
+
};
|
|
240
|
+
const list = async (input) => {
|
|
241
|
+
await ready;
|
|
242
|
+
assertTenantId(input.tenantId);
|
|
243
|
+
assertStorageCapability(storage, "cursorPagination");
|
|
244
|
+
const first = validatePageSize$1(input.first);
|
|
245
|
+
const where = { tenantId: {
|
|
246
|
+
operator: "eq",
|
|
247
|
+
value: input.tenantId
|
|
248
|
+
} };
|
|
249
|
+
if (input.folderId !== void 0) Object.assign(where, { folderId: {
|
|
250
|
+
operator: "eq",
|
|
251
|
+
value: input.folderId
|
|
252
|
+
} });
|
|
253
|
+
if (input.kind !== void 0) Object.assign(where, { kind: {
|
|
254
|
+
operator: "eq",
|
|
255
|
+
value: input.kind
|
|
256
|
+
} });
|
|
257
|
+
if (input.status !== void 0) Object.assign(where, { status: {
|
|
258
|
+
operator: "eq",
|
|
259
|
+
value: input.status
|
|
260
|
+
} });
|
|
261
|
+
else Object.assign(where, { status: {
|
|
262
|
+
operator: "ne",
|
|
263
|
+
value: "deleted"
|
|
264
|
+
} });
|
|
265
|
+
const orderBy = [{
|
|
266
|
+
field: input.orderBy ?? "createdAt",
|
|
267
|
+
direction: input.direction ?? "desc"
|
|
268
|
+
}];
|
|
269
|
+
const tagsAny = input.tagsAny === void 0 ? void 0 : normalizeMediaTags(input.tagsAny);
|
|
270
|
+
const tagsAll = input.tagsAll === void 0 ? void 0 : normalizeMediaTags(input.tagsAll);
|
|
271
|
+
const checksum = input.checksum === void 0 ? void 0 : normalizeMediaChecksum(input.checksum);
|
|
272
|
+
if (!((tagsAny?.length ?? 0) > 0 || (tagsAll?.length ?? 0) > 0 || checksum !== void 0)) {
|
|
273
|
+
const page = await storage.findPage(MEDIA_ASSETS_COLLECTION, {
|
|
274
|
+
where,
|
|
275
|
+
orderBy,
|
|
276
|
+
first,
|
|
277
|
+
...input.after ? { after: { value: input.after } } : {}
|
|
278
|
+
});
|
|
279
|
+
return {
|
|
280
|
+
items: page.items,
|
|
281
|
+
nextCursor: page.nextCursor?.value ?? null
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
const items = [];
|
|
285
|
+
let cursor = input.after;
|
|
286
|
+
let nextCursor = null;
|
|
287
|
+
let scanned = 0;
|
|
288
|
+
const maxScan = 5e3;
|
|
289
|
+
while (scanned < maxScan) {
|
|
290
|
+
const cursorBefore = cursor;
|
|
291
|
+
const page = await storage.findPage(MEDIA_ASSETS_COLLECTION, {
|
|
292
|
+
where,
|
|
293
|
+
orderBy,
|
|
294
|
+
first: 1,
|
|
295
|
+
...cursor ? { after: { value: cursor } } : {}
|
|
296
|
+
});
|
|
297
|
+
const asset = page.items[0];
|
|
298
|
+
if (!asset) {
|
|
299
|
+
nextCursor = null;
|
|
300
|
+
break;
|
|
301
|
+
}
|
|
302
|
+
scanned += 1;
|
|
303
|
+
cursor = page.nextCursor?.value ?? void 0;
|
|
304
|
+
const tagsMatch = (tagsAny === void 0 || tagsAny.length === 0 || tagsAny.some((tag) => asset.tags.includes(tag))) && (tagsAll === void 0 || tagsAll.every((tag) => asset.tags.includes(tag)));
|
|
305
|
+
const checksumMatch = checksum === void 0 || asset.checksum?.algorithm === checksum.algorithm && asset.checksum?.value === checksum.value;
|
|
306
|
+
if (tagsMatch && checksumMatch) {
|
|
307
|
+
if (items.length === first) {
|
|
308
|
+
nextCursor = cursorBefore ?? null;
|
|
309
|
+
break;
|
|
310
|
+
}
|
|
311
|
+
items.push(asset);
|
|
312
|
+
}
|
|
313
|
+
if (!cursor) {
|
|
314
|
+
nextCursor = null;
|
|
315
|
+
break;
|
|
316
|
+
}
|
|
317
|
+
nextCursor = cursor;
|
|
318
|
+
}
|
|
319
|
+
return {
|
|
320
|
+
items,
|
|
321
|
+
nextCursor
|
|
322
|
+
};
|
|
323
|
+
};
|
|
324
|
+
const update = async (input) => {
|
|
325
|
+
await ready;
|
|
326
|
+
assertTenantId(input.tenantId);
|
|
327
|
+
assertConditionalWrites(storage);
|
|
328
|
+
const asset = await getActiveAsset(input.tenantId, input.assetId);
|
|
329
|
+
if (asset.status === "processing") throw new MediaAssetConflictError("Asset metadata cannot be changed while processing is active.");
|
|
330
|
+
const changes = {
|
|
331
|
+
updatedAt: getMediaNow(options.now),
|
|
332
|
+
updatedBy: input.actorId ?? null
|
|
333
|
+
};
|
|
334
|
+
if (isPresent(input, "folderId")) {
|
|
335
|
+
const folderId = input.folderId ?? null;
|
|
336
|
+
await ensureFolder(input.tenantId, folderId);
|
|
337
|
+
Object.assign(changes, { folderId });
|
|
338
|
+
}
|
|
339
|
+
if (input.displayName !== void 0) Object.assign(changes, { displayName: normalizeDisplayName(input.displayName) });
|
|
340
|
+
for (const key of [
|
|
341
|
+
"altText",
|
|
342
|
+
"caption",
|
|
343
|
+
"title",
|
|
344
|
+
"description"
|
|
345
|
+
]) if (isPresent(input, key)) Object.assign(changes, { [key]: normalizeOptionalText(input[key] ?? null, key) });
|
|
346
|
+
if (input.tags !== void 0) Object.assign(changes, { tags: normalizeMediaTags(input.tags) });
|
|
347
|
+
if (isPresent(input, "crop")) Object.assign(changes, { crop: input.crop == null ? null : normalizeMediaCrop(input.crop) });
|
|
348
|
+
if (input.focalPoint !== void 0) Object.assign(changes, { focalPoint: input.focalPoint === null ? null : normalizeMediaFocalPoint(input.focalPoint) });
|
|
349
|
+
if (input.hotspots !== void 0) Object.assign(changes, { hotspots: normalizeMediaHotspots(input.hotspots) });
|
|
350
|
+
const updated = await storage.update(MEDIA_ASSETS_COLLECTION, asset.id, changes, makeStorageCondition(input.expectedRevision));
|
|
351
|
+
if (!updated) throw new MediaAssetConflictError("The asset changed before its metadata could be updated.");
|
|
352
|
+
return updated;
|
|
353
|
+
};
|
|
354
|
+
const softDelete = async (input) => {
|
|
355
|
+
await ready;
|
|
356
|
+
assertTenantId(input.tenantId);
|
|
357
|
+
assertConditionalWrites(storage);
|
|
358
|
+
const asset = await getActiveAsset(input.tenantId, input.assetId);
|
|
359
|
+
if (asset.status === "processing") throw new MediaAssetConflictError("An asset cannot be deleted while processing is active.");
|
|
360
|
+
if (await storage.findOne("media_asset_usages", { where: {
|
|
361
|
+
tenantId: {
|
|
362
|
+
operator: "eq",
|
|
363
|
+
value: input.tenantId
|
|
364
|
+
},
|
|
365
|
+
assetId: {
|
|
366
|
+
operator: "eq",
|
|
367
|
+
value: asset.id
|
|
368
|
+
}
|
|
369
|
+
} })) throw new MediaAssetConflictError("An asset referenced by content cannot be deleted until its usages are removed.");
|
|
370
|
+
const now = getMediaNow(options.now);
|
|
371
|
+
const updated = await storage.update(MEDIA_ASSETS_COLLECTION, asset.id, {
|
|
372
|
+
status: "deleted",
|
|
373
|
+
previousStatus: asset.status === "deleted" ? null : asset.status,
|
|
374
|
+
deletedAt: now,
|
|
375
|
+
updatedAt: now,
|
|
376
|
+
updatedBy: input.actorId ?? null
|
|
377
|
+
}, makeStorageCondition(input.expectedRevision));
|
|
378
|
+
if (!updated) throw new MediaAssetConflictError("The asset changed before it could be deleted.");
|
|
379
|
+
if (await storage.findOne("media_asset_usages", { where: {
|
|
380
|
+
tenantId: {
|
|
381
|
+
operator: "eq",
|
|
382
|
+
value: input.tenantId
|
|
383
|
+
},
|
|
384
|
+
assetId: {
|
|
385
|
+
operator: "eq",
|
|
386
|
+
value: asset.id
|
|
387
|
+
}
|
|
388
|
+
} })) {
|
|
389
|
+
if (!await storage.update("media_assets", asset.id, {
|
|
390
|
+
status: asset.status,
|
|
391
|
+
previousStatus: null,
|
|
392
|
+
processingJobId: null,
|
|
393
|
+
deletedAt: null,
|
|
394
|
+
updatedAt: getMediaNow(options.now),
|
|
395
|
+
updatedBy: input.actorId ?? null
|
|
396
|
+
}, makeStorageCondition(updated.revision))) throw new MediaAssetConflictError("A media usage was added while the asset was being deleted.");
|
|
397
|
+
throw new MediaAssetConflictError("An asset referenced by content cannot be deleted until its usages are removed.");
|
|
398
|
+
}
|
|
399
|
+
return updated;
|
|
400
|
+
};
|
|
401
|
+
const restore = async (input) => {
|
|
402
|
+
await ready;
|
|
403
|
+
assertTenantId(input.tenantId);
|
|
404
|
+
assertConditionalWrites(storage);
|
|
405
|
+
const asset = await getAnyAsset(input.tenantId, input.assetId);
|
|
406
|
+
if (asset.status !== "deleted") throw new MediaAssetConflictError("Only a deleted asset can be restored.");
|
|
407
|
+
await ensureFolder(input.tenantId, asset.folderId);
|
|
408
|
+
const now = getMediaNow(options.now);
|
|
409
|
+
const updated = await storage.update(MEDIA_ASSETS_COLLECTION, asset.id, {
|
|
410
|
+
status: asset.previousStatus ?? "uploaded",
|
|
411
|
+
previousStatus: null,
|
|
412
|
+
deletedAt: null,
|
|
413
|
+
updatedAt: now,
|
|
414
|
+
updatedBy: input.actorId ?? null
|
|
415
|
+
}, makeStorageCondition(input.expectedRevision));
|
|
416
|
+
if (!updated) throw new MediaAssetConflictError("The asset changed before it could be restored.");
|
|
417
|
+
return updated;
|
|
418
|
+
};
|
|
419
|
+
const permanentlyDelete = async (input) => {
|
|
420
|
+
await ready;
|
|
421
|
+
assertTenantId(input.tenantId);
|
|
422
|
+
assertConditionalWrites(storage);
|
|
423
|
+
const asset = await getAnyAsset(input.tenantId, input.assetId);
|
|
424
|
+
if (asset.status !== "deleted") throw new MediaAssetConflictError("An asset must be soft-deleted before permanent deletion.");
|
|
425
|
+
if ((await listUsage(input.tenantId, asset.id)).length > 0) throw new MediaAssetConflictError("A referenced asset cannot be permanently deleted.");
|
|
426
|
+
const objects = /* @__PURE__ */ new Map();
|
|
427
|
+
objects.set(objectKey(asset.object), asset.object);
|
|
428
|
+
for (const variant of asset.variants) if (variant.object) objects.set(objectKey(variant.object), variant.object);
|
|
429
|
+
if (!await storage.delete("media_assets", asset.id, makeStorageCondition(input.expectedRevision))) throw new MediaAssetConflictError("The asset changed before it could be permanently deleted.");
|
|
430
|
+
const objectDeletionFailures = [];
|
|
431
|
+
for (const object of objects.values()) try {
|
|
432
|
+
await objectStorage.deleteObject(object);
|
|
433
|
+
} catch (error) {
|
|
434
|
+
objectDeletionFailures.push({
|
|
435
|
+
key: object.key,
|
|
436
|
+
error: error instanceof Error ? error.message : "Object deletion failed."
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
return {
|
|
440
|
+
deleted: true,
|
|
441
|
+
objectDeletionFailures
|
|
442
|
+
};
|
|
443
|
+
};
|
|
444
|
+
const registerUsage = async (input) => {
|
|
445
|
+
await ready;
|
|
446
|
+
assertTenantId(input.tenantId);
|
|
447
|
+
assertStorageCapability(storage, "uniqueConstraints");
|
|
448
|
+
const asset = await getActiveAsset(input.tenantId, input.assetId);
|
|
449
|
+
for (const [field, value] of [["resourceType", input.resourceType], ["resourceId", input.resourceId]]) if (typeof value !== "string" || value.trim() === "") throw new MediaValidationError(`${field} must be a non-empty string.`);
|
|
450
|
+
const fieldKey = input.fieldKey ?? "";
|
|
451
|
+
if (typeof fieldKey !== "string") throw new MediaValidationError("fieldKey must be a string.");
|
|
452
|
+
const existing = await storage.findOne(MEDIA_ASSET_USAGES_COLLECTION, { where: {
|
|
453
|
+
tenantId: {
|
|
454
|
+
operator: "eq",
|
|
455
|
+
value: input.tenantId
|
|
456
|
+
},
|
|
457
|
+
assetId: {
|
|
458
|
+
operator: "eq",
|
|
459
|
+
value: asset.id
|
|
460
|
+
},
|
|
461
|
+
resourceType: {
|
|
462
|
+
operator: "eq",
|
|
463
|
+
value: input.resourceType
|
|
464
|
+
},
|
|
465
|
+
resourceId: {
|
|
466
|
+
operator: "eq",
|
|
467
|
+
value: input.resourceId
|
|
468
|
+
},
|
|
469
|
+
fieldKey: {
|
|
470
|
+
operator: "eq",
|
|
471
|
+
value: fieldKey
|
|
472
|
+
}
|
|
473
|
+
} });
|
|
474
|
+
if (existing) return existing;
|
|
475
|
+
const now = getMediaNow(options.now);
|
|
476
|
+
const insert = {
|
|
477
|
+
id: createMediaId(options.idFactory, "usage"),
|
|
478
|
+
tenantId: input.tenantId,
|
|
479
|
+
assetId: asset.id,
|
|
480
|
+
resourceType: input.resourceType,
|
|
481
|
+
resourceId: input.resourceId,
|
|
482
|
+
fieldKey,
|
|
483
|
+
createdAt: now,
|
|
484
|
+
updatedAt: now,
|
|
485
|
+
createdBy: input.actorId ?? null,
|
|
486
|
+
revision: 1
|
|
487
|
+
};
|
|
488
|
+
const inserted = await storage.insert(MEDIA_ASSET_USAGES_COLLECTION, insert);
|
|
489
|
+
const latestAsset = await storage.findById(MEDIA_ASSETS_COLLECTION, asset.id);
|
|
490
|
+
if (!latestAsset || latestAsset.tenantId !== input.tenantId || latestAsset.status === "deleted") {
|
|
491
|
+
await storage.delete(MEDIA_ASSET_USAGES_COLLECTION, inserted.id, makeStorageCondition(inserted.revision));
|
|
492
|
+
throw new MediaAssetConflictError("The asset changed before its usage could be registered.");
|
|
493
|
+
}
|
|
494
|
+
return inserted;
|
|
495
|
+
};
|
|
496
|
+
const removeUsage = async (input) => {
|
|
497
|
+
await ready;
|
|
498
|
+
assertTenantId(input.tenantId);
|
|
499
|
+
if (typeof input.resourceType !== "string" || typeof input.resourceId !== "string") throw new MediaValidationError("A usage requires resourceType and resourceId.");
|
|
500
|
+
return storage.deleteMany(MEDIA_ASSET_USAGES_COLLECTION, { where: {
|
|
501
|
+
tenantId: {
|
|
502
|
+
operator: "eq",
|
|
503
|
+
value: input.tenantId
|
|
504
|
+
},
|
|
505
|
+
assetId: {
|
|
506
|
+
operator: "eq",
|
|
507
|
+
value: input.assetId
|
|
508
|
+
},
|
|
509
|
+
resourceType: {
|
|
510
|
+
operator: "eq",
|
|
511
|
+
value: input.resourceType
|
|
512
|
+
},
|
|
513
|
+
resourceId: {
|
|
514
|
+
operator: "eq",
|
|
515
|
+
value: input.resourceId
|
|
516
|
+
},
|
|
517
|
+
fieldKey: {
|
|
518
|
+
operator: "eq",
|
|
519
|
+
value: input.fieldKey ?? ""
|
|
520
|
+
}
|
|
521
|
+
} });
|
|
522
|
+
};
|
|
523
|
+
return {
|
|
524
|
+
ready,
|
|
525
|
+
create,
|
|
526
|
+
get,
|
|
527
|
+
list,
|
|
528
|
+
update,
|
|
529
|
+
softDelete,
|
|
530
|
+
restore,
|
|
531
|
+
permanentlyDelete,
|
|
532
|
+
registerUsage,
|
|
533
|
+
removeUsage,
|
|
534
|
+
listUsage
|
|
535
|
+
};
|
|
536
|
+
};
|
|
537
|
+
const cleanupOrphanedMediaObjects = async (options) => {
|
|
538
|
+
if (!Number.isFinite(options.olderThan.getTime())) throw new MediaValidationError("olderThan must be a valid date.");
|
|
539
|
+
const maxObjects = options.maxObjects ?? 500;
|
|
540
|
+
if (!Number.isInteger(maxObjects) || maxObjects < 1 || maxObjects > 1e4) throw new MediaValidationError("maxObjects must be an integer from 1 to 10000.");
|
|
541
|
+
await registerMediaCollections(options.storage);
|
|
542
|
+
const assets = await options.storage.findMany(MEDIA_ASSETS_COLLECTION);
|
|
543
|
+
const referenced = /* @__PURE__ */ new Set();
|
|
544
|
+
for (const asset of assets) {
|
|
545
|
+
referenced.add(objectKey(asset.object));
|
|
546
|
+
for (const variant of asset.variants) if (variant.object) referenced.add(objectKey(variant.object));
|
|
547
|
+
}
|
|
548
|
+
let cursor;
|
|
549
|
+
let examined = 0;
|
|
550
|
+
let deleted = 0;
|
|
551
|
+
let complete = true;
|
|
552
|
+
const failures = [];
|
|
553
|
+
while (examined < maxObjects) {
|
|
554
|
+
const first = Math.min(100, maxObjects - examined);
|
|
555
|
+
const page = await options.objectStorage.listObjects({
|
|
556
|
+
first,
|
|
557
|
+
olderThan: options.olderThan,
|
|
558
|
+
...cursor ? { cursor } : {}
|
|
559
|
+
});
|
|
560
|
+
if (page.items.length === 0) break;
|
|
561
|
+
for (const item of page.items) {
|
|
562
|
+
examined += 1;
|
|
563
|
+
if (referenced.has(objectKey(item.object))) continue;
|
|
564
|
+
try {
|
|
565
|
+
if (await options.objectStorage.deleteObject(item.object)) deleted += 1;
|
|
566
|
+
} catch (error) {
|
|
567
|
+
failures.push({
|
|
568
|
+
key: item.object.key,
|
|
569
|
+
error: error instanceof Error ? error.message : "Object deletion failed."
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
cursor = page.nextCursor ?? void 0;
|
|
574
|
+
if (!cursor) break;
|
|
575
|
+
}
|
|
576
|
+
if (cursor) complete = false;
|
|
577
|
+
return {
|
|
578
|
+
examined,
|
|
579
|
+
deleted,
|
|
580
|
+
failures,
|
|
581
|
+
complete
|
|
582
|
+
};
|
|
583
|
+
};
|
|
584
|
+
const cleanupExpiredMediaUploads = async (options) => {
|
|
585
|
+
const first = options.first ?? 100;
|
|
586
|
+
if (!Number.isFinite(options.before.getTime())) throw new MediaValidationError("before must be a valid date.");
|
|
587
|
+
if (!Number.isInteger(first) || first < 1 || first > 1e3) throw new MediaValidationError("first must be an integer from 1 to 1000.");
|
|
588
|
+
const sessions = await options.objectStorage.listExpiredUploadSessions(options.before, first);
|
|
589
|
+
let aborted = 0;
|
|
590
|
+
const failures = [];
|
|
591
|
+
for (const session of sessions) try {
|
|
592
|
+
if (await options.objectStorage.abortUpload(session.id)) aborted += 1;
|
|
593
|
+
} catch (error) {
|
|
594
|
+
failures.push({
|
|
595
|
+
sessionId: session.id,
|
|
596
|
+
error: error instanceof Error ? error.message : "Upload cleanup failed."
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
return {
|
|
600
|
+
examined: sessions.length,
|
|
601
|
+
aborted,
|
|
602
|
+
failures
|
|
603
|
+
};
|
|
604
|
+
};
|
|
605
|
+
// src/services/folder.service.ts
|
|
606
|
+
const validatePageSize = (first) => {
|
|
607
|
+
const value = first ?? 50;
|
|
608
|
+
if (!Number.isInteger(value) || value < 1 || value > 100) throw new MediaValidationError("first must be an integer from 1 to 100.");
|
|
609
|
+
return value;
|
|
610
|
+
};
|
|
611
|
+
const createMediaFolderService = (options) => {
|
|
612
|
+
const { storage } = options;
|
|
613
|
+
const ready = registerMediaCollections(storage);
|
|
614
|
+
const getActiveFolder = async (tenantId, folderId) => {
|
|
615
|
+
assertTenantId(tenantId);
|
|
616
|
+
const folder = await storage.findById(MEDIA_FOLDERS_COLLECTION, folderId);
|
|
617
|
+
if (!folder || folder.tenantId !== tenantId || folder.deletedAt) throw new MediaNotFoundError("Media folder");
|
|
618
|
+
return folder;
|
|
619
|
+
};
|
|
620
|
+
const ensureParent = async (tenantId, parentId) => {
|
|
621
|
+
if (parentId !== null) await getActiveFolder(tenantId, parentId);
|
|
622
|
+
};
|
|
623
|
+
const ensureSiblingNameAvailable = async (tenantId, parentId, name, exceptId) => {
|
|
624
|
+
assertStorageCapability(storage, "uniqueConstraints");
|
|
625
|
+
const existing = await storage.findOne(MEDIA_FOLDERS_COLLECTION, { where: {
|
|
626
|
+
tenantId: {
|
|
627
|
+
operator: "eq",
|
|
628
|
+
value: tenantId
|
|
629
|
+
},
|
|
630
|
+
parentId: {
|
|
631
|
+
operator: "eq",
|
|
632
|
+
value: parentId
|
|
633
|
+
},
|
|
634
|
+
name: {
|
|
635
|
+
operator: "eq",
|
|
636
|
+
value: name
|
|
637
|
+
},
|
|
638
|
+
deletedAt: {
|
|
639
|
+
operator: "eq",
|
|
640
|
+
value: null
|
|
641
|
+
}
|
|
642
|
+
} });
|
|
643
|
+
if (existing && existing.id !== exceptId) throw new MediaAssetConflictError("A folder with this name already exists in the selected parent.");
|
|
644
|
+
};
|
|
645
|
+
const get = async (tenantId, folderId) => {
|
|
646
|
+
await ready;
|
|
647
|
+
return getActiveFolder(tenantId, folderId);
|
|
648
|
+
};
|
|
649
|
+
const create = async (input) => {
|
|
650
|
+
await ready;
|
|
651
|
+
assertTenantId(input.tenantId);
|
|
652
|
+
const name = normalizeDisplayName(input.name);
|
|
653
|
+
const parentId = input.parentId ?? null;
|
|
654
|
+
await ensureParent(input.tenantId, parentId);
|
|
655
|
+
await ensureSiblingNameAvailable(input.tenantId, parentId, name);
|
|
656
|
+
const now = getMediaNow(options.now);
|
|
657
|
+
const insert = {
|
|
658
|
+
id: createMediaId(options.idFactory, "folder"),
|
|
659
|
+
tenantId: input.tenantId,
|
|
660
|
+
parentId,
|
|
661
|
+
name,
|
|
662
|
+
createdAt: now,
|
|
663
|
+
updatedAt: now,
|
|
664
|
+
createdBy: input.actorId ?? null,
|
|
665
|
+
updatedBy: input.actorId ?? null,
|
|
666
|
+
deletedAt: null,
|
|
667
|
+
revision: 1
|
|
668
|
+
};
|
|
669
|
+
const folder = await storage.insert(MEDIA_FOLDERS_COLLECTION, insert);
|
|
670
|
+
if (parentId !== null) try {
|
|
671
|
+
await ensureParent(input.tenantId, parentId);
|
|
672
|
+
} catch {
|
|
673
|
+
await storage.delete(MEDIA_FOLDERS_COLLECTION, folder.id, makeStorageCondition(folder.revision));
|
|
674
|
+
throw new MediaAssetConflictError("The parent folder changed while the folder was being created.");
|
|
675
|
+
}
|
|
676
|
+
return folder;
|
|
677
|
+
};
|
|
678
|
+
const list = async (input) => {
|
|
679
|
+
await ready;
|
|
680
|
+
assertTenantId(input.tenantId);
|
|
681
|
+
assertStorageCapability(storage, "cursorPagination");
|
|
682
|
+
const first = validatePageSize(input.first);
|
|
683
|
+
const page = await storage.findPage(MEDIA_FOLDERS_COLLECTION, {
|
|
684
|
+
where: {
|
|
685
|
+
tenantId: {
|
|
686
|
+
operator: "eq",
|
|
687
|
+
value: input.tenantId
|
|
688
|
+
},
|
|
689
|
+
parentId: {
|
|
690
|
+
operator: "eq",
|
|
691
|
+
value: input.parentId ?? null
|
|
692
|
+
},
|
|
693
|
+
deletedAt: {
|
|
694
|
+
operator: "eq",
|
|
695
|
+
value: null
|
|
696
|
+
}
|
|
697
|
+
},
|
|
698
|
+
orderBy: [{
|
|
699
|
+
field: "name",
|
|
700
|
+
direction: "asc"
|
|
701
|
+
}],
|
|
702
|
+
first,
|
|
703
|
+
...input.after ? { after: { value: input.after } } : {}
|
|
704
|
+
});
|
|
705
|
+
return {
|
|
706
|
+
items: page.items,
|
|
707
|
+
nextCursor: page.nextCursor?.value ?? null
|
|
708
|
+
};
|
|
709
|
+
};
|
|
710
|
+
const rename = async (input) => {
|
|
711
|
+
await ready;
|
|
712
|
+
assertTenantId(input.tenantId);
|
|
713
|
+
assertConditionalWrites(storage);
|
|
714
|
+
const folder = await getActiveFolder(input.tenantId, input.folderId);
|
|
715
|
+
const name = normalizeDisplayName(input.name);
|
|
716
|
+
await ensureSiblingNameAvailable(input.tenantId, folder.parentId, name, folder.id);
|
|
717
|
+
const updated = await storage.update(MEDIA_FOLDERS_COLLECTION, folder.id, {
|
|
718
|
+
name,
|
|
719
|
+
updatedAt: getMediaNow(options.now),
|
|
720
|
+
updatedBy: input.actorId ?? null
|
|
721
|
+
}, makeStorageCondition(input.expectedRevision));
|
|
722
|
+
if (!updated) throw new MediaAssetConflictError("The folder changed before it could be renamed.");
|
|
723
|
+
return updated;
|
|
724
|
+
};
|
|
725
|
+
const move = async (input) => {
|
|
726
|
+
await ready;
|
|
727
|
+
assertTenantId(input.tenantId);
|
|
728
|
+
assertConditionalWrites(storage);
|
|
729
|
+
const folder = await getActiveFolder(input.tenantId, input.folderId);
|
|
730
|
+
await ensureParent(input.tenantId, input.parentId);
|
|
731
|
+
await ensureSiblingNameAvailable(input.tenantId, input.parentId, folder.name, folder.id);
|
|
732
|
+
let ancestorId = input.parentId;
|
|
733
|
+
const visited = /* @__PURE__ */ new Set();
|
|
734
|
+
while (ancestorId !== null) {
|
|
735
|
+
if (ancestorId === folder.id) throw new MediaAssetConflictError("A folder cannot be moved into itself or a descendant.");
|
|
736
|
+
if (visited.has(ancestorId)) throw new MediaAssetConflictError("The folder hierarchy contains a cycle.");
|
|
737
|
+
visited.add(ancestorId);
|
|
738
|
+
ancestorId = (await getActiveFolder(input.tenantId, ancestorId)).parentId;
|
|
739
|
+
}
|
|
740
|
+
const updated = await storage.update(MEDIA_FOLDERS_COLLECTION, folder.id, {
|
|
741
|
+
parentId: input.parentId,
|
|
742
|
+
updatedAt: getMediaNow(options.now),
|
|
743
|
+
updatedBy: input.actorId ?? null
|
|
744
|
+
}, makeStorageCondition(input.expectedRevision));
|
|
745
|
+
if (!updated) throw new MediaAssetConflictError("The folder changed before it could be moved.");
|
|
746
|
+
if (input.parentId !== null) try {
|
|
747
|
+
await ensureParent(input.tenantId, input.parentId);
|
|
748
|
+
} catch {
|
|
749
|
+
await storage.update(MEDIA_FOLDERS_COLLECTION, folder.id, {
|
|
750
|
+
parentId: folder.parentId,
|
|
751
|
+
updatedAt: getMediaNow(options.now),
|
|
752
|
+
updatedBy: input.actorId ?? null
|
|
753
|
+
}, makeStorageCondition(updated.revision));
|
|
754
|
+
throw new MediaAssetConflictError("The destination folder changed while the folder was being moved.");
|
|
755
|
+
}
|
|
756
|
+
return updated;
|
|
757
|
+
};
|
|
758
|
+
const deleteFolder = async (input) => {
|
|
759
|
+
await ready;
|
|
760
|
+
assertTenantId(input.tenantId);
|
|
761
|
+
assertConditionalWrites(storage);
|
|
762
|
+
const folder = await getActiveFolder(input.tenantId, input.folderId);
|
|
763
|
+
const [children, assets] = await Promise.all([storage.findOne(MEDIA_FOLDERS_COLLECTION, { where: {
|
|
764
|
+
tenantId: {
|
|
765
|
+
operator: "eq",
|
|
766
|
+
value: input.tenantId
|
|
767
|
+
},
|
|
768
|
+
parentId: {
|
|
769
|
+
operator: "eq",
|
|
770
|
+
value: folder.id
|
|
771
|
+
}
|
|
772
|
+
} }), storage.findOne(MEDIA_ASSETS_COLLECTION, { where: {
|
|
773
|
+
tenantId: {
|
|
774
|
+
operator: "eq",
|
|
775
|
+
value: input.tenantId
|
|
776
|
+
},
|
|
777
|
+
folderId: {
|
|
778
|
+
operator: "eq",
|
|
779
|
+
value: folder.id
|
|
780
|
+
}
|
|
781
|
+
} })]);
|
|
782
|
+
if (children || assets) throw new MediaAssetConflictError("A non-empty folder cannot be deleted. Move its children and assets first.");
|
|
783
|
+
const now = getMediaNow(options.now);
|
|
784
|
+
const updated = await storage.update(MEDIA_FOLDERS_COLLECTION, folder.id, {
|
|
785
|
+
deletedAt: now,
|
|
786
|
+
updatedAt: now,
|
|
787
|
+
updatedBy: input.actorId ?? null
|
|
788
|
+
}, makeStorageCondition(input.expectedRevision));
|
|
789
|
+
if (!updated) throw new MediaAssetConflictError("The folder changed before it could be deleted.");
|
|
790
|
+
const [racedChild, racedAsset] = await Promise.all([storage.findOne(MEDIA_FOLDERS_COLLECTION, { where: {
|
|
791
|
+
tenantId: {
|
|
792
|
+
operator: "eq",
|
|
793
|
+
value: input.tenantId
|
|
794
|
+
},
|
|
795
|
+
parentId: {
|
|
796
|
+
operator: "eq",
|
|
797
|
+
value: folder.id
|
|
798
|
+
}
|
|
799
|
+
} }), storage.findOne(MEDIA_ASSETS_COLLECTION, { where: {
|
|
800
|
+
tenantId: {
|
|
801
|
+
operator: "eq",
|
|
802
|
+
value: input.tenantId
|
|
803
|
+
},
|
|
804
|
+
folderId: {
|
|
805
|
+
operator: "eq",
|
|
806
|
+
value: folder.id
|
|
807
|
+
}
|
|
808
|
+
} })]);
|
|
809
|
+
if (racedChild || racedAsset) {
|
|
810
|
+
if (!await storage.update("media_folders", folder.id, {
|
|
811
|
+
deletedAt: null,
|
|
812
|
+
updatedAt: getMediaNow(options.now),
|
|
813
|
+
updatedBy: input.actorId ?? null
|
|
814
|
+
}, makeStorageCondition(updated.revision))) throw new MediaAssetConflictError("The folder changed while its contents were being moved.");
|
|
815
|
+
throw new MediaAssetConflictError("A folder containing child folders or assets cannot be deleted.");
|
|
816
|
+
}
|
|
817
|
+
return updated;
|
|
818
|
+
};
|
|
819
|
+
const restore = async (input) => {
|
|
820
|
+
await ready;
|
|
821
|
+
assertTenantId(input.tenantId);
|
|
822
|
+
assertConditionalWrites(storage);
|
|
823
|
+
const folder = await storage.findById(MEDIA_FOLDERS_COLLECTION, input.folderId);
|
|
824
|
+
if (!folder || folder.tenantId !== input.tenantId || !folder.deletedAt) throw new MediaNotFoundError("Deleted media folder");
|
|
825
|
+
await ensureParent(input.tenantId, folder.parentId);
|
|
826
|
+
await ensureSiblingNameAvailable(input.tenantId, folder.parentId, folder.name);
|
|
827
|
+
const updated = await storage.update(MEDIA_FOLDERS_COLLECTION, folder.id, {
|
|
828
|
+
deletedAt: null,
|
|
829
|
+
updatedAt: getMediaNow(options.now),
|
|
830
|
+
updatedBy: input.actorId ?? null
|
|
831
|
+
}, makeStorageCondition(input.expectedRevision));
|
|
832
|
+
if (!updated) throw new MediaAssetConflictError("The folder changed before it could be restored.");
|
|
833
|
+
return updated;
|
|
834
|
+
};
|
|
835
|
+
const permanentlyDelete = async (input) => {
|
|
836
|
+
await ready;
|
|
837
|
+
assertTenantId(input.tenantId);
|
|
838
|
+
assertConditionalWrites(storage);
|
|
839
|
+
const folder = await storage.findById(MEDIA_FOLDERS_COLLECTION, input.folderId);
|
|
840
|
+
if (!folder || folder.tenantId !== input.tenantId || !folder.deletedAt) throw new MediaNotFoundError("Deleted media folder");
|
|
841
|
+
const [children, assets] = await Promise.all([storage.findOne(MEDIA_FOLDERS_COLLECTION, { where: {
|
|
842
|
+
tenantId: {
|
|
843
|
+
operator: "eq",
|
|
844
|
+
value: input.tenantId
|
|
845
|
+
},
|
|
846
|
+
parentId: {
|
|
847
|
+
operator: "eq",
|
|
848
|
+
value: folder.id
|
|
849
|
+
}
|
|
850
|
+
} }), storage.findOne(MEDIA_ASSETS_COLLECTION, { where: {
|
|
851
|
+
tenantId: {
|
|
852
|
+
operator: "eq",
|
|
853
|
+
value: input.tenantId
|
|
854
|
+
},
|
|
855
|
+
folderId: {
|
|
856
|
+
operator: "eq",
|
|
857
|
+
value: folder.id
|
|
858
|
+
}
|
|
859
|
+
} })]);
|
|
860
|
+
if (children || assets) throw new MediaAssetConflictError("A folder with child folders or assets cannot be permanently deleted.");
|
|
861
|
+
if (!await storage.delete("media_folders", folder.id, makeStorageCondition(input.expectedRevision))) throw new MediaAssetConflictError("The folder changed before it could be permanently deleted.");
|
|
862
|
+
return true;
|
|
863
|
+
};
|
|
864
|
+
return {
|
|
865
|
+
ready,
|
|
866
|
+
create,
|
|
867
|
+
get,
|
|
868
|
+
list,
|
|
869
|
+
rename,
|
|
870
|
+
move,
|
|
871
|
+
delete: deleteFolder,
|
|
872
|
+
restore,
|
|
873
|
+
permanentlyDelete
|
|
874
|
+
};
|
|
875
|
+
};
|
|
876
|
+
// src/services/audit.service.ts
|
|
877
|
+
const MEDIA_AUDIT_EVENTS_COLLECTION = "media_audit_events";
|
|
878
|
+
const isText = (value) => typeof value === "string" && value.trim().length > 0 && value.length <= 255 && !/[\u0000-\u001f\u007f]/.test(value);
|
|
879
|
+
const validResource = (value) => value === "upload" || value === "asset" || value === "folder";
|
|
880
|
+
const validResult = (value) => value === "success" || value === "denied" || value === "failure";
|
|
881
|
+
const validEvent = (value) => {
|
|
882
|
+
if (typeof value !== "object" || value === null) return false;
|
|
883
|
+
const event = value;
|
|
884
|
+
return isText(event.tenantId) && (event.actorId === null || isText(event.actorId)) && validResource(event.resource) && (event.resourceId === void 0 || isText(event.resourceId)) && (event.relatedAssetId === void 0 || isText(event.relatedAssetId)) && typeof event.action === "string" && /^[a-z][a-z-]*:[a-z][a-z-]*$/.test(event.action) && event.action.length <= 120 && event.timestamp instanceof Date && Number.isFinite(event.timestamp.getTime()) && validResult(event.result);
|
|
885
|
+
};
|
|
886
|
+
const isAuditRecord = (value) => validEvent(value) && "id" in value && isText(value.id) && "createdAt" in value && value.createdAt instanceof Date && Number.isFinite(value.createdAt.getTime()) && "updatedAt" in value && value.updatedAt instanceof Date && Number.isFinite(value.updatedAt.getTime()) && "revision" in value && Number.isInteger(value.revision) && typeof value.revision === "number" && value.revision > 0;
|
|
887
|
+
const createMediaAuditService = (options) => {
|
|
888
|
+
if (typeof options.authorize !== "function") throw new TypeError("Media audit requires an authorization policy.");
|
|
889
|
+
const { storage } = options;
|
|
890
|
+
const ready = storage.registerCollection({
|
|
891
|
+
name: MEDIA_AUDIT_EVENTS_COLLECTION,
|
|
892
|
+
schema: { validate: isAuditRecord },
|
|
893
|
+
indexes: [{
|
|
894
|
+
name: "by-tenant-resource",
|
|
895
|
+
fields: ["tenantId", "resource"]
|
|
896
|
+
}, {
|
|
897
|
+
name: "by-tenant-result",
|
|
898
|
+
fields: ["tenantId", "result"]
|
|
899
|
+
}]
|
|
900
|
+
});
|
|
901
|
+
const authorize = async (tenantId, actorId, action) => {
|
|
902
|
+
assertTenantId(tenantId);
|
|
903
|
+
if (!isText(actorId)) throw new MediaValidationError("Audit actorId must be a non-empty identifier.");
|
|
904
|
+
if (await options.authorize({
|
|
905
|
+
tenantId,
|
|
906
|
+
actorId,
|
|
907
|
+
action
|
|
908
|
+
}) !== true) throw new MediaPermissionDeniedError();
|
|
909
|
+
};
|
|
910
|
+
return {
|
|
911
|
+
ready,
|
|
912
|
+
async record({ event, actorId }) {
|
|
913
|
+
await ready;
|
|
914
|
+
if (!validEvent(event)) throw new MediaValidationError("The media audit event is invalid.");
|
|
915
|
+
await authorize(event.tenantId, actorId, "audit:write");
|
|
916
|
+
const now = getMediaNow(options.now);
|
|
917
|
+
const record = {
|
|
918
|
+
id: createMediaId(options.idFactory, "media_audit"),
|
|
919
|
+
tenantId: event.tenantId,
|
|
920
|
+
actorId: event.actorId,
|
|
921
|
+
resource: event.resource,
|
|
922
|
+
...event.resourceId === void 0 ? {} : { resourceId: event.resourceId },
|
|
923
|
+
...event.relatedAssetId === void 0 ? {} : { relatedAssetId: event.relatedAssetId },
|
|
924
|
+
action: event.action,
|
|
925
|
+
timestamp: event.timestamp,
|
|
926
|
+
result: event.result,
|
|
927
|
+
createdAt: now,
|
|
928
|
+
updatedAt: now,
|
|
929
|
+
revision: 1
|
|
930
|
+
};
|
|
931
|
+
return storage.insert(MEDIA_AUDIT_EVENTS_COLLECTION, record);
|
|
932
|
+
},
|
|
933
|
+
async list(input) {
|
|
934
|
+
await ready;
|
|
935
|
+
await authorize(input.tenantId, input.actorId, "audit:read");
|
|
936
|
+
assertStorageCapability(storage, "cursorPagination");
|
|
937
|
+
const first = input.first ?? 50;
|
|
938
|
+
if (!Number.isInteger(first) || first < 1 || first > 100 || input.resource !== void 0 && !validResource(input.resource) || input.result !== void 0 && !validResult(input.result) || input.resourceId !== void 0 && !isText(input.resourceId) || input.after !== void 0 && (typeof input.after !== "string" || input.after.length === 0 || input.after.length > 8192)) throw new MediaValidationError("Invalid media audit query.");
|
|
939
|
+
const where = {
|
|
940
|
+
tenantId: {
|
|
941
|
+
operator: "eq",
|
|
942
|
+
value: input.tenantId
|
|
943
|
+
},
|
|
944
|
+
...input.resource === void 0 ? {} : { resource: {
|
|
945
|
+
operator: "eq",
|
|
946
|
+
value: input.resource
|
|
947
|
+
} },
|
|
948
|
+
...input.resourceId === void 0 ? {} : { resourceId: {
|
|
949
|
+
operator: "eq",
|
|
950
|
+
value: input.resourceId
|
|
951
|
+
} },
|
|
952
|
+
...input.result === void 0 ? {} : { result: {
|
|
953
|
+
operator: "eq",
|
|
954
|
+
value: input.result
|
|
955
|
+
} }
|
|
956
|
+
};
|
|
957
|
+
const page = await storage.findPage(MEDIA_AUDIT_EVENTS_COLLECTION, {
|
|
958
|
+
where,
|
|
959
|
+
first,
|
|
960
|
+
orderBy: [{
|
|
961
|
+
field: "id",
|
|
962
|
+
direction: "asc"
|
|
963
|
+
}],
|
|
964
|
+
...input.after === void 0 ? {} : { after: { value: input.after } }
|
|
965
|
+
});
|
|
966
|
+
return {
|
|
967
|
+
items: page.items,
|
|
968
|
+
nextCursor: page.nextCursor?.value ?? null
|
|
969
|
+
};
|
|
970
|
+
}
|
|
971
|
+
};
|
|
972
|
+
};
|
|
973
|
+
// src/services/processing.service.ts
|
|
974
|
+
const isAbortError = (error) => error instanceof Error && error.name === "AbortError";
|
|
975
|
+
const errorIsRetryable = (error) => {
|
|
976
|
+
if (error instanceof MediaProcessingError) return error.retryable;
|
|
977
|
+
if (error instanceof MediaValidationError || error instanceof MediaCapabilityError || error instanceof MediaNotFoundError || error instanceof MediaAssetConflictError || isAbortError(error)) return false;
|
|
978
|
+
return true;
|
|
979
|
+
};
|
|
980
|
+
const errorMessage = (error) => error instanceof Error ? error.message : "Media processing failed.";
|
|
981
|
+
const errorCode = (error) => error instanceof MediaProcessingError || error instanceof MediaValidationError || error instanceof MediaCapabilityError || error instanceof MediaNotFoundError || error instanceof MediaAssetConflictError ? error.code : void 0;
|
|
982
|
+
const validateWorkerId = (workerId) => {
|
|
983
|
+
if (typeof workerId !== "string" || workerId.trim() === "") throw new MediaValidationError("workerId must be a non-empty string.");
|
|
984
|
+
};
|
|
985
|
+
const mergeVariants = (existing, generated) => {
|
|
986
|
+
const result = /* @__PURE__ */ new Map();
|
|
987
|
+
for (const variant of existing) result.set(variant.name, variant);
|
|
988
|
+
for (const variant of generated) result.set(variant.name, variant);
|
|
989
|
+
return [...result.values()];
|
|
990
|
+
};
|
|
991
|
+
const outputKindToMediaKind = (kind) => {
|
|
992
|
+
if (kind === "video") return "video";
|
|
993
|
+
if (kind === "manifest") return "other";
|
|
994
|
+
return "image";
|
|
995
|
+
};
|
|
996
|
+
const makeVariants = async (job, asset, output, now, objectStorage, idFactory) => {
|
|
997
|
+
const profiles = new Map(job.profiles.map((profile) => [profile.name, profile]));
|
|
998
|
+
const generated = [];
|
|
999
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1000
|
+
for (const outputVariant of output.variants) {
|
|
1001
|
+
if (!profiles.get(outputVariant.name)) throw new MediaValidationError(`Processor returned an unrequested profile "${outputVariant.name}".`);
|
|
1002
|
+
if (seen.has(outputVariant.name)) throw new MediaValidationError(`Processor returned profile "${outputVariant.name}" more than once.`);
|
|
1003
|
+
if (outputVariant.bitrate !== void 0 && (!Number.isSafeInteger(outputVariant.bitrate) || outputVariant.bitrate < 1)) throw new MediaValidationError(`Processor output "${outputVariant.name}" bitrate must be a positive safe integer.`);
|
|
1004
|
+
seen.add(outputVariant.name);
|
|
1005
|
+
const metadata = validateMediaFileMetadata({
|
|
1006
|
+
kind: outputKindToMediaKind(outputVariant.kind),
|
|
1007
|
+
mimeType: outputVariant.mimeType,
|
|
1008
|
+
size: outputVariant.size,
|
|
1009
|
+
...outputVariant.checksum ? { checksum: outputVariant.checksum } : {},
|
|
1010
|
+
...outputVariant.width !== void 0 ? {
|
|
1011
|
+
width: outputVariant.width,
|
|
1012
|
+
height: outputVariant.height
|
|
1013
|
+
} : {},
|
|
1014
|
+
...outputVariant.duration !== void 0 ? { duration: outputVariant.duration } : {}
|
|
1015
|
+
});
|
|
1016
|
+
const object = normalizeMediaObjectReference(outputVariant.object);
|
|
1017
|
+
const storedObject = await objectStorage.getObjectMetadata(object);
|
|
1018
|
+
if (!storedObject || storedObject.tenantId !== job.tenantId) throw new MediaProcessingError(`Processor output "${outputVariant.name}" is not present in the tenant object store.`, { retryable: false });
|
|
1019
|
+
if (storedObject.size !== metadata.size || storedObject.mimeType.toLowerCase() !== metadata.mimeType) throw new MediaProcessingError(`Processor output "${outputVariant.name}" metadata does not match the stored object.`, { retryable: false });
|
|
1020
|
+
if (metadata.checksum && storedObject.checksum && storedObject.checksum.value !== metadata.checksum.value) throw new MediaProcessingError(`Processor output "${outputVariant.name}" checksum does not match the stored object.`, { retryable: false });
|
|
1021
|
+
generated.push({
|
|
1022
|
+
id: createMediaId(idFactory, "variant"),
|
|
1023
|
+
assetId: asset.id,
|
|
1024
|
+
name: outputVariant.name,
|
|
1025
|
+
kind: outputVariant.kind,
|
|
1026
|
+
status: "ready",
|
|
1027
|
+
object,
|
|
1028
|
+
mimeType: metadata.mimeType,
|
|
1029
|
+
size: metadata.size,
|
|
1030
|
+
...storedObject.checksum ? { checksum: storedObject.checksum } : metadata.checksum ? { checksum: metadata.checksum } : {},
|
|
1031
|
+
...metadata.width !== void 0 ? {
|
|
1032
|
+
width: metadata.width,
|
|
1033
|
+
height: metadata.height
|
|
1034
|
+
} : {},
|
|
1035
|
+
...metadata.duration !== void 0 ? { duration: metadata.duration } : {},
|
|
1036
|
+
...outputVariant.bitrate !== void 0 ? { bitrate: outputVariant.bitrate } : {},
|
|
1037
|
+
createdAt: now,
|
|
1038
|
+
updatedAt: now,
|
|
1039
|
+
error: null
|
|
1040
|
+
});
|
|
1041
|
+
}
|
|
1042
|
+
const failures = new Map((output.failures ?? []).map((failure) => [failure.profile, failure]));
|
|
1043
|
+
if (failures.size !== (output.failures?.length ?? 0)) throw new MediaValidationError("Processor returned duplicate profile failures.");
|
|
1044
|
+
const fatalFailures = [];
|
|
1045
|
+
const warnings = [];
|
|
1046
|
+
let fatalFailuresRetryable = true;
|
|
1047
|
+
for (const profile of job.profiles) {
|
|
1048
|
+
if (seen.has(profile.name)) {
|
|
1049
|
+
if (failures.has(profile.name)) throw new MediaValidationError(`Profile "${profile.name}" cannot be both successful and failed.`);
|
|
1050
|
+
continue;
|
|
1051
|
+
}
|
|
1052
|
+
const failure = failures.get(profile.name);
|
|
1053
|
+
const message = failure?.message ?? "The processor did not return this profile.";
|
|
1054
|
+
if (failure && typeof failure.message !== "string") throw new MediaValidationError(`Failure for profile "${profile.name}" requires a message.`);
|
|
1055
|
+
generated.push({
|
|
1056
|
+
id: createMediaId(idFactory, "variant"),
|
|
1057
|
+
assetId: asset.id,
|
|
1058
|
+
name: profile.name,
|
|
1059
|
+
kind: job.kind === "image" ? "image" : "video",
|
|
1060
|
+
status: "failed",
|
|
1061
|
+
error: message,
|
|
1062
|
+
createdAt: now,
|
|
1063
|
+
updatedAt: now
|
|
1064
|
+
});
|
|
1065
|
+
if (profile.required ?? true) {
|
|
1066
|
+
fatalFailures.push(`${profile.name}: ${message}`);
|
|
1067
|
+
if (failure?.retryable === false) fatalFailuresRetryable = false;
|
|
1068
|
+
} else warnings.push(`${profile.name}: ${message}`);
|
|
1069
|
+
}
|
|
1070
|
+
for (const failedProfile of failures.keys()) if (!profiles.has(failedProfile)) throw new MediaValidationError(`Processor failed an unrequested profile "${failedProfile}".`);
|
|
1071
|
+
return {
|
|
1072
|
+
variants: generated,
|
|
1073
|
+
fatalFailures,
|
|
1074
|
+
fatalFailuresRetryable,
|
|
1075
|
+
warnings
|
|
1076
|
+
};
|
|
1077
|
+
};
|
|
1078
|
+
const toProcessingFailure = (error) => ({
|
|
1079
|
+
message: errorMessage(error),
|
|
1080
|
+
...errorCode(error) ? { code: errorCode(error) } : {},
|
|
1081
|
+
retryable: errorIsRetryable(error)
|
|
1082
|
+
});
|
|
1083
|
+
const createMediaProcessingService = (options) => {
|
|
1084
|
+
const { storage, queue } = options;
|
|
1085
|
+
const ready = registerMediaCollections(storage);
|
|
1086
|
+
const controllers = /* @__PURE__ */ new Map();
|
|
1087
|
+
const baseRetryDelayMs = options.baseRetryDelayMs ?? 1e3;
|
|
1088
|
+
const maxRetryDelayMs = options.maxRetryDelayMs ?? 6e4;
|
|
1089
|
+
const leaseDurationMs = options.leaseDurationMs ?? 3e4;
|
|
1090
|
+
if (!Number.isInteger(baseRetryDelayMs) || baseRetryDelayMs < 1 || !Number.isInteger(maxRetryDelayMs) || maxRetryDelayMs < baseRetryDelayMs || !Number.isInteger(leaseDurationMs) || leaseDurationMs < 1) throw new MediaValidationError("Processing retry and lease durations are invalid.");
|
|
1091
|
+
const getAsset = async (tenantId, assetId) => {
|
|
1092
|
+
const asset = await storage.findById(MEDIA_ASSETS_COLLECTION, assetId);
|
|
1093
|
+
if (!asset || asset.tenantId !== tenantId) throw new MediaNotFoundError("Media asset");
|
|
1094
|
+
return asset;
|
|
1095
|
+
};
|
|
1096
|
+
const updateAsset = async (asset, changes) => {
|
|
1097
|
+
const updated = await storage.update(MEDIA_ASSETS_COLLECTION, asset.id, {
|
|
1098
|
+
...changes,
|
|
1099
|
+
updatedAt: getMediaNow(options.now)
|
|
1100
|
+
}, makeStorageCondition(asset.revision));
|
|
1101
|
+
if (!updated) throw new MediaAssetConflictError("The asset changed while its processing state was being updated.");
|
|
1102
|
+
return updated;
|
|
1103
|
+
};
|
|
1104
|
+
const enqueue = async (input) => {
|
|
1105
|
+
await ready;
|
|
1106
|
+
assertTenantId(input.tenantId);
|
|
1107
|
+
assertConditionalWrites(storage);
|
|
1108
|
+
if (input.kind === "image") {
|
|
1109
|
+
if (!options.processor) throw new MediaCapabilityError("MediaProcessor");
|
|
1110
|
+
validateMediaImageProfiles(input.profiles);
|
|
1111
|
+
} else {
|
|
1112
|
+
if (!options.transcoder) throw new MediaCapabilityError("VideoTranscoder");
|
|
1113
|
+
validateMediaVideoProfiles(input.profiles);
|
|
1114
|
+
}
|
|
1115
|
+
if (typeof input.idempotencyKey !== "string" || input.idempotencyKey.trim() === "") throw new MediaValidationError("idempotencyKey must be a non-empty string.");
|
|
1116
|
+
const maxAttempts = input.maxAttempts ?? 3;
|
|
1117
|
+
if (!Number.isInteger(maxAttempts) || maxAttempts < 1 || maxAttempts > 20) throw new MediaValidationError("maxAttempts must be an integer from 1 to 20.");
|
|
1118
|
+
const asset = await getAsset(input.tenantId, input.assetId);
|
|
1119
|
+
if (asset.status === "deleted") throw new MediaNotFoundError("Media asset");
|
|
1120
|
+
if (asset.status !== "uploaded" && asset.status !== "failed" && asset.status !== "ready") throw new MediaAssetConflictError(`An asset in "${asset.status}" state cannot be queued for processing.`);
|
|
1121
|
+
if (input.kind === "image" && asset.kind !== "image" || input.kind === "video" && asset.kind !== "video") throw new MediaValidationError(`A ${input.kind} job cannot process a ${asset.kind} asset.`);
|
|
1122
|
+
if (input.availableAt !== void 0 && !Number.isFinite(input.availableAt.getTime())) throw new MediaValidationError("availableAt must be a valid date.");
|
|
1123
|
+
const createdAt = getMediaNow(options.now);
|
|
1124
|
+
const jobInput = {
|
|
1125
|
+
id: createMediaId(options.idFactory, "job"),
|
|
1126
|
+
tenantId: input.tenantId,
|
|
1127
|
+
assetId: input.assetId,
|
|
1128
|
+
kind: input.kind,
|
|
1129
|
+
profiles: input.profiles,
|
|
1130
|
+
idempotencyKey: input.idempotencyKey,
|
|
1131
|
+
maxAttempts,
|
|
1132
|
+
availableAt: input.availableAt ?? createdAt,
|
|
1133
|
+
createdAt
|
|
1134
|
+
};
|
|
1135
|
+
return queue.enqueue(jobInput);
|
|
1136
|
+
};
|
|
1137
|
+
const runNext = async (workerId) => {
|
|
1138
|
+
await ready;
|
|
1139
|
+
validateWorkerId(workerId);
|
|
1140
|
+
const startedAt = getMediaNow(options.now);
|
|
1141
|
+
const job = await queue.claimNext({
|
|
1142
|
+
workerId,
|
|
1143
|
+
leaseDurationMs,
|
|
1144
|
+
now: startedAt
|
|
1145
|
+
});
|
|
1146
|
+
if (!job) return null;
|
|
1147
|
+
const controller = new AbortController();
|
|
1148
|
+
controllers.set(job.id, controller);
|
|
1149
|
+
let currentAsset;
|
|
1150
|
+
let heartbeatError;
|
|
1151
|
+
let heartbeatPending;
|
|
1152
|
+
let heartbeatStopped = false;
|
|
1153
|
+
const renewLease = async () => {
|
|
1154
|
+
await queue.renewLease(job.id, workerId, leaseDurationMs, getMediaNow(options.now));
|
|
1155
|
+
};
|
|
1156
|
+
const heartbeatIntervalMs = Math.max(1, Math.floor(leaseDurationMs / 3));
|
|
1157
|
+
const heartbeatTimer = setInterval(() => {
|
|
1158
|
+
if (heartbeatStopped || heartbeatPending) return;
|
|
1159
|
+
heartbeatPending = renewLease().catch((error) => {
|
|
1160
|
+
heartbeatError = error;
|
|
1161
|
+
controller.abort();
|
|
1162
|
+
}).finally(() => {
|
|
1163
|
+
heartbeatPending = void 0;
|
|
1164
|
+
});
|
|
1165
|
+
}, heartbeatIntervalMs);
|
|
1166
|
+
const stopHeartbeat = async () => {
|
|
1167
|
+
if (heartbeatStopped) return;
|
|
1168
|
+
heartbeatStopped = true;
|
|
1169
|
+
clearInterval(heartbeatTimer);
|
|
1170
|
+
if (heartbeatPending) await heartbeatPending;
|
|
1171
|
+
};
|
|
1172
|
+
try {
|
|
1173
|
+
assertConditionalWrites(storage);
|
|
1174
|
+
currentAsset = await getAsset(job.tenantId, job.assetId);
|
|
1175
|
+
if (currentAsset.status === "deleted") throw new MediaNotFoundError("Media asset");
|
|
1176
|
+
if (currentAsset.status === "processing" && currentAsset.processingJobId !== job.id) throw new MediaProcessingError("Another processing job currently owns this asset.", { retryable: true });
|
|
1177
|
+
if (currentAsset.status !== "processing") currentAsset = await updateAsset(currentAsset, {
|
|
1178
|
+
status: "processing",
|
|
1179
|
+
previousStatus: currentAsset.status,
|
|
1180
|
+
processingError: null,
|
|
1181
|
+
processingJobId: job.id
|
|
1182
|
+
});
|
|
1183
|
+
const onProgress = async (progress) => {
|
|
1184
|
+
if (!Number.isFinite(progress) || progress < 0 || progress > 100) throw new MediaValidationError("Processor progress must be from 0 to 100.");
|
|
1185
|
+
await queue.updateProgress(job.id, workerId, progress, getMediaNow(options.now));
|
|
1186
|
+
await renewLease();
|
|
1187
|
+
};
|
|
1188
|
+
let output;
|
|
1189
|
+
if (job.kind === "image") {
|
|
1190
|
+
if (!options.processor) throw new MediaCapabilityError("MediaProcessor");
|
|
1191
|
+
output = await options.processor.processImage({
|
|
1192
|
+
jobId: job.id,
|
|
1193
|
+
idempotencyKey: job.idempotencyKey,
|
|
1194
|
+
asset: currentAsset,
|
|
1195
|
+
profiles: job.profiles,
|
|
1196
|
+
signal: controller.signal,
|
|
1197
|
+
onProgress
|
|
1198
|
+
});
|
|
1199
|
+
} else {
|
|
1200
|
+
const transcoder = options.transcoder;
|
|
1201
|
+
if (!transcoder) throw new MediaCapabilityError("VideoTranscoder");
|
|
1202
|
+
output = await transcoder.transcode({
|
|
1203
|
+
jobId: job.id,
|
|
1204
|
+
idempotencyKey: job.idempotencyKey,
|
|
1205
|
+
asset: currentAsset,
|
|
1206
|
+
profiles: job.profiles,
|
|
1207
|
+
signal: controller.signal,
|
|
1208
|
+
onProgress
|
|
1209
|
+
});
|
|
1210
|
+
}
|
|
1211
|
+
if (controller.signal.aborted) {
|
|
1212
|
+
if (heartbeatError) throw heartbeatError;
|
|
1213
|
+
const abortError = /* @__PURE__ */ new Error("Media processing was cancelled.");
|
|
1214
|
+
abortError.name = "AbortError";
|
|
1215
|
+
throw abortError;
|
|
1216
|
+
}
|
|
1217
|
+
currentAsset = await getAsset(job.tenantId, job.assetId);
|
|
1218
|
+
if (currentAsset.status !== "processing" || currentAsset.processingJobId !== job.id) throw new MediaAssetConflictError("The processing job no longer owns the asset.");
|
|
1219
|
+
const built = await makeVariants(job, currentAsset, output, getMediaNow(options.now), options.objectStorage, options.idFactory);
|
|
1220
|
+
const processingError = built.fatalFailures.length > 0 ? built.fatalFailures.join("; ") : built.warnings.length > 0 ? built.warnings.join("; ") : null;
|
|
1221
|
+
currentAsset = await updateAsset(currentAsset, {
|
|
1222
|
+
variants: mergeVariants(currentAsset.variants, built.variants),
|
|
1223
|
+
...built.fatalFailures.length === 0 ? {
|
|
1224
|
+
status: "ready",
|
|
1225
|
+
previousStatus: null,
|
|
1226
|
+
processingJobId: null
|
|
1227
|
+
} : {},
|
|
1228
|
+
processingError
|
|
1229
|
+
});
|
|
1230
|
+
if (built.fatalFailures.length > 0) throw new MediaProcessingError(`Required media profiles failed: ${built.fatalFailures.join("; ")}`, { retryable: built.fatalFailuresRetryable });
|
|
1231
|
+
await stopHeartbeat();
|
|
1232
|
+
if (heartbeatError) throw heartbeatError;
|
|
1233
|
+
return await queue.complete(job.id, workerId, built.variants, getMediaNow(options.now));
|
|
1234
|
+
} catch (error) {
|
|
1235
|
+
await stopHeartbeat();
|
|
1236
|
+
if (isAbortError(error)) {
|
|
1237
|
+
const cancelled = await queue.get(job.id);
|
|
1238
|
+
if (cancelled?.status === "cancelled") return cancelled;
|
|
1239
|
+
}
|
|
1240
|
+
const failure = toProcessingFailure(error);
|
|
1241
|
+
const now = getMediaNow(options.now);
|
|
1242
|
+
const retryAt = failure.retryable && job.attempt < job.maxAttempts ? new Date(now.getTime() + Math.min(maxRetryDelayMs, baseRetryDelayMs * 2 ** Math.min(job.attempt - 1, 30))) : null;
|
|
1243
|
+
const failedJob = await queue.fail(job.id, workerId, failure, retryAt, now);
|
|
1244
|
+
if (failedJob.status === "failed" || failedJob.status === "dead-letter") {
|
|
1245
|
+
const asset = await storage.findById(MEDIA_ASSETS_COLLECTION, job.assetId);
|
|
1246
|
+
if (asset && asset.tenantId === job.tenantId && asset.status !== "deleted" && asset.processingJobId === job.id) await updateAsset(asset, {
|
|
1247
|
+
status: "failed",
|
|
1248
|
+
previousStatus: null,
|
|
1249
|
+
processingJobId: null,
|
|
1250
|
+
processingError: failure.message
|
|
1251
|
+
});
|
|
1252
|
+
}
|
|
1253
|
+
return failedJob;
|
|
1254
|
+
} finally {
|
|
1255
|
+
await stopHeartbeat();
|
|
1256
|
+
controllers.delete(job.id);
|
|
1257
|
+
}
|
|
1258
|
+
};
|
|
1259
|
+
const cancel = async (jobId) => {
|
|
1260
|
+
await ready;
|
|
1261
|
+
const before = await queue.get(jobId);
|
|
1262
|
+
if (!before) return null;
|
|
1263
|
+
controllers.get(jobId)?.abort();
|
|
1264
|
+
const cancelled = await queue.cancel(jobId, getMediaNow(options.now));
|
|
1265
|
+
if (!cancelled) return null;
|
|
1266
|
+
if (before.status === "processing") {
|
|
1267
|
+
const asset = await getAsset(before.tenantId, before.assetId);
|
|
1268
|
+
if (asset.status === "processing" && asset.processingJobId === before.id) await updateAsset(asset, {
|
|
1269
|
+
status: asset.previousStatus ?? "uploaded",
|
|
1270
|
+
previousStatus: null,
|
|
1271
|
+
processingJobId: null,
|
|
1272
|
+
processingError: null
|
|
1273
|
+
});
|
|
1274
|
+
}
|
|
1275
|
+
return cancelled;
|
|
1276
|
+
};
|
|
1277
|
+
return {
|
|
1278
|
+
ready,
|
|
1279
|
+
enqueue,
|
|
1280
|
+
runNext,
|
|
1281
|
+
cancel
|
|
1282
|
+
};
|
|
1283
|
+
};
|
|
1284
|
+
export { cleanupExpiredMediaUploads as a, MEDIA_ASSETS_COLLECTION as c, registerMediaCollections as d, MEDIA_ASSET_STATUSES as f, createMediaFolderService as i, MEDIA_ASSET_USAGES_COLLECTION as l, MEDIA_AUDIT_EVENTS_COLLECTION as n, cleanupOrphanedMediaObjects as o, MEDIA_KINDS as p, createMediaAuditService as r, createMediaAssetService as s, createMediaProcessingService as t, MEDIA_FOLDERS_COLLECTION as u };
|
|
1285
|
+
|
|
1286
|
+
//# sourceMappingURL=src-8d6s1iWH.js.map
|