@opensaas/stack-storage 0.42.3 → 0.44.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +447 -0
- package/README.md +62 -30
- package/dist/.build-hash +1 -0
- package/dist/fields/index.d.ts +9 -8
- package/dist/fields/index.d.ts.map +1 -1
- package/dist/fields/index.js +376 -153
- package/dist/fields/index.js.map +1 -1
- package/dist/providers/local.d.ts +8 -0
- package/dist/providers/local.d.ts.map +1 -1
- package/dist/providers/local.js +56 -5
- package/dist/providers/local.js.map +1 -1
- package/dist/runtime/index.d.ts +29 -0
- package/dist/runtime/index.d.ts.map +1 -1
- package/dist/runtime/index.js +244 -29
- package/dist/runtime/index.js.map +1 -1
- package/dist/utils/asset-references.d.ts +13 -0
- package/dist/utils/asset-references.d.ts.map +1 -0
- package/dist/utils/asset-references.js +40 -0
- package/dist/utils/asset-references.js.map +1 -0
- package/dist/utils/image.d.ts +17 -0
- package/dist/utils/image.d.ts.map +1 -1
- package/dist/utils/image.js +69 -22
- package/dist/utils/image.js.map +1 -1
- package/dist/utils/metadata-trust.d.ts +30 -0
- package/dist/utils/metadata-trust.d.ts.map +1 -0
- package/dist/utils/metadata-trust.js +57 -0
- package/dist/utils/metadata-trust.js.map +1 -0
- package/dist/utils/multi-column.d.ts +7 -7
- package/dist/utils/multi-column.d.ts.map +1 -1
- package/dist/utils/multi-column.js +17 -34
- package/dist/utils/multi-column.js.map +1 -1
- package/dist/utils/upload.d.ts +58 -0
- package/dist/utils/upload.d.ts.map +1 -1
- package/dist/utils/upload.js +135 -11
- package/dist/utils/upload.js.map +1 -1
- package/package.json +20 -9
- package/.turbo/turbo-build.log +0 -4
- package/CLAUDE.md +0 -528
- package/src/config/index.ts +0 -30
- package/src/config/types.ts +0 -92
- package/src/fields/index.ts +0 -531
- package/src/index.ts +0 -14
- package/src/providers/index.ts +0 -1
- package/src/providers/local.ts +0 -79
- package/src/runtime/index.ts +0 -244
- package/src/runtime/registry.ts +0 -106
- package/src/utils/image.ts +0 -95
- package/src/utils/index.ts +0 -3
- package/src/utils/multi-column.ts +0 -425
- package/src/utils/upload.ts +0 -95
- package/tests/field-zod-schema.test.ts +0 -133
- package/tests/image-utils.test.ts +0 -498
- package/tests/local-provider.test.ts +0 -364
- package/tests/multi-column-fields.test.ts +0 -393
- package/tests/multi-column.test.ts +0 -453
- package/tests/opensaas-image-file-write-validation.test.ts +0 -294
- package/tests/provider-registry.test.ts +0 -201
- package/tests/upload-utils.test.ts +0 -313
- package/tsconfig.json +0 -9
- package/vitest.config.ts +0 -14
package/dist/fields/index.js
CHANGED
|
@@ -1,8 +1,102 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { assembleFileMetadata, assembleImageMetadata, DEFAULT_FILE_COLUMN_PARTS, fileColumnDescriptors, fileColumnNames, imageColumnDescriptors, imageColumnNames, resolveFileColumnMap, resolveImageColumnMap, splitFileMetadata, splitImageMetadata, } from '../utils/multi-column.js';
|
|
3
|
+
import { authorizeStoredMetadata } from '../utils/metadata-trust.js';
|
|
4
|
+
import { isAssetReferenced } from '../utils/asset-references.js';
|
|
5
|
+
import { ValidationError } from '@opensaas/stack-core';
|
|
6
|
+
const storedUrlSchema = z.string().regex(/^(https?:\/\/|\/(?![/\\]))/i, {
|
|
7
|
+
message: 'url must be an http(s) URL or an absolute path',
|
|
8
|
+
});
|
|
3
9
|
function isMultiColumn(columns) {
|
|
4
10
|
return columns === 'keystone' || (typeof columns === 'object' && columns?.mode === 'keystone');
|
|
5
11
|
}
|
|
12
|
+
/**
|
|
13
|
+
* Nullability is ONE decision, shared by the emitted column, the declared
|
|
14
|
+
* TypeScript face and the Zod schema. Splitting them lets `db.isNullable: false`
|
|
15
|
+
* emit a NOT NULL column while the face and schema still admit `null`, so
|
|
16
|
+
* `create({ data: { field: null } })` type-checks, validates, and then dies on a
|
|
17
|
+
* not-null violation. Multi-column mode has no single column to constrain —
|
|
18
|
+
* every part column is nullable — so the assembled metadata is always nullable.
|
|
19
|
+
*/
|
|
20
|
+
function resolveNullable(db) {
|
|
21
|
+
return isMultiColumn(db?.columns) ? true : (db?.isNullable ?? true);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Refuse `db.isNullable: false` alongside multi-column mode.
|
|
25
|
+
*
|
|
26
|
+
* Thrown from `getContractField`, which core's `validateExtensionPacks` calls
|
|
27
|
+
* inside a try/catch and reports as a `field-descriptor-error` config refusal
|
|
28
|
+
* naming the list and the field — so generation stops before any column is
|
|
29
|
+
* emitted. Core cannot make this call itself: another field package may
|
|
30
|
+
* legitimately consume `db.isNullable` when building its part columns, and only
|
|
31
|
+
* the package that drops the option knows that it drops it.
|
|
32
|
+
*/
|
|
33
|
+
function refuseNullabilityOverride(db) {
|
|
34
|
+
if (db?.isNullable !== false)
|
|
35
|
+
return;
|
|
36
|
+
throw new Error('db.isNullable: false is set alongside db.columns (multi-column, Keystone-parity mode), ' +
|
|
37
|
+
'where every part column is nullable and an all-NULL row reads back as null — the ' +
|
|
38
|
+
'assembled value cannot be non-nullable. Remove db.isNullable, or remove db.columns to ' +
|
|
39
|
+
'use the single-Json? column that db.isNullable constrains.');
|
|
40
|
+
}
|
|
41
|
+
function refuseMultiColumnTransformations(db, transformations) {
|
|
42
|
+
if (!isMultiColumn(db?.columns))
|
|
43
|
+
return;
|
|
44
|
+
if (transformations == null || Object.keys(transformations).length === 0)
|
|
45
|
+
return;
|
|
46
|
+
throw new Error('image() sets both db.columns (multi-column mode) and transformations. Multi-column mode has ' +
|
|
47
|
+
'no column to store the generated variants, so they would be uploaded and never recorded. ' +
|
|
48
|
+
'Remove transformations, or remove db.columns to use the single-Json column that stores variants.');
|
|
49
|
+
}
|
|
50
|
+
/** The metadata blob's single-column backing, honouring the `db` overrides the field documents. */
|
|
51
|
+
function metadataColumn(fieldName, db) {
|
|
52
|
+
const descriptor = {
|
|
53
|
+
kind: 'column',
|
|
54
|
+
name: fieldName,
|
|
55
|
+
type: { pack: 'pg', type: 'jsonb' },
|
|
56
|
+
nullable: resolveNullable(db),
|
|
57
|
+
};
|
|
58
|
+
if (db?.nativeType !== undefined)
|
|
59
|
+
descriptor.nativeType = db.nativeType;
|
|
60
|
+
if (db?.map !== undefined)
|
|
61
|
+
descriptor.map = db.map;
|
|
62
|
+
return descriptor;
|
|
63
|
+
}
|
|
64
|
+
/** The `outputType`/`inputType` faces for a metadata field, following its column's nullability. */
|
|
65
|
+
function metadataFaces(metadataType, nullable) {
|
|
66
|
+
const suffix = nullable ? ' | null' : '';
|
|
67
|
+
return {
|
|
68
|
+
outputType: `${metadataType}${suffix}`,
|
|
69
|
+
inputType: `File | ${metadataType}${suffix}`,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Apply a field's nullability to its metadata Zod schema. A non-nullable column
|
|
74
|
+
* rejects `null` outright; `undefined` is still allowed on update so partial
|
|
75
|
+
* updates need not restate the field.
|
|
76
|
+
*/
|
|
77
|
+
function applyNullability(schema, nullable, operation) {
|
|
78
|
+
// `.nullish()` (= `.nullable().optional()`) makes the object KEY optional in
|
|
79
|
+
// Zod 4 — a bare union that merely accepts an `undefined` value does NOT
|
|
80
|
+
// (see issue #618, and the #570 precedent in core's validation tests).
|
|
81
|
+
if (nullable)
|
|
82
|
+
return schema.nullish();
|
|
83
|
+
return operation === 'create' ? schema : schema.optional();
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* The per-part columns of a multi-column field, as the contract spells them.
|
|
87
|
+
* The model field name and the physical column are the same string here (see
|
|
88
|
+
* `imagePartFieldName` in `../utils/multi-column.js`), so no `map` is carried.
|
|
89
|
+
*/
|
|
90
|
+
function partColumns(parts) {
|
|
91
|
+
return {
|
|
92
|
+
kind: 'columns',
|
|
93
|
+
columns: parts.map((part) => ({
|
|
94
|
+
name: part.name,
|
|
95
|
+
type: { pack: 'pg', type: part.type === 'Int' ? 'int' : 'text' },
|
|
96
|
+
nullable: true,
|
|
97
|
+
})),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
6
100
|
function imageColumnOverrides(columns) {
|
|
7
101
|
return typeof columns === 'object' ? columns.map : undefined;
|
|
8
102
|
}
|
|
@@ -17,12 +111,146 @@ function fileColumnPartsFor(columns) {
|
|
|
17
111
|
* authoritative and must never trigger a re-upload (the no-re-upload
|
|
18
112
|
* guarantee — see ADR-0006).
|
|
19
113
|
*/
|
|
114
|
+
/** Shape-only detection of an already-uploaded `FileMetadata` value — see `authorizeStoredMetadata`. */
|
|
115
|
+
function isFileMetadataShaped(value) {
|
|
116
|
+
return typeof value === 'object' && value !== null && 'filename' in value && 'url' in value;
|
|
117
|
+
}
|
|
118
|
+
/** Shape-only detection of an already-uploaded `ImageMetadata` value. */
|
|
119
|
+
function isImageMetadataShaped(value) {
|
|
120
|
+
return isFileMetadataShaped(value) && 'width' in value && 'height' in value;
|
|
121
|
+
}
|
|
20
122
|
function isFileLike(value) {
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
123
|
+
if (typeof value !== 'object' || value === null)
|
|
124
|
+
return false;
|
|
125
|
+
const candidate = value;
|
|
126
|
+
// Every member the upload path reads, not just `arrayBuffer`: `uploadFile`
|
|
127
|
+
// and `uploadImage` derive the stored `originalFilename` from `name`, the
|
|
128
|
+
// MIME type from `type` and validate against `size`. A value carrying only
|
|
129
|
+
// `arrayBuffer` satisfied the old check and was stored under
|
|
130
|
+
// `originalFilename: undefined`.
|
|
131
|
+
return (typeof candidate.arrayBuffer === 'function' &&
|
|
132
|
+
typeof candidate.name === 'string' &&
|
|
133
|
+
typeof candidate.type === 'string' &&
|
|
134
|
+
typeof candidate.size === 'number');
|
|
135
|
+
}
|
|
136
|
+
function logicalValue(fieldConfig, fieldKey, row) {
|
|
137
|
+
if (!row)
|
|
138
|
+
return undefined;
|
|
139
|
+
return fieldConfig.assembleColumns ? fieldConfig.assembleColumns(fieldKey, row) : row[fieldKey];
|
|
140
|
+
}
|
|
141
|
+
function staleAssets(pending, status) {
|
|
142
|
+
if (status !== 'committed')
|
|
143
|
+
return pending.uploaded?.filename ? [pending.uploaded] : [];
|
|
144
|
+
const stale = [pending.discarded ? pending.uploaded : null];
|
|
145
|
+
if (pending.replaced?.filename !== pending.uploaded?.filename || pending.discarded) {
|
|
146
|
+
stale.push(pending.replaced);
|
|
147
|
+
}
|
|
148
|
+
return stale.filter((asset) => Boolean(asset?.filename));
|
|
25
149
|
}
|
|
150
|
+
function claimStableKeyFor(context, listKey, fieldKey, field, item) {
|
|
151
|
+
return async (key) => {
|
|
152
|
+
if (await isAssetReferenced(context, listKey, fieldKey, field, key, item?.id)) {
|
|
153
|
+
throw new ValidationError([
|
|
154
|
+
`${fieldKey}: a file with this name already belongs to another item`,
|
|
155
|
+
]);
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
async function withoutSharedVariants(context, listKey, fieldKey, field, metadata) {
|
|
160
|
+
if (!metadata.transformations)
|
|
161
|
+
return metadata;
|
|
162
|
+
const kept = {};
|
|
163
|
+
for (const [name, variant] of Object.entries(metadata.transformations)) {
|
|
164
|
+
const key = variant.filename ?? variant.url.split('/').pop();
|
|
165
|
+
if (key && (await isAssetReferenced(context, listKey, fieldKey, field, key)))
|
|
166
|
+
continue;
|
|
167
|
+
kept[name] = variant;
|
|
168
|
+
}
|
|
169
|
+
return { ...metadata, transformations: kept };
|
|
170
|
+
}
|
|
171
|
+
function previousOnClear(fieldConfig, { item, fieldKey }) {
|
|
172
|
+
return fieldConfig.cleanupOnReplace ? logicalValue(fieldConfig, fieldKey, item) : null;
|
|
173
|
+
}
|
|
174
|
+
function createPendingUploads() {
|
|
175
|
+
const pending = new WeakMap();
|
|
176
|
+
const queueFor = (write, fieldKey) => {
|
|
177
|
+
const forWrite = pending.get(write) ?? new Map();
|
|
178
|
+
pending.set(write, forWrite);
|
|
179
|
+
const queue = forWrite.get(fieldKey) ?? [];
|
|
180
|
+
forWrite.set(fieldKey, queue);
|
|
181
|
+
return queue;
|
|
182
|
+
};
|
|
183
|
+
return {
|
|
184
|
+
set: (write, fieldKey, value) => {
|
|
185
|
+
queueFor(write, fieldKey).push(value);
|
|
186
|
+
},
|
|
187
|
+
take: (write, fieldKey) => {
|
|
188
|
+
if (typeof write !== 'object' || write === null)
|
|
189
|
+
return undefined;
|
|
190
|
+
return pending.get(write)?.get(fieldKey)?.shift();
|
|
191
|
+
},
|
|
192
|
+
size: (write, fieldKey) => {
|
|
193
|
+
if (typeof write !== 'object' || write === null)
|
|
194
|
+
return 0;
|
|
195
|
+
return pending.get(write)?.get(fieldKey)?.length ?? 0;
|
|
196
|
+
},
|
|
197
|
+
amendLast: (write, fieldKey, amend) => {
|
|
198
|
+
if (typeof write !== 'object' || write === null)
|
|
199
|
+
return;
|
|
200
|
+
const queue = pending.get(write)?.get(fieldKey);
|
|
201
|
+
if (queue?.length)
|
|
202
|
+
queue[queue.length - 1] = amend(queue[queue.length - 1]);
|
|
203
|
+
},
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
const pendingFileUploads = createPendingUploads();
|
|
207
|
+
const pendingImageUploads = createPendingUploads();
|
|
208
|
+
/* eslint-disable @typescript-eslint/no-explicit-any -- Field builder hooks are generic and resolved at runtime */
|
|
209
|
+
function composeFieldHooks(builtIn, userHooks, cleanupAfterTransaction, uploads, replacedOnClear) {
|
|
210
|
+
return {
|
|
211
|
+
...userHooks,
|
|
212
|
+
resolveInput: async (args) => {
|
|
213
|
+
const queuedBefore = uploads.size(args.inputData, args.fieldKey);
|
|
214
|
+
const resolved = await builtIn.resolveInput(args);
|
|
215
|
+
const final = userHooks?.resolveInput
|
|
216
|
+
? await userHooks.resolveInput({
|
|
217
|
+
...args,
|
|
218
|
+
resolvedData: { ...args.resolvedData, [args.fieldKey]: resolved },
|
|
219
|
+
})
|
|
220
|
+
: resolved;
|
|
221
|
+
if (final === null) {
|
|
222
|
+
const replaced = replacedOnClear(args);
|
|
223
|
+
if (uploads.size(args.inputData, args.fieldKey) > queuedBefore) {
|
|
224
|
+
uploads.amendLast(args.inputData, args.fieldKey, (pending) => ({
|
|
225
|
+
...pending,
|
|
226
|
+
replaced: replaced?.filename ? replaced : null,
|
|
227
|
+
discarded: true,
|
|
228
|
+
}));
|
|
229
|
+
return final;
|
|
230
|
+
}
|
|
231
|
+
if (replaced?.filename && typeof args.inputData === 'object' && args.inputData !== null) {
|
|
232
|
+
uploads.set(args.inputData, args.fieldKey, { uploaded: null, replaced });
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
if (!userHooks?.resolveInput)
|
|
236
|
+
return final;
|
|
237
|
+
if (final?.filename !== resolved?.filename &&
|
|
238
|
+
uploads.size(args.inputData, args.fieldKey) > queuedBefore) {
|
|
239
|
+
uploads.amendLast(args.inputData, args.fieldKey, (pending) => ({
|
|
240
|
+
...pending,
|
|
241
|
+
replaced: null,
|
|
242
|
+
discarded: true,
|
|
243
|
+
}));
|
|
244
|
+
}
|
|
245
|
+
return final;
|
|
246
|
+
},
|
|
247
|
+
afterTransaction: async (args) => {
|
|
248
|
+
await cleanupAfterTransaction(args);
|
|
249
|
+
await userHooks?.afterTransaction?.(args);
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
/* eslint-enable @typescript-eslint/no-explicit-any */
|
|
26
254
|
/**
|
|
27
255
|
* Creates a file upload field
|
|
28
256
|
*
|
|
@@ -48,28 +276,69 @@ export function file(options) {
|
|
|
48
276
|
const multiColumn = isMultiColumn(options.db?.columns);
|
|
49
277
|
const columnMapFor = (fieldName) => resolveFileColumnMap(fieldName, fileColumnOverrides(options.db?.columns));
|
|
50
278
|
const fileParts = fileColumnPartsFor(options.db?.columns);
|
|
279
|
+
const nullable = resolveNullable(options.db);
|
|
280
|
+
const faces = metadataFaces("import('@opensaas/stack-storage').FileMetadata", nullable);
|
|
281
|
+
const cleanupAfterTransaction = async ({ status, operation, inputData, originalItem, fieldKey, listKey, context,
|
|
282
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Field builder hooks are generic and resolved at runtime
|
|
283
|
+
}) => {
|
|
284
|
+
if (operation === 'delete') {
|
|
285
|
+
if (status !== 'committed' || !fieldConfig.cleanupOnDelete)
|
|
286
|
+
return;
|
|
287
|
+
const deleted = logicalValue(fieldConfig, fieldKey, originalItem);
|
|
288
|
+
if (!deleted || typeof deleted !== 'object' || !deleted.filename)
|
|
289
|
+
return;
|
|
290
|
+
try {
|
|
291
|
+
if (await isAssetReferenced(context, listKey, fieldKey, fieldConfig, deleted.filename))
|
|
292
|
+
return;
|
|
293
|
+
await context.storage.deleteFile(fieldConfig.storage, deleted.filename);
|
|
294
|
+
}
|
|
295
|
+
catch (error) {
|
|
296
|
+
console.error(`Failed to cleanup file on delete: ${deleted.filename}`, error);
|
|
297
|
+
}
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
const pending = pendingFileUploads.take(inputData, fieldKey);
|
|
301
|
+
if (!pending)
|
|
302
|
+
return;
|
|
303
|
+
for (const stale of staleAssets(pending, status)) {
|
|
304
|
+
try {
|
|
305
|
+
if (await isAssetReferenced(context, listKey, fieldKey, fieldConfig, stale.filename))
|
|
306
|
+
continue;
|
|
307
|
+
await context.storage.deleteFile(fieldConfig.storage, stale.filename);
|
|
308
|
+
}
|
|
309
|
+
catch (error) {
|
|
310
|
+
console.error(`Failed to cleanup file: ${stale.filename}`, error);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
};
|
|
51
314
|
const fieldConfig = {
|
|
52
315
|
type: 'file',
|
|
316
|
+
outputType: faces.outputType,
|
|
317
|
+
inputType: faces.inputType,
|
|
53
318
|
...restOptions,
|
|
54
|
-
|
|
55
|
-
// Multi-column mode adds the same logical field back via TransformedFields
|
|
56
|
-
// while the raw per-part columns are stripped from the payload.
|
|
57
|
-
resultExtension: {
|
|
58
|
-
outputType: "import('@opensaas/stack-storage').FileMetadata | null",
|
|
59
|
-
},
|
|
60
|
-
hooks: {
|
|
319
|
+
hooks: composeFieldHooks({
|
|
61
320
|
// Keystone-compliant field resolveInput args: the field value lives at
|
|
62
321
|
// `resolvedData[fieldKey]`. See FieldResolveInputHookArgs in core.
|
|
63
322
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Field builder hooks are generic and resolved at runtime
|
|
64
|
-
resolveInput: async (
|
|
323
|
+
resolveInput: async (args) => {
|
|
324
|
+
const { resolvedData, inputData, fieldKey, listKey, context, item, operation } = args;
|
|
65
325
|
const inputValue = resolvedData?.[fieldKey];
|
|
66
326
|
if (inputValue === null || inputValue === undefined) {
|
|
67
327
|
return inputValue;
|
|
68
328
|
}
|
|
69
329
|
// An existing metadata value is AUTHORITATIVE and must never
|
|
70
|
-
// re-upload
|
|
71
|
-
|
|
72
|
-
|
|
330
|
+
// re-upload — but only when it is genuinely the row's own currently
|
|
331
|
+
// stored value, or the write is sudo. See ADR-0006 and issue #1619.
|
|
332
|
+
if (isFileMetadataShaped(inputValue)) {
|
|
333
|
+
return authorizeStoredMetadata({
|
|
334
|
+
value: inputValue,
|
|
335
|
+
fieldKey,
|
|
336
|
+
operation,
|
|
337
|
+
isSudo: context._isSudo === true,
|
|
338
|
+
currentValue: () => fieldConfig.assembleColumns
|
|
339
|
+
? fieldConfig.assembleColumns(fieldKey, (item ?? {}))
|
|
340
|
+
: (item?.[fieldKey] ?? null),
|
|
341
|
+
});
|
|
73
342
|
}
|
|
74
343
|
if (isFileLike(inputValue)) {
|
|
75
344
|
const fileObj = inputValue;
|
|
@@ -77,86 +346,39 @@ export function file(options) {
|
|
|
77
346
|
const buffer = Buffer.from(arrayBuffer);
|
|
78
347
|
const metadata = (await context.storage.uploadFile(fieldConfig.storage, fileObj, buffer, {
|
|
79
348
|
validation: fieldConfig.validation,
|
|
349
|
+
claimStableKey: claimStableKeyFor(context, listKey, fieldKey, fieldConfig, item),
|
|
80
350
|
}));
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
}
|
|
87
|
-
catch (error) {
|
|
88
|
-
console.error(`Failed to cleanup old file: ${oldMetadata.filename}`, error);
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
}
|
|
351
|
+
const previous = logicalValue(fieldConfig, fieldKey, item);
|
|
352
|
+
pendingFileUploads.set(inputData, fieldKey, {
|
|
353
|
+
uploaded: metadata,
|
|
354
|
+
replaced: fieldConfig.cleanupOnReplace ? (previous ?? null) : null,
|
|
355
|
+
});
|
|
92
356
|
return metadata;
|
|
93
357
|
}
|
|
94
358
|
// Unknown type - return as-is and let validation catch it
|
|
95
359
|
return inputValue;
|
|
96
360
|
},
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
// The deleted row is `originalItem`.
|
|
100
|
-
if (operation === 'delete' && fieldConfig.cleanupOnDelete) {
|
|
101
|
-
const fileMetadata = originalItem?.[fieldKey];
|
|
102
|
-
if (fileMetadata && typeof fileMetadata === 'object' && fileMetadata.filename) {
|
|
103
|
-
try {
|
|
104
|
-
await context.storage.deleteFile(fileMetadata.storageProvider, fileMetadata.filename);
|
|
105
|
-
}
|
|
106
|
-
catch (error) {
|
|
107
|
-
console.error(`Failed to cleanup file on delete: ${fileMetadata.filename}`, error);
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
},
|
|
112
|
-
...userHooks,
|
|
113
|
-
},
|
|
114
|
-
getZodSchema: (_fieldName, _operation) => {
|
|
361
|
+
}, userHooks, cleanupAfterTransaction, pendingFileUploads, (args) => previousOnClear(fieldConfig, args)),
|
|
362
|
+
getZodSchema: (_fieldName, operation) => {
|
|
115
363
|
const fileMetadataSchema = z.object({
|
|
116
364
|
filename: z.string(),
|
|
117
365
|
originalFilename: z.string(),
|
|
118
|
-
url:
|
|
366
|
+
url: storedUrlSchema,
|
|
119
367
|
mimeType: z.string(),
|
|
120
368
|
size: z.number(),
|
|
121
369
|
uploadedAt: z.string(),
|
|
122
370
|
storageProvider: z.string(),
|
|
123
371
|
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
124
372
|
});
|
|
125
|
-
|
|
126
|
-
// makes the object KEY optional in Zod 4 — a bare union that merely accepts
|
|
127
|
-
// an `undefined` value does NOT (see issue #618, and the #570 precedent in
|
|
128
|
-
// core's validation tests).
|
|
129
|
-
return fileMetadataSchema.nullish();
|
|
130
|
-
},
|
|
131
|
-
getPrismaType: (_fieldName) => {
|
|
132
|
-
return { type: 'Json', modifiers: '?' };
|
|
133
|
-
},
|
|
134
|
-
getTypeScriptType: () => {
|
|
135
|
-
return {
|
|
136
|
-
type: 'FileMetadata | null',
|
|
137
|
-
optional: true,
|
|
138
|
-
};
|
|
139
|
-
},
|
|
140
|
-
getTypeScriptImports: () => {
|
|
141
|
-
return [
|
|
142
|
-
{
|
|
143
|
-
names: ['FileMetadata'],
|
|
144
|
-
from: '@opensaas/stack-storage',
|
|
145
|
-
typeOnly: true,
|
|
146
|
-
},
|
|
147
|
-
];
|
|
373
|
+
return applyNullability(fileMetadataSchema, nullable, operation);
|
|
148
374
|
},
|
|
375
|
+
getContractField: (fieldName) => metadataColumn(fieldName, options.db),
|
|
149
376
|
};
|
|
150
|
-
// Only attached in multi-column mode; the single-
|
|
377
|
+
// Only attached in multi-column mode; the single-column jsonb default is unaffected.
|
|
151
378
|
if (multiColumn) {
|
|
152
|
-
fieldConfig.
|
|
153
|
-
|
|
154
|
-
return fileColumnDescriptors(
|
|
155
|
-
name: col.name,
|
|
156
|
-
type: col.type,
|
|
157
|
-
modifiers: '?',
|
|
158
|
-
map: col.map,
|
|
159
|
-
}));
|
|
379
|
+
fieldConfig.getContractField = (fieldName) => {
|
|
380
|
+
refuseNullabilityOverride(options.db);
|
|
381
|
+
return partColumns(fileColumnDescriptors(columnMapFor(fieldName), fileParts));
|
|
160
382
|
};
|
|
161
383
|
fieldConfig.getColumnNames = (fieldName) => fileColumnNames(columnMapFor(fieldName), fileParts);
|
|
162
384
|
fieldConfig.assembleColumns = (fieldName, row) => assembleFileMetadata(row, columnMapFor(fieldName), fieldConfig.storage, fileParts);
|
|
@@ -168,6 +390,7 @@ export function file(options) {
|
|
|
168
390
|
* Creates an image upload field with optional transformations
|
|
169
391
|
*
|
|
170
392
|
* Uses JSON field backing to store image metadata including dimensions, transformations, etc.
|
|
393
|
+
* `transformations` cannot be combined with `db.columns` (multi-column mode); the field throws.
|
|
171
394
|
*
|
|
172
395
|
* @example
|
|
173
396
|
* ```typescript
|
|
@@ -188,35 +411,79 @@ export function file(options) {
|
|
|
188
411
|
*/
|
|
189
412
|
export function image(options) {
|
|
190
413
|
const { hooks: userHooks, ...restOptions } = options;
|
|
414
|
+
refuseMultiColumnTransformations(options.db, options.transformations);
|
|
191
415
|
// See ADR-0006.
|
|
192
416
|
const multiColumn = isMultiColumn(options.db?.columns);
|
|
193
417
|
const columnMapFor = (fieldName) => resolveImageColumnMap(fieldName, imageColumnOverrides(options.db?.columns));
|
|
418
|
+
const nullable = resolveNullable(options.db);
|
|
419
|
+
const faces = metadataFaces("import('@opensaas/stack-storage').ImageMetadata", nullable);
|
|
420
|
+
const cleanupAfterTransaction = async ({ status, operation, inputData, originalItem, fieldKey, listKey, context,
|
|
421
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Field builder hooks are generic and resolved at runtime
|
|
422
|
+
}) => {
|
|
423
|
+
if (operation === 'delete') {
|
|
424
|
+
if (status !== 'committed' || !fieldConfig.cleanupOnDelete)
|
|
425
|
+
return;
|
|
426
|
+
const deleted = logicalValue(fieldConfig, fieldKey, originalItem);
|
|
427
|
+
if (!deleted || typeof deleted !== 'object' || !deleted.filename)
|
|
428
|
+
return;
|
|
429
|
+
try {
|
|
430
|
+
if (await isAssetReferenced(context, listKey, fieldKey, fieldConfig, deleted.filename))
|
|
431
|
+
return;
|
|
432
|
+
await context.storage.deleteImage({
|
|
433
|
+
...(await withoutSharedVariants(context, listKey, fieldKey, fieldConfig, deleted)),
|
|
434
|
+
storageProvider: fieldConfig.storage,
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
catch (error) {
|
|
438
|
+
console.error(`Failed to cleanup image on delete: ${deleted.filename}`, error);
|
|
439
|
+
}
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
const pending = pendingImageUploads.take(inputData, fieldKey);
|
|
443
|
+
if (!pending)
|
|
444
|
+
return;
|
|
445
|
+
for (const stale of staleAssets(pending, status)) {
|
|
446
|
+
try {
|
|
447
|
+
if (await isAssetReferenced(context, listKey, fieldKey, fieldConfig, stale.filename))
|
|
448
|
+
continue;
|
|
449
|
+
await context.storage.deleteImage({
|
|
450
|
+
...(await withoutSharedVariants(context, listKey, fieldKey, fieldConfig, stale)),
|
|
451
|
+
storageProvider: fieldConfig.storage,
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
catch (error) {
|
|
455
|
+
console.error(`Failed to cleanup image: ${stale.filename}`, error);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
};
|
|
194
459
|
const fieldConfig = {
|
|
195
460
|
type: 'image',
|
|
461
|
+
outputType: faces.outputType,
|
|
462
|
+
inputType: faces.inputType,
|
|
196
463
|
...restOptions,
|
|
197
|
-
|
|
198
|
-
// Multi-column mode adds the same logical field back via TransformedFields
|
|
199
|
-
// while the raw per-part columns are stripped from the payload.
|
|
200
|
-
resultExtension: {
|
|
201
|
-
outputType: "import('@opensaas/stack-storage').ImageMetadata | null",
|
|
202
|
-
},
|
|
203
|
-
hooks: {
|
|
464
|
+
hooks: composeFieldHooks({
|
|
204
465
|
// Keystone-compliant field resolveInput args: the field value lives at
|
|
205
466
|
// `resolvedData[fieldKey]`. See FieldResolveInputHookArgs in core.
|
|
206
467
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Field builder hooks are generic and resolved at runtime
|
|
207
|
-
resolveInput: async (
|
|
468
|
+
resolveInput: async (args) => {
|
|
469
|
+
const { resolvedData, inputData, fieldKey, listKey, context, item, operation } = args;
|
|
208
470
|
const inputValue = resolvedData?.[fieldKey];
|
|
209
471
|
if (inputValue === null || inputValue === undefined) {
|
|
210
472
|
return inputValue;
|
|
211
473
|
}
|
|
212
474
|
// An existing metadata value is AUTHORITATIVE and must never
|
|
213
|
-
// re-upload
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
475
|
+
// re-upload — but only when it is genuinely the row's own currently
|
|
476
|
+
// stored value, or the write is sudo. See ADR-0006 and issue #1619.
|
|
477
|
+
if (isImageMetadataShaped(inputValue)) {
|
|
478
|
+
return authorizeStoredMetadata({
|
|
479
|
+
value: inputValue,
|
|
480
|
+
fieldKey,
|
|
481
|
+
operation,
|
|
482
|
+
isSudo: context._isSudo === true,
|
|
483
|
+
currentValue: () => fieldConfig.assembleColumns
|
|
484
|
+
? fieldConfig.assembleColumns(fieldKey, (item ?? {}))
|
|
485
|
+
: (item?.[fieldKey] ?? null),
|
|
486
|
+
});
|
|
220
487
|
}
|
|
221
488
|
if (isFileLike(inputValue)) {
|
|
222
489
|
const fileObj = inputValue;
|
|
@@ -224,46 +491,25 @@ export function image(options) {
|
|
|
224
491
|
const buffer = Buffer.from(arrayBuffer);
|
|
225
492
|
const metadata = (await context.storage.uploadImage(fieldConfig.storage, fileObj, buffer, {
|
|
226
493
|
validation: fieldConfig.validation,
|
|
227
|
-
|
|
494
|
+
claimStableKey: claimStableKeyFor(context, listKey, fieldKey, fieldConfig, item),
|
|
495
|
+
transformations: multiColumn ? undefined : fieldConfig.transformations,
|
|
228
496
|
}));
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
}
|
|
235
|
-
catch (error) {
|
|
236
|
-
console.error(`Failed to cleanup old image: ${oldMetadata.filename}`, error);
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
}
|
|
497
|
+
const previous = logicalValue(fieldConfig, fieldKey, item);
|
|
498
|
+
pendingImageUploads.set(inputData, fieldKey, {
|
|
499
|
+
uploaded: metadata,
|
|
500
|
+
replaced: fieldConfig.cleanupOnReplace ? (previous ?? null) : null,
|
|
501
|
+
});
|
|
240
502
|
return metadata;
|
|
241
503
|
}
|
|
242
504
|
// Unknown type - return as-is and let validation catch it
|
|
243
505
|
return inputValue;
|
|
244
506
|
},
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
// The deleted row is `originalItem`.
|
|
248
|
-
if (operation === 'delete' && fieldConfig.cleanupOnDelete) {
|
|
249
|
-
const imageMetadata = originalItem?.[fieldKey];
|
|
250
|
-
if (imageMetadata && typeof imageMetadata === 'object' && imageMetadata.filename) {
|
|
251
|
-
try {
|
|
252
|
-
await context.storage.deleteImage(imageMetadata);
|
|
253
|
-
}
|
|
254
|
-
catch (error) {
|
|
255
|
-
console.error(`Failed to cleanup image on delete: ${imageMetadata.filename}`, error);
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
},
|
|
260
|
-
...userHooks,
|
|
261
|
-
},
|
|
262
|
-
getZodSchema: (_fieldName, _operation) => {
|
|
507
|
+
}, userHooks, cleanupAfterTransaction, pendingImageUploads, (args) => previousOnClear(fieldConfig, args)),
|
|
508
|
+
getZodSchema: (_fieldName, operation) => {
|
|
263
509
|
const imageMetadataSchema = z.object({
|
|
264
510
|
filename: z.string(),
|
|
265
511
|
originalFilename: z.string(),
|
|
266
|
-
url:
|
|
512
|
+
url: storedUrlSchema,
|
|
267
513
|
mimeType: z.string(),
|
|
268
514
|
size: z.number(),
|
|
269
515
|
width: z.number(),
|
|
@@ -273,45 +519,22 @@ export function image(options) {
|
|
|
273
519
|
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
274
520
|
transformations: z
|
|
275
521
|
.record(z.string(), z.object({
|
|
276
|
-
url:
|
|
522
|
+
url: storedUrlSchema,
|
|
277
523
|
width: z.number(),
|
|
278
524
|
height: z.number(),
|
|
279
525
|
size: z.number(),
|
|
280
526
|
}))
|
|
281
527
|
.optional(),
|
|
282
528
|
});
|
|
283
|
-
|
|
284
|
-
return imageMetadataSchema.nullish();
|
|
285
|
-
},
|
|
286
|
-
getPrismaType: (_fieldName) => {
|
|
287
|
-
return { type: 'Json', modifiers: '?' };
|
|
288
|
-
},
|
|
289
|
-
getTypeScriptType: () => {
|
|
290
|
-
return {
|
|
291
|
-
type: 'ImageMetadata | null',
|
|
292
|
-
optional: true,
|
|
293
|
-
};
|
|
294
|
-
},
|
|
295
|
-
getTypeScriptImports: () => {
|
|
296
|
-
return [
|
|
297
|
-
{
|
|
298
|
-
names: ['ImageMetadata'],
|
|
299
|
-
from: '@opensaas/stack-storage',
|
|
300
|
-
typeOnly: true,
|
|
301
|
-
},
|
|
302
|
-
];
|
|
529
|
+
return applyNullability(imageMetadataSchema, nullable, operation);
|
|
303
530
|
},
|
|
531
|
+
getContractField: (fieldName) => metadataColumn(fieldName, options.db),
|
|
304
532
|
};
|
|
305
|
-
// Only attached in multi-column mode; the single-
|
|
533
|
+
// Only attached in multi-column mode; the single-column jsonb default is unaffected.
|
|
306
534
|
if (multiColumn) {
|
|
307
|
-
fieldConfig.
|
|
308
|
-
|
|
309
|
-
return imageColumnDescriptors(
|
|
310
|
-
name: col.name,
|
|
311
|
-
type: col.type,
|
|
312
|
-
modifiers: '?',
|
|
313
|
-
map: col.map,
|
|
314
|
-
}));
|
|
535
|
+
fieldConfig.getContractField = (fieldName) => {
|
|
536
|
+
refuseNullabilityOverride(options.db);
|
|
537
|
+
return partColumns(imageColumnDescriptors(columnMapFor(fieldName)));
|
|
315
538
|
};
|
|
316
539
|
fieldConfig.getColumnNames = (fieldName) => imageColumnNames(columnMapFor(fieldName));
|
|
317
540
|
fieldConfig.assembleColumns = (fieldName, row) => assembleImageMetadata(row, columnMapFor(fieldName), fieldConfig.storage);
|