@opensaas/stack-storage 0.43.0 → 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 +445 -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/src/fields/index.ts
DELETED
|
@@ -1,531 +0,0 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
BaseFieldConfig,
|
|
3
|
-
TypeInfo,
|
|
4
|
-
MultiColumnPrismaResult,
|
|
5
|
-
} from '@opensaas/stack-core/extend'
|
|
6
|
-
import { z } from 'zod'
|
|
7
|
-
import type { ComponentType } from 'react'
|
|
8
|
-
import type { FileMetadata, ImageMetadata, ImageTransformationConfig } from '../config/types.js'
|
|
9
|
-
import type { FileValidationOptions } from '../utils/upload.js'
|
|
10
|
-
import {
|
|
11
|
-
assembleFileMetadata,
|
|
12
|
-
assembleImageMetadata,
|
|
13
|
-
DEFAULT_FILE_COLUMN_PARTS,
|
|
14
|
-
fileColumnDescriptors,
|
|
15
|
-
fileColumnNames,
|
|
16
|
-
imageColumnDescriptors,
|
|
17
|
-
imageColumnNames,
|
|
18
|
-
resolveFileColumnMap,
|
|
19
|
-
resolveImageColumnMap,
|
|
20
|
-
splitFileMetadata,
|
|
21
|
-
splitImageMetadata,
|
|
22
|
-
type FileColumnMap,
|
|
23
|
-
type FileColumnPart,
|
|
24
|
-
type ImageColumnMap,
|
|
25
|
-
} from '../utils/multi-column.js'
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* Multi-column (Keystone-parity) database mode for image()/file() fields.
|
|
29
|
-
*
|
|
30
|
-
* The default backing for image()/file() is a single `Json?` column. A
|
|
31
|
-
* migrating project that already has a Keystone database can instead set
|
|
32
|
-
* `columns: 'keystone'` to map the field onto the existing per-part columns in
|
|
33
|
-
* place — no destructive migration, no re-upload of existing assets. The
|
|
34
|
-
* per-part column names (used in `@map`) follow Keystone's `<field>_<part>`
|
|
35
|
-
* convention and can be overridden individually. See ADR-0006.
|
|
36
|
-
*/
|
|
37
|
-
export interface ImageDbConfig {
|
|
38
|
-
/** Custom database column name for single-Json? mode (unused in multi-column mode). */
|
|
39
|
-
map?: string
|
|
40
|
-
/** Override DB-level nullability for single-Json? mode. */
|
|
41
|
-
isNullable?: boolean
|
|
42
|
-
/** Override the native database type for single-Json? mode. */
|
|
43
|
-
nativeType?: string
|
|
44
|
-
/**
|
|
45
|
-
* Enable multi-column mode by setting `'keystone'`. Per-part column-name
|
|
46
|
-
* overrides may be supplied; any omitted part falls back to the Keystone
|
|
47
|
-
* default `<field>_<part>`.
|
|
48
|
-
*/
|
|
49
|
-
columns?: 'keystone' | { mode: 'keystone'; map?: Partial<ImageColumnMap> }
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* Multi-column (Keystone-parity) database mode for file() fields.
|
|
54
|
-
*/
|
|
55
|
-
export interface FileDbConfig {
|
|
56
|
-
/** Custom database column name for single-Json? mode (unused in multi-column mode). */
|
|
57
|
-
map?: string
|
|
58
|
-
/** Override DB-level nullability for single-Json? mode. */
|
|
59
|
-
isNullable?: boolean
|
|
60
|
-
/** Override the native database type for single-Json? mode. */
|
|
61
|
-
nativeType?: string
|
|
62
|
-
/**
|
|
63
|
-
* Enable multi-column mode by setting `'keystone'`. Per-part column-name
|
|
64
|
-
* overrides may be supplied; any omitted part falls back to the Keystone
|
|
65
|
-
* default `<field>_<part>`.
|
|
66
|
-
*
|
|
67
|
-
* By default only `filename`/`filesize`/`url` are emitted. Pass `parts` to
|
|
68
|
-
* additionally opt into the `pathname`/`contentType` Keystone-parity
|
|
69
|
-
* extras (e.g. `parts: FILE_COLUMN_PARTS` for all five, or a custom subset)
|
|
70
|
-
* — see {@link FILE_COLUMN_PARTS} / {@link DEFAULT_FILE_COLUMN_PARTS}.
|
|
71
|
-
*/
|
|
72
|
-
columns?:
|
|
73
|
-
| 'keystone'
|
|
74
|
-
| { mode: 'keystone'; map?: Partial<FileColumnMap>; parts?: readonly FileColumnPart[] }
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
function isMultiColumn(columns: ImageDbConfig['columns'] | FileDbConfig['columns']): boolean {
|
|
78
|
-
return columns === 'keystone' || (typeof columns === 'object' && columns?.mode === 'keystone')
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
function imageColumnOverrides(
|
|
82
|
-
columns: ImageDbConfig['columns'],
|
|
83
|
-
): Partial<ImageColumnMap> | undefined {
|
|
84
|
-
return typeof columns === 'object' ? columns.map : undefined
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
function fileColumnOverrides(columns: FileDbConfig['columns']): Partial<FileColumnMap> | undefined {
|
|
88
|
-
return typeof columns === 'object' ? columns.map : undefined
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
function fileColumnPartsFor(columns: FileDbConfig['columns']): readonly FileColumnPart[] {
|
|
92
|
-
return typeof columns === 'object' && columns.parts ? columns.parts : DEFAULT_FILE_COLUMN_PARTS
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/**
|
|
96
|
-
* An already-shaped metadata value or populated multi-column row is
|
|
97
|
-
* authoritative and must never trigger a re-upload (the no-re-upload
|
|
98
|
-
* guarantee — see ADR-0006).
|
|
99
|
-
*/
|
|
100
|
-
function isFileLike(value: unknown): value is File {
|
|
101
|
-
return (
|
|
102
|
-
typeof value === 'object' &&
|
|
103
|
-
value !== null &&
|
|
104
|
-
'arrayBuffer' in value &&
|
|
105
|
-
typeof (value as { arrayBuffer?: unknown }).arrayBuffer === 'function'
|
|
106
|
-
)
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
export interface FileFieldConfig<
|
|
110
|
-
TTypeInfo extends TypeInfo = TypeInfo,
|
|
111
|
-
> extends BaseFieldConfig<TTypeInfo> {
|
|
112
|
-
type: 'file'
|
|
113
|
-
/** Name of the storage provider from config.storage */
|
|
114
|
-
storage: string
|
|
115
|
-
/** File validation options */
|
|
116
|
-
validation?: FileValidationOptions
|
|
117
|
-
/** Automatically delete file from storage when record is deleted */
|
|
118
|
-
cleanupOnDelete?: boolean
|
|
119
|
-
/** Automatically delete old file from storage when replaced with new file */
|
|
120
|
-
cleanupOnReplace?: boolean
|
|
121
|
-
/** Database configuration; see {@link FileDbConfig} for multi-column mode. */
|
|
122
|
-
db?: FileDbConfig
|
|
123
|
-
/** UI options */
|
|
124
|
-
ui?: {
|
|
125
|
-
/** Custom component to use for rendering this field */
|
|
126
|
-
component?: ComponentType<unknown>
|
|
127
|
-
/** Custom field type name for component registry lookup */
|
|
128
|
-
fieldType?: string
|
|
129
|
-
/** Label for the field */
|
|
130
|
-
label?: string
|
|
131
|
-
/** Help text shown below the field */
|
|
132
|
-
helpText?: string
|
|
133
|
-
/** Placeholder text */
|
|
134
|
-
placeholder?: string
|
|
135
|
-
/** Additional UI options passed through to component */
|
|
136
|
-
[key: string]: unknown
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
export interface ImageFieldConfig<
|
|
141
|
-
TTypeInfo extends TypeInfo = TypeInfo,
|
|
142
|
-
> extends BaseFieldConfig<TTypeInfo> {
|
|
143
|
-
type: 'image'
|
|
144
|
-
/** Name of the storage provider from config.storage */
|
|
145
|
-
storage: string
|
|
146
|
-
/** Image transformations to generate on upload */
|
|
147
|
-
transformations?: Record<string, ImageTransformationConfig>
|
|
148
|
-
/** File validation options */
|
|
149
|
-
validation?: FileValidationOptions
|
|
150
|
-
/** Automatically delete file from storage when record is deleted */
|
|
151
|
-
cleanupOnDelete?: boolean
|
|
152
|
-
/** Automatically delete old file from storage when replaced with new file */
|
|
153
|
-
cleanupOnReplace?: boolean
|
|
154
|
-
/** Database configuration; see {@link ImageDbConfig} for multi-column mode. */
|
|
155
|
-
db?: ImageDbConfig
|
|
156
|
-
/** UI options */
|
|
157
|
-
ui?: {
|
|
158
|
-
/** Custom component to use for rendering this field */
|
|
159
|
-
component?: ComponentType<unknown>
|
|
160
|
-
/** Custom field type name for component registry lookup */
|
|
161
|
-
fieldType?: string
|
|
162
|
-
/** Label for the field */
|
|
163
|
-
label?: string
|
|
164
|
-
/** Help text shown below the field */
|
|
165
|
-
helpText?: string
|
|
166
|
-
/** Placeholder text */
|
|
167
|
-
placeholder?: string
|
|
168
|
-
/** Show image preview */
|
|
169
|
-
showPreview?: boolean
|
|
170
|
-
/** Preview size (width in pixels) */
|
|
171
|
-
previewSize?: number
|
|
172
|
-
/** Additional UI options passed through to component */
|
|
173
|
-
[key: string]: unknown
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
/**
|
|
178
|
-
* Creates a file upload field
|
|
179
|
-
*
|
|
180
|
-
* Uses JSON field backing to store file metadata including filename, URL, size, MIME type, etc.
|
|
181
|
-
*
|
|
182
|
-
* @example
|
|
183
|
-
* ```typescript
|
|
184
|
-
* fields: {
|
|
185
|
-
* resume: file({
|
|
186
|
-
* storage: 'documents',
|
|
187
|
-
* validation: {
|
|
188
|
-
* maxFileSize: 10 * 1024 * 1024, // 10MB
|
|
189
|
-
* acceptedMimeTypes: ['application/pdf']
|
|
190
|
-
* }
|
|
191
|
-
* })
|
|
192
|
-
* }
|
|
193
|
-
* ```
|
|
194
|
-
*/
|
|
195
|
-
export function file<TTypeInfo extends TypeInfo = TypeInfo>(
|
|
196
|
-
options: Omit<FileFieldConfig<TTypeInfo>, 'type'>,
|
|
197
|
-
): FileFieldConfig<TTypeInfo> {
|
|
198
|
-
const { hooks: userHooks, ...restOptions } = options
|
|
199
|
-
|
|
200
|
-
// Column map resolves lazily per field name so default `<field>_<part>`
|
|
201
|
-
// names line up with the live columns.
|
|
202
|
-
const multiColumn = isMultiColumn(options.db?.columns)
|
|
203
|
-
const columnMapFor = (fieldName: string): FileColumnMap =>
|
|
204
|
-
resolveFileColumnMap(fieldName, fileColumnOverrides(options.db?.columns))
|
|
205
|
-
const fileParts: readonly FileColumnPart[] = fileColumnPartsFor(options.db?.columns)
|
|
206
|
-
|
|
207
|
-
const fieldConfig: FileFieldConfig<TTypeInfo> = {
|
|
208
|
-
type: 'file',
|
|
209
|
-
...restOptions,
|
|
210
|
-
|
|
211
|
-
// Override Prisma's Json type with FileMetadata | null in context.db types.
|
|
212
|
-
// Multi-column mode adds the same logical field back via TransformedFields
|
|
213
|
-
// while the raw per-part columns are stripped from the payload.
|
|
214
|
-
resultExtension: {
|
|
215
|
-
outputType: "import('@opensaas/stack-storage').FileMetadata | null",
|
|
216
|
-
},
|
|
217
|
-
|
|
218
|
-
hooks: {
|
|
219
|
-
// Keystone-compliant field resolveInput args: the field value lives at
|
|
220
|
-
// `resolvedData[fieldKey]`. See FieldResolveInputHookArgs in core.
|
|
221
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Field builder hooks are generic and resolved at runtime
|
|
222
|
-
resolveInput: async ({ resolvedData, fieldKey, context, item }: any) => {
|
|
223
|
-
const inputValue = resolvedData?.[fieldKey]
|
|
224
|
-
|
|
225
|
-
if (inputValue === null || inputValue === undefined) {
|
|
226
|
-
return inputValue
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
// An existing metadata value is AUTHORITATIVE and must never
|
|
230
|
-
// re-upload. See ADR-0006.
|
|
231
|
-
if (typeof inputValue === 'object' && 'filename' in inputValue && 'url' in inputValue) {
|
|
232
|
-
return inputValue as FileMetadata
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
if (isFileLike(inputValue)) {
|
|
236
|
-
const fileObj = inputValue
|
|
237
|
-
const arrayBuffer = await fileObj.arrayBuffer()
|
|
238
|
-
const buffer = Buffer.from(arrayBuffer)
|
|
239
|
-
|
|
240
|
-
const metadata = (await context.storage.uploadFile(fieldConfig.storage, fileObj, buffer, {
|
|
241
|
-
validation: fieldConfig.validation,
|
|
242
|
-
})) as FileMetadata
|
|
243
|
-
|
|
244
|
-
if (fieldConfig.cleanupOnReplace && item && fieldKey) {
|
|
245
|
-
const oldMetadata = item[fieldKey] as FileMetadata | null
|
|
246
|
-
if (oldMetadata && oldMetadata.filename) {
|
|
247
|
-
try {
|
|
248
|
-
await context.storage.deleteFile(oldMetadata.storageProvider, oldMetadata.filename)
|
|
249
|
-
} catch (error) {
|
|
250
|
-
console.error(`Failed to cleanup old file: ${oldMetadata.filename}`, error)
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
return metadata
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
// Unknown type - return as-is and let validation catch it
|
|
259
|
-
return inputValue
|
|
260
|
-
},
|
|
261
|
-
|
|
262
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Field builder hooks are generic and resolved at runtime
|
|
263
|
-
afterOperation: async ({ operation, originalItem, fieldKey, context }: any) => {
|
|
264
|
-
// The deleted row is `originalItem`.
|
|
265
|
-
if (operation === 'delete' && fieldConfig.cleanupOnDelete) {
|
|
266
|
-
const fileMetadata = originalItem?.[fieldKey] as FileMetadata | null
|
|
267
|
-
|
|
268
|
-
if (fileMetadata && typeof fileMetadata === 'object' && fileMetadata.filename) {
|
|
269
|
-
try {
|
|
270
|
-
await context.storage.deleteFile(fileMetadata.storageProvider, fileMetadata.filename)
|
|
271
|
-
} catch (error) {
|
|
272
|
-
console.error(`Failed to cleanup file on delete: ${fileMetadata.filename}`, error)
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
},
|
|
277
|
-
...userHooks,
|
|
278
|
-
},
|
|
279
|
-
|
|
280
|
-
getZodSchema: (_fieldName: string, _operation: 'create' | 'update') => {
|
|
281
|
-
const fileMetadataSchema = z.object({
|
|
282
|
-
filename: z.string(),
|
|
283
|
-
originalFilename: z.string(),
|
|
284
|
-
url: z.string(), // Accept both absolute URLs and relative paths
|
|
285
|
-
mimeType: z.string(),
|
|
286
|
-
size: z.number(),
|
|
287
|
-
uploadedAt: z.string(),
|
|
288
|
-
storageProvider: z.string(),
|
|
289
|
-
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
290
|
-
})
|
|
291
|
-
|
|
292
|
-
// Allow null or undefined values. `.nullish()` (= `.nullable().optional()`)
|
|
293
|
-
// makes the object KEY optional in Zod 4 — a bare union that merely accepts
|
|
294
|
-
// an `undefined` value does NOT (see issue #618, and the #570 precedent in
|
|
295
|
-
// core's validation tests).
|
|
296
|
-
return fileMetadataSchema.nullish()
|
|
297
|
-
},
|
|
298
|
-
|
|
299
|
-
getPrismaType: (_fieldName: string) => {
|
|
300
|
-
return { type: 'Json', modifiers: '?' }
|
|
301
|
-
},
|
|
302
|
-
|
|
303
|
-
getTypeScriptType: () => {
|
|
304
|
-
return {
|
|
305
|
-
type: 'FileMetadata | null',
|
|
306
|
-
optional: true,
|
|
307
|
-
}
|
|
308
|
-
},
|
|
309
|
-
|
|
310
|
-
getTypeScriptImports: () => {
|
|
311
|
-
return [
|
|
312
|
-
{
|
|
313
|
-
names: ['FileMetadata'],
|
|
314
|
-
from: '@opensaas/stack-storage',
|
|
315
|
-
typeOnly: true,
|
|
316
|
-
},
|
|
317
|
-
]
|
|
318
|
-
},
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
// Only attached in multi-column mode; the single-Json? default is unaffected.
|
|
322
|
-
if (multiColumn) {
|
|
323
|
-
fieldConfig.getPrismaColumns = (fieldName: string): MultiColumnPrismaResult[] => {
|
|
324
|
-
const map = columnMapFor(fieldName)
|
|
325
|
-
return fileColumnDescriptors(map, fileParts).map((col) => ({
|
|
326
|
-
name: col.name,
|
|
327
|
-
type: col.type,
|
|
328
|
-
modifiers: '?',
|
|
329
|
-
map: col.map,
|
|
330
|
-
}))
|
|
331
|
-
}
|
|
332
|
-
fieldConfig.getColumnNames = (fieldName: string): string[] =>
|
|
333
|
-
fileColumnNames(columnMapFor(fieldName), fileParts)
|
|
334
|
-
fieldConfig.assembleColumns = (fieldName: string, row: Record<string, unknown>): unknown =>
|
|
335
|
-
assembleFileMetadata(row, columnMapFor(fieldName), fieldConfig.storage, fileParts)
|
|
336
|
-
fieldConfig.splitColumns = (fieldName: string, value: unknown): Record<string, unknown> =>
|
|
337
|
-
splitFileMetadata((value ?? null) as FileMetadata | null, columnMapFor(fieldName), fileParts)
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
return fieldConfig
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
/**
|
|
344
|
-
* Creates an image upload field with optional transformations
|
|
345
|
-
*
|
|
346
|
-
* Uses JSON field backing to store image metadata including dimensions, transformations, etc.
|
|
347
|
-
*
|
|
348
|
-
* @example
|
|
349
|
-
* ```typescript
|
|
350
|
-
* fields: {
|
|
351
|
-
* avatar: image({
|
|
352
|
-
* storage: 'avatars',
|
|
353
|
-
* transformations: {
|
|
354
|
-
* thumbnail: { width: 100, height: 100, fit: 'cover' },
|
|
355
|
-
* profile: { width: 400, height: 400, fit: 'cover' }
|
|
356
|
-
* },
|
|
357
|
-
* validation: {
|
|
358
|
-
* maxFileSize: 5 * 1024 * 1024, // 5MB
|
|
359
|
-
* acceptedMimeTypes: ['image/jpeg', 'image/png', 'image/webp']
|
|
360
|
-
* }
|
|
361
|
-
* })
|
|
362
|
-
* }
|
|
363
|
-
* ```
|
|
364
|
-
*/
|
|
365
|
-
export function image<TTypeInfo extends TypeInfo = TypeInfo>(
|
|
366
|
-
options: Omit<ImageFieldConfig<TTypeInfo>, 'type'>,
|
|
367
|
-
): ImageFieldConfig<TTypeInfo> {
|
|
368
|
-
const { hooks: userHooks, ...restOptions } = options
|
|
369
|
-
|
|
370
|
-
// See ADR-0006.
|
|
371
|
-
const multiColumn = isMultiColumn(options.db?.columns)
|
|
372
|
-
const columnMapFor = (fieldName: string): ImageColumnMap =>
|
|
373
|
-
resolveImageColumnMap(fieldName, imageColumnOverrides(options.db?.columns))
|
|
374
|
-
|
|
375
|
-
const fieldConfig: ImageFieldConfig<TTypeInfo> = {
|
|
376
|
-
type: 'image',
|
|
377
|
-
...restOptions,
|
|
378
|
-
|
|
379
|
-
// Override Prisma's Json type with ImageMetadata | null in context.db types.
|
|
380
|
-
// Multi-column mode adds the same logical field back via TransformedFields
|
|
381
|
-
// while the raw per-part columns are stripped from the payload.
|
|
382
|
-
resultExtension: {
|
|
383
|
-
outputType: "import('@opensaas/stack-storage').ImageMetadata | null",
|
|
384
|
-
},
|
|
385
|
-
|
|
386
|
-
hooks: {
|
|
387
|
-
// Keystone-compliant field resolveInput args: the field value lives at
|
|
388
|
-
// `resolvedData[fieldKey]`. See FieldResolveInputHookArgs in core.
|
|
389
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Field builder hooks are generic and resolved at runtime
|
|
390
|
-
resolveInput: async ({ resolvedData, fieldKey, context, item }: any) => {
|
|
391
|
-
const inputValue = resolvedData?.[fieldKey]
|
|
392
|
-
|
|
393
|
-
if (inputValue === null || inputValue === undefined) {
|
|
394
|
-
return inputValue
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
// An existing metadata value is AUTHORITATIVE and must never
|
|
398
|
-
// re-upload. See ADR-0006.
|
|
399
|
-
if (
|
|
400
|
-
typeof inputValue === 'object' &&
|
|
401
|
-
'filename' in inputValue &&
|
|
402
|
-
'url' in inputValue &&
|
|
403
|
-
'width' in inputValue &&
|
|
404
|
-
'height' in inputValue
|
|
405
|
-
) {
|
|
406
|
-
return inputValue as ImageMetadata
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
if (isFileLike(inputValue)) {
|
|
410
|
-
const fileObj = inputValue
|
|
411
|
-
const arrayBuffer = await fileObj.arrayBuffer()
|
|
412
|
-
const buffer = Buffer.from(arrayBuffer)
|
|
413
|
-
|
|
414
|
-
const metadata = (await context.storage.uploadImage(
|
|
415
|
-
fieldConfig.storage,
|
|
416
|
-
fileObj,
|
|
417
|
-
buffer,
|
|
418
|
-
{
|
|
419
|
-
validation: fieldConfig.validation,
|
|
420
|
-
transformations: fieldConfig.transformations,
|
|
421
|
-
},
|
|
422
|
-
)) as ImageMetadata
|
|
423
|
-
|
|
424
|
-
if (fieldConfig.cleanupOnReplace && item && fieldKey) {
|
|
425
|
-
const oldMetadata = item[fieldKey] as ImageMetadata | null
|
|
426
|
-
if (oldMetadata && oldMetadata.filename) {
|
|
427
|
-
try {
|
|
428
|
-
await context.storage.deleteImage(oldMetadata)
|
|
429
|
-
} catch (error) {
|
|
430
|
-
console.error(`Failed to cleanup old image: ${oldMetadata.filename}`, error)
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
return metadata
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
// Unknown type - return as-is and let validation catch it
|
|
439
|
-
return inputValue
|
|
440
|
-
},
|
|
441
|
-
|
|
442
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Field builder hooks are generic and resolved at runtime
|
|
443
|
-
afterOperation: async ({ operation, originalItem, fieldKey, context }: any) => {
|
|
444
|
-
// The deleted row is `originalItem`.
|
|
445
|
-
if (operation === 'delete' && fieldConfig.cleanupOnDelete) {
|
|
446
|
-
const imageMetadata = originalItem?.[fieldKey] as ImageMetadata | null
|
|
447
|
-
|
|
448
|
-
if (imageMetadata && typeof imageMetadata === 'object' && imageMetadata.filename) {
|
|
449
|
-
try {
|
|
450
|
-
await context.storage.deleteImage(imageMetadata)
|
|
451
|
-
} catch (error) {
|
|
452
|
-
console.error(`Failed to cleanup image on delete: ${imageMetadata.filename}`, error)
|
|
453
|
-
}
|
|
454
|
-
}
|
|
455
|
-
}
|
|
456
|
-
},
|
|
457
|
-
...userHooks,
|
|
458
|
-
},
|
|
459
|
-
|
|
460
|
-
getZodSchema: (_fieldName: string, _operation: 'create' | 'update') => {
|
|
461
|
-
const imageMetadataSchema = z.object({
|
|
462
|
-
filename: z.string(),
|
|
463
|
-
originalFilename: z.string(),
|
|
464
|
-
url: z.string(), // Accept both absolute URLs and relative paths
|
|
465
|
-
mimeType: z.string(),
|
|
466
|
-
size: z.number(),
|
|
467
|
-
width: z.number(),
|
|
468
|
-
height: z.number(),
|
|
469
|
-
uploadedAt: z.string(),
|
|
470
|
-
storageProvider: z.string(),
|
|
471
|
-
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
472
|
-
transformations: z
|
|
473
|
-
.record(
|
|
474
|
-
z.string(),
|
|
475
|
-
z.object({
|
|
476
|
-
url: z.string(), // Accept both absolute URLs and relative paths
|
|
477
|
-
width: z.number(),
|
|
478
|
-
height: z.number(),
|
|
479
|
-
size: z.number(),
|
|
480
|
-
}),
|
|
481
|
-
)
|
|
482
|
-
.optional(),
|
|
483
|
-
})
|
|
484
|
-
|
|
485
|
-
// Same `.nullish()` KEY-optionality rationale as file()'s getZodSchema above.
|
|
486
|
-
return imageMetadataSchema.nullish()
|
|
487
|
-
},
|
|
488
|
-
|
|
489
|
-
getPrismaType: (_fieldName: string) => {
|
|
490
|
-
return { type: 'Json', modifiers: '?' }
|
|
491
|
-
},
|
|
492
|
-
|
|
493
|
-
getTypeScriptType: () => {
|
|
494
|
-
return {
|
|
495
|
-
type: 'ImageMetadata | null',
|
|
496
|
-
optional: true,
|
|
497
|
-
}
|
|
498
|
-
},
|
|
499
|
-
|
|
500
|
-
getTypeScriptImports: () => {
|
|
501
|
-
return [
|
|
502
|
-
{
|
|
503
|
-
names: ['ImageMetadata'],
|
|
504
|
-
from: '@opensaas/stack-storage',
|
|
505
|
-
typeOnly: true,
|
|
506
|
-
},
|
|
507
|
-
]
|
|
508
|
-
},
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
// Only attached in multi-column mode; the single-Json? default is unaffected.
|
|
512
|
-
if (multiColumn) {
|
|
513
|
-
fieldConfig.getPrismaColumns = (fieldName: string): MultiColumnPrismaResult[] => {
|
|
514
|
-
const map = columnMapFor(fieldName)
|
|
515
|
-
return imageColumnDescriptors(map).map((col) => ({
|
|
516
|
-
name: col.name,
|
|
517
|
-
type: col.type,
|
|
518
|
-
modifiers: '?',
|
|
519
|
-
map: col.map,
|
|
520
|
-
}))
|
|
521
|
-
}
|
|
522
|
-
fieldConfig.getColumnNames = (fieldName: string): string[] =>
|
|
523
|
-
imageColumnNames(columnMapFor(fieldName))
|
|
524
|
-
fieldConfig.assembleColumns = (fieldName: string, row: Record<string, unknown>): unknown =>
|
|
525
|
-
assembleImageMetadata(row, columnMapFor(fieldName), fieldConfig.storage)
|
|
526
|
-
fieldConfig.splitColumns = (fieldName: string, value: unknown): Record<string, unknown> =>
|
|
527
|
-
splitImageMetadata((value ?? null) as ImageMetadata | null, columnMapFor(fieldName))
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
return fieldConfig
|
|
531
|
-
}
|
package/src/index.ts
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
// Config and types
|
|
2
|
-
export * from './config/index.js'
|
|
3
|
-
|
|
4
|
-
// Field builders
|
|
5
|
-
export * from './fields/index.js'
|
|
6
|
-
|
|
7
|
-
// Storage providers
|
|
8
|
-
export * from './providers/index.js'
|
|
9
|
-
|
|
10
|
-
// Runtime utilities
|
|
11
|
-
export * from './runtime/index.js'
|
|
12
|
-
|
|
13
|
-
// Upload utilities
|
|
14
|
-
export * from './utils/index.js'
|
package/src/providers/index.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { LocalStorageProvider } from './local.js'
|
package/src/providers/local.ts
DELETED
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
import fs from 'node:fs/promises'
|
|
2
|
-
import path from 'node:path'
|
|
3
|
-
import { randomBytes } from 'node:crypto'
|
|
4
|
-
import type {
|
|
5
|
-
StorageProvider,
|
|
6
|
-
UploadOptions,
|
|
7
|
-
UploadResult,
|
|
8
|
-
LocalStorageConfig,
|
|
9
|
-
} from '../config/types.js'
|
|
10
|
-
|
|
11
|
-
export class LocalStorageProvider implements StorageProvider {
|
|
12
|
-
private config: LocalStorageConfig
|
|
13
|
-
|
|
14
|
-
constructor(config: LocalStorageConfig) {
|
|
15
|
-
this.config = config
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
private async ensureUploadDir(): Promise<void> {
|
|
19
|
-
try {
|
|
20
|
-
await fs.access(this.config.uploadDir)
|
|
21
|
-
} catch {
|
|
22
|
-
await fs.mkdir(this.config.uploadDir, { recursive: true })
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
private generateFilename(originalFilename: string): string {
|
|
27
|
-
if (this.config.generateUniqueFilenames === false) {
|
|
28
|
-
return originalFilename
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
const ext = path.extname(originalFilename)
|
|
32
|
-
const uniqueId = randomBytes(16).toString('hex')
|
|
33
|
-
const timestamp = Date.now()
|
|
34
|
-
return `${timestamp}-${uniqueId}${ext}`
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
async upload(
|
|
38
|
-
file: Buffer | Uint8Array,
|
|
39
|
-
filename: string,
|
|
40
|
-
options?: UploadOptions,
|
|
41
|
-
): Promise<UploadResult> {
|
|
42
|
-
await this.ensureUploadDir()
|
|
43
|
-
|
|
44
|
-
const generatedFilename = this.generateFilename(filename)
|
|
45
|
-
const filePath = path.join(this.config.uploadDir, generatedFilename)
|
|
46
|
-
|
|
47
|
-
await fs.writeFile(filePath, file)
|
|
48
|
-
|
|
49
|
-
const stats = await fs.stat(filePath)
|
|
50
|
-
|
|
51
|
-
return {
|
|
52
|
-
filename: generatedFilename,
|
|
53
|
-
url: `${this.config.serveUrl}/${generatedFilename}`,
|
|
54
|
-
size: stats.size,
|
|
55
|
-
contentType: options?.contentType || 'application/octet-stream',
|
|
56
|
-
metadata: options?.metadata,
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
async download(filename: string): Promise<Buffer> {
|
|
61
|
-
const filePath = path.join(this.config.uploadDir, filename)
|
|
62
|
-
return await fs.readFile(filePath)
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
async delete(filename: string): Promise<void> {
|
|
66
|
-
const filePath = path.join(this.config.uploadDir, filename)
|
|
67
|
-
try {
|
|
68
|
-
await fs.unlink(filePath)
|
|
69
|
-
} catch (error) {
|
|
70
|
-
if ((error as { code?: string }).code !== 'ENOENT') {
|
|
71
|
-
throw error
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
getUrl(filename: string): string {
|
|
77
|
-
return `${this.config.serveUrl}/${filename}`
|
|
78
|
-
}
|
|
79
|
-
}
|