@opensaas/stack-storage 0.43.0 → 0.44.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +451 -0
  2. package/README.md +62 -30
  3. package/dist/.build-hash +1 -0
  4. package/dist/fields/index.d.ts +9 -8
  5. package/dist/fields/index.d.ts.map +1 -1
  6. package/dist/fields/index.js +376 -153
  7. package/dist/fields/index.js.map +1 -1
  8. package/dist/providers/local.d.ts +8 -0
  9. package/dist/providers/local.d.ts.map +1 -1
  10. package/dist/providers/local.js +56 -5
  11. package/dist/providers/local.js.map +1 -1
  12. package/dist/runtime/index.d.ts +29 -0
  13. package/dist/runtime/index.d.ts.map +1 -1
  14. package/dist/runtime/index.js +244 -29
  15. package/dist/runtime/index.js.map +1 -1
  16. package/dist/utils/asset-references.d.ts +13 -0
  17. package/dist/utils/asset-references.d.ts.map +1 -0
  18. package/dist/utils/asset-references.js +40 -0
  19. package/dist/utils/asset-references.js.map +1 -0
  20. package/dist/utils/image.d.ts +17 -0
  21. package/dist/utils/image.d.ts.map +1 -1
  22. package/dist/utils/image.js +69 -22
  23. package/dist/utils/image.js.map +1 -1
  24. package/dist/utils/metadata-trust.d.ts +30 -0
  25. package/dist/utils/metadata-trust.d.ts.map +1 -0
  26. package/dist/utils/metadata-trust.js +57 -0
  27. package/dist/utils/metadata-trust.js.map +1 -0
  28. package/dist/utils/multi-column.d.ts +7 -7
  29. package/dist/utils/multi-column.d.ts.map +1 -1
  30. package/dist/utils/multi-column.js +17 -34
  31. package/dist/utils/multi-column.js.map +1 -1
  32. package/dist/utils/upload.d.ts +58 -0
  33. package/dist/utils/upload.d.ts.map +1 -1
  34. package/dist/utils/upload.js +144 -14
  35. package/dist/utils/upload.js.map +1 -1
  36. package/package.json +20 -9
  37. package/.turbo/turbo-build.log +0 -4
  38. package/CLAUDE.md +0 -528
  39. package/src/config/index.ts +0 -30
  40. package/src/config/types.ts +0 -92
  41. package/src/fields/index.ts +0 -531
  42. package/src/index.ts +0 -14
  43. package/src/providers/index.ts +0 -1
  44. package/src/providers/local.ts +0 -79
  45. package/src/runtime/index.ts +0 -244
  46. package/src/runtime/registry.ts +0 -106
  47. package/src/utils/image.ts +0 -95
  48. package/src/utils/index.ts +0 -3
  49. package/src/utils/multi-column.ts +0 -425
  50. package/src/utils/upload.ts +0 -95
  51. package/tests/field-zod-schema.test.ts +0 -133
  52. package/tests/image-utils.test.ts +0 -498
  53. package/tests/local-provider.test.ts +0 -364
  54. package/tests/multi-column-fields.test.ts +0 -393
  55. package/tests/multi-column.test.ts +0 -453
  56. package/tests/opensaas-image-file-write-validation.test.ts +0 -294
  57. package/tests/provider-registry.test.ts +0 -201
  58. package/tests/upload-utils.test.ts +0 -313
  59. package/tsconfig.json +0 -9
  60. package/vitest.config.ts +0 -14
@@ -1,294 +0,0 @@
1
- import { describe, it, expect, vi } from 'vitest'
2
- import { ValidationError, type FieldConfig } from '@opensaas/stack-core'
3
- import { validateWithZod } from '@opensaas/stack-core/internal'
4
- import { image, file } from '../src/fields/index.js'
5
- import type { ImageMetadata, FileMetadata } from '../src/config/types.js'
6
-
7
- /**
8
- * End-to-end regression coverage for #789/#790: a wrong-shape write value for
9
- * an `image()`/`file()` field must be rejected by validation instead of being
10
- * silently split into null/undefined physical columns.
11
- *
12
- * This exercises the REAL field pipeline pieces in the order the Hook
13
- * Pipeline runs them (see `packages/core/src/context/hook-pipeline.ts`):
14
- *
15
- * field `resolveInput` → built-in field rules → `splitColumns`
16
- *
17
- * `runValidateFieldRules` below mirrors core's `validateFieldRules`
18
- * (`packages/core/src/hooks/index.ts`) — itself a thin formatting wrapper
19
- * over the public `validateWithZod` export — so this test validates against
20
- * the exact Zod schema (`field.getZodSchema`) Phase 3 of the real pipeline
21
- * runs, and throws the real `ValidationError` class on failure. `splitColumns`
22
- * is only invoked when that validation passes, matching the #789 phase order
23
- * (validate the LOGICAL value before splitting into physical columns).
24
- */
25
-
26
- /** A File-like stub with an arrayBuffer() method (triggers an upload). */
27
- function fakeFile(bytes = [1, 2, 3]): File {
28
- return {
29
- name: 'photo.png',
30
- type: 'image/png',
31
- arrayBuffer: async () => new Uint8Array(bytes).buffer,
32
- } as unknown as File
33
- }
34
-
35
- /**
36
- * The legacy Keystone GraphQL upload wrapper shape (`{ upload: File }`). It
37
- * has neither `.arrayBuffer()` (so it isn't File-like) nor `filename`/`url`
38
- * keys (so it doesn't look like already-shaped metadata either) — the
39
- * unrecognised shape that reproduces the original silent-corruption bug.
40
- */
41
- function legacyUploadWrapper(): unknown {
42
- return { upload: fakeFile() }
43
- }
44
-
45
- function makeContext() {
46
- const uploadImage = vi.fn(async (): Promise<ImageMetadata> => ({
47
- filename: 'new.png',
48
- originalFilename: 'photo.png',
49
- url: '/uploads/new.png',
50
- mimeType: 'image/png',
51
- size: 3,
52
- width: 10,
53
- height: 10,
54
- uploadedAt: new Date().toISOString(),
55
- storageProvider: 'images',
56
- }))
57
- const uploadFile = vi.fn(async (): Promise<FileMetadata> => ({
58
- filename: 'new.pdf',
59
- originalFilename: 'doc.pdf',
60
- url: '/uploads/new.pdf',
61
- mimeType: 'application/pdf',
62
- size: 3,
63
- uploadedAt: new Date().toISOString(),
64
- storageProvider: 'documents',
65
- }))
66
- return {
67
- context: { storage: { uploadImage, uploadFile, deleteImage: vi.fn(), deleteFile: vi.fn() } },
68
- uploadImage,
69
- uploadFile,
70
- }
71
- }
72
-
73
- /** Mirrors core's `validateFieldRules` — throws the real `ValidationError` on failure. */
74
- function runValidateFieldRules(
75
- data: Record<string, unknown>,
76
- fieldConfigs: Record<string, FieldConfig>,
77
- operation: 'create' | 'update',
78
- ): void {
79
- const result = validateWithZod(data, fieldConfigs, operation)
80
- if (!result.success) {
81
- throw new ValidationError(Object.values(result.errors), result.errors)
82
- }
83
- }
84
-
85
- /**
86
- * Runs the real resolveInput → validate → splitColumns sequence for one field
87
- * and one input value, in that order. `splitColumns` is only reached if
88
- * validation does not throw — exactly the #789 phase order.
89
- */
90
- async function resolveValidateAndSplit(
91
- field: FieldConfig,
92
- fieldKey: string,
93
- operation: 'create' | 'update',
94
- inputValue: unknown,
95
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- test helper threads through a minimal context stub
96
- context: any,
97
- item?: Record<string, unknown>,
98
- ): Promise<Record<string, unknown>> {
99
- const resolved = await field.hooks!.resolveInput!({
100
- listKey: 'Post',
101
- fieldKey,
102
- operation,
103
- inputData: { [fieldKey]: inputValue },
104
- item,
105
- resolvedData: { [fieldKey]: inputValue },
106
- context,
107
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
108
- } as any)
109
-
110
- runValidateFieldRules({ [fieldKey]: resolved }, { [fieldKey]: field }, operation)
111
-
112
- return field.splitColumns!(fieldKey, resolved)
113
- }
114
-
115
- describe('image()/file() write validation matrix (#790)', () => {
116
- describe('db.columns: "keystone" (multi-column) mode', () => {
117
- describe('image()', () => {
118
- const field = image({ storage: 'images', db: { columns: 'keystone' } })
119
-
120
- it('rejects the legacy Keystone upload-wrapper shape with a thrown ValidationError', async () => {
121
- const { context } = makeContext()
122
- const splitSpy = vi.spyOn(field, 'splitColumns')
123
-
124
- await expect(
125
- resolveValidateAndSplit(field, 'image', 'create', legacyUploadWrapper(), context),
126
- ).rejects.toThrow(ValidationError)
127
-
128
- // splitColumns must never run once validation has rejected the value —
129
- // this is the exact mechanism that used to silently corrupt data.
130
- expect(splitSpy).not.toHaveBeenCalled()
131
- })
132
-
133
- it('clears every column for a null value', async () => {
134
- const { context } = makeContext()
135
- const columns = await resolveValidateAndSplit(field, 'image', 'update', null, context)
136
- expect(columns).toEqual({
137
- image_url: null,
138
- image_width: null,
139
- image_height: null,
140
- image_filesize: null,
141
- image_contentType: null,
142
- image_contentDisposition: null,
143
- image_pathname: null,
144
- })
145
- })
146
-
147
- it('keeps an already-shaped ImageMetadata unchanged (no re-upload) and splits it', async () => {
148
- const { context, uploadImage } = makeContext()
149
- const existing: ImageMetadata = {
150
- filename: 'a.jpg',
151
- originalFilename: 'a.jpg',
152
- url: '/u/a.jpg',
153
- mimeType: 'image/jpeg',
154
- size: 1024,
155
- width: 100,
156
- height: 50,
157
- uploadedAt: '',
158
- storageProvider: 'images',
159
- }
160
- const columns = await resolveValidateAndSplit(field, 'image', 'update', existing, context, {
161
- image: existing,
162
- })
163
- expect(uploadImage).not.toHaveBeenCalled()
164
- expect(columns).toEqual({
165
- image_url: '/u/a.jpg',
166
- image_width: 100,
167
- image_height: 50,
168
- image_filesize: 1024,
169
- image_contentType: 'image/jpeg',
170
- image_contentDisposition: null,
171
- image_pathname: 'a.jpg',
172
- })
173
- })
174
-
175
- it('uploads a File-like value and splits the returned metadata', async () => {
176
- const { context, uploadImage } = makeContext()
177
- const columns = await resolveValidateAndSplit(field, 'image', 'create', fakeFile(), context)
178
- expect(uploadImage).toHaveBeenCalledTimes(1)
179
- expect(columns).toMatchObject({
180
- image_url: '/uploads/new.png',
181
- image_width: 10,
182
- image_height: 10,
183
- image_filesize: 3,
184
- image_contentType: 'image/png',
185
- })
186
- })
187
- })
188
-
189
- describe('file()', () => {
190
- const field = file({ storage: 'documents', db: { columns: 'keystone' } })
191
-
192
- it('rejects the legacy Keystone upload-wrapper shape with a thrown ValidationError', async () => {
193
- const { context } = makeContext()
194
- const splitSpy = vi.spyOn(field, 'splitColumns')
195
-
196
- await expect(
197
- resolveValidateAndSplit(field, 'doc', 'create', legacyUploadWrapper(), context),
198
- ).rejects.toThrow(ValidationError)
199
- expect(splitSpy).not.toHaveBeenCalled()
200
- })
201
-
202
- it('clears every column for a null value', async () => {
203
- const { context } = makeContext()
204
- const columns = await resolveValidateAndSplit(field, 'doc', 'update', null, context)
205
- expect(columns).toEqual({ doc_filename: null, doc_filesize: null, doc_url: null })
206
- })
207
-
208
- it('keeps an already-shaped FileMetadata unchanged (no re-upload) and splits it', async () => {
209
- const { context, uploadFile } = makeContext()
210
- const existing: FileMetadata = {
211
- filename: 'report.pdf',
212
- originalFilename: 'report.pdf',
213
- url: 'https://cdn/report.pdf',
214
- mimeType: 'application/pdf',
215
- size: 4096,
216
- uploadedAt: '',
217
- storageProvider: 'documents',
218
- }
219
- const columns = await resolveValidateAndSplit(field, 'doc', 'update', existing, context, {
220
- doc: existing,
221
- })
222
- expect(uploadFile).not.toHaveBeenCalled()
223
- expect(columns).toEqual({
224
- doc_filename: 'report.pdf',
225
- doc_filesize: 4096,
226
- doc_url: 'https://cdn/report.pdf',
227
- })
228
- })
229
-
230
- it('uploads a File-like value and splits the returned metadata', async () => {
231
- const { context, uploadFile } = makeContext()
232
- const columns = await resolveValidateAndSplit(field, 'doc', 'create', fakeFile(), context)
233
- expect(uploadFile).toHaveBeenCalledTimes(1)
234
- expect(columns).toEqual({
235
- doc_filename: 'new.pdf',
236
- doc_filesize: 3,
237
- doc_url: '/uploads/new.pdf',
238
- })
239
- })
240
- })
241
- })
242
-
243
- describe('default single-column (JSON) mode — comparison baseline', () => {
244
- // No `db.columns: 'keystone'` — these fields have no `splitColumns`, so the
245
- // resolved logical value goes straight to the database as `Json?`. The
246
- // downstream report's own caveat was that this path was never explicitly
247
- // verified; these assertions close that gap (it already throws today).
248
- describe('image()', () => {
249
- const field = image({ storage: 'images' })
250
-
251
- it('already rejects the legacy upload-wrapper shape (baseline, unaffected by #789)', async () => {
252
- expect(field.splitColumns).toBeUndefined()
253
- const { context } = makeContext()
254
- const resolved = await field.hooks!.resolveInput!({
255
- listKey: 'Post',
256
- fieldKey: 'image',
257
- operation: 'create',
258
- inputData: { image: legacyUploadWrapper() },
259
- item: undefined,
260
- resolvedData: { image: legacyUploadWrapper() },
261
- context,
262
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
263
- } as any)
264
-
265
- expect(() =>
266
- runValidateFieldRules({ image: resolved }, { image: field }, 'create'),
267
- ).toThrow(ValidationError)
268
- })
269
- })
270
-
271
- describe('file()', () => {
272
- const field = file({ storage: 'documents' })
273
-
274
- it('already rejects the legacy upload-wrapper shape (baseline, unaffected by #789)', async () => {
275
- expect(field.splitColumns).toBeUndefined()
276
- const { context } = makeContext()
277
- const resolved = await field.hooks!.resolveInput!({
278
- listKey: 'Post',
279
- fieldKey: 'doc',
280
- operation: 'create',
281
- inputData: { doc: legacyUploadWrapper() },
282
- item: undefined,
283
- resolvedData: { doc: legacyUploadWrapper() },
284
- context,
285
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
286
- } as any)
287
-
288
- expect(() => runValidateFieldRules({ doc: resolved }, { doc: field }, 'create')).toThrow(
289
- ValidationError,
290
- )
291
- })
292
- })
293
- })
294
- })
@@ -1,201 +0,0 @@
1
- import { describe, it, expect, beforeEach } from 'vitest'
2
- import type { OpenSaasConfig } from '@opensaas/stack-core'
3
- import {
4
- createStorageProvider,
5
- registerStorageProvider,
6
- getStorageProviderFactory,
7
- hasStorageProvider,
8
- resetStorageProviderRegistry,
9
- } from '../src/runtime/index.js'
10
- import { LocalStorageProvider } from '../src/providers/local.js'
11
- import { assembleImageMetadata, keystoneImageColumnMap } from '../src/utils/multi-column.js'
12
- import type {
13
- StorageProvider,
14
- UploadOptions,
15
- UploadResult,
16
- BaseStorageConfig,
17
- } from '../src/config/types.js'
18
-
19
- /**
20
- * A minimal custom provider config + implementation used to prove that a
21
- * non-`local`, host-registered provider can be constructed via the registry —
22
- * without `@opensaas/stack-storage` depending on `-s3`/`-vercel`.
23
- */
24
- interface FakeStorageConfig extends BaseStorageConfig {
25
- type: 'fake'
26
- baseUrl: string
27
- }
28
-
29
- class FakeStorageProvider implements StorageProvider {
30
- constructor(public readonly config: FakeStorageConfig) {}
31
-
32
- async upload(
33
- _file: Buffer | Uint8Array,
34
- filename: string,
35
- options?: UploadOptions,
36
- ): Promise<UploadResult> {
37
- return {
38
- filename,
39
- url: `${this.config.baseUrl}/${filename}`,
40
- size: 0,
41
- contentType: options?.contentType ?? 'application/octet-stream',
42
- }
43
- }
44
-
45
- async download(): Promise<Buffer> {
46
- return Buffer.from('')
47
- }
48
-
49
- async delete(): Promise<void> {}
50
-
51
- getUrl(filename: string): string {
52
- return `${this.config.baseUrl}/${filename}`
53
- }
54
- }
55
-
56
- /** Builds a minimal, strongly-typed config carrying a single storage provider. */
57
- function configWith(name: string, providerConfig: BaseStorageConfig): OpenSaasConfig {
58
- return {
59
- db: { provider: 'sqlite' },
60
- lists: {},
61
- storage: { [name]: providerConfig },
62
- }
63
- }
64
-
65
- describe('storage provider registry', () => {
66
- beforeEach(() => {
67
- // Restore registry to built-in defaults so registrations don't leak.
68
- resetStorageProviderRegistry()
69
- })
70
-
71
- describe('built-in defaults', () => {
72
- it("registers 'local' by default so createStorageProvider builds it", () => {
73
- const config = configWith('files', {
74
- type: 'local',
75
- uploadDir: './uploads',
76
- serveUrl: '/uploads',
77
- })
78
-
79
- const provider = createStorageProvider(config, 'files')
80
-
81
- expect(provider).toBeInstanceOf(LocalStorageProvider)
82
- })
83
-
84
- it("reports 'local' as registered", () => {
85
- expect(hasStorageProvider('local')).toBe(true)
86
- expect(getStorageProviderFactory('local')).toBeTypeOf('function')
87
- })
88
- })
89
-
90
- describe('registering a custom provider', () => {
91
- it('lets createStorageProvider construct a registered non-local provider', () => {
92
- registerStorageProvider<FakeStorageConfig>(
93
- 'fake',
94
- (providerConfig) => new FakeStorageProvider(providerConfig),
95
- )
96
-
97
- const config = configWith('cdn', {
98
- type: 'fake',
99
- baseUrl: 'https://cdn.example.com',
100
- })
101
-
102
- const provider = createStorageProvider(config, 'cdn')
103
-
104
- expect(provider).toBeInstanceOf(FakeStorageProvider)
105
- expect(provider.getUrl('photo.jpg')).toBe('https://cdn.example.com/photo.jpg')
106
- })
107
-
108
- it('passes the provider config through to the factory', () => {
109
- let received: FakeStorageConfig | undefined
110
- registerStorageProvider<FakeStorageConfig>('fake', (providerConfig) => {
111
- received = providerConfig
112
- return new FakeStorageProvider(providerConfig)
113
- })
114
-
115
- const providerConfig: FakeStorageConfig = {
116
- type: 'fake',
117
- baseUrl: 'https://assets.example.com',
118
- }
119
-
120
- createStorageProvider(configWith('assets', providerConfig), 'assets')
121
-
122
- expect(received).toEqual(providerConfig)
123
- })
124
-
125
- it('reflects registration via hasStorageProvider/getStorageProviderFactory', () => {
126
- expect(hasStorageProvider('fake')).toBe(false)
127
-
128
- registerStorageProvider<FakeStorageConfig>(
129
- 'fake',
130
- (providerConfig) => new FakeStorageProvider(providerConfig),
131
- )
132
-
133
- expect(hasStorageProvider('fake')).toBe(true)
134
- expect(getStorageProviderFactory('fake')).toBeTypeOf('function')
135
- })
136
-
137
- it('overwrites a previous registration for the same type', () => {
138
- registerStorageProvider<FakeStorageConfig>(
139
- 'fake',
140
- (providerConfig) => new FakeStorageProvider({ ...providerConfig, baseUrl: 'first' }),
141
- )
142
- registerStorageProvider<FakeStorageConfig>(
143
- 'fake',
144
- (providerConfig) => new FakeStorageProvider({ ...providerConfig, baseUrl: 'second' }),
145
- )
146
-
147
- const provider = createStorageProvider(
148
- configWith('cdn', { type: 'fake', baseUrl: 'ignored' }),
149
- 'cdn',
150
- )
151
-
152
- expect(provider.getUrl('x')).toBe('second/x')
153
- })
154
- })
155
-
156
- describe('unregistered providers', () => {
157
- it('throws a clear error for an unregistered type', () => {
158
- const config = configWith('cdn', { type: 's3', bucket: 'my-bucket' })
159
-
160
- expect(() => createStorageProvider(config, 'cdn')).toThrow(
161
- /Unknown storage provider type: s3/,
162
- )
163
- expect(() => createStorageProvider(config, 'cdn')).toThrow(/registerStorageProvider/)
164
- })
165
-
166
- it('still throws when the named provider is absent from config', () => {
167
- const config = configWith('files', {
168
- type: 'local',
169
- uploadDir: './uploads',
170
- serveUrl: '/uploads',
171
- })
172
-
173
- expect(() => createStorageProvider(config, 'missing')).toThrow(
174
- /Storage provider 'missing' not found in config/,
175
- )
176
- })
177
- })
178
-
179
- describe('read path is unaffected by the registry', () => {
180
- it('assembleImageMetadata stamps the provider name without constructing a provider', () => {
181
- // No provider registered for 'remote'; the read path must not care.
182
- expect(hasStorageProvider('remote')).toBe(false)
183
-
184
- const map = keystoneImageColumnMap('image')
185
- const row = {
186
- image_url: 'https://cdn.example.com/pic.jpg',
187
- image_width: 800,
188
- image_height: 600,
189
- image_filesize: 1234,
190
- image_contentType: 'image/jpeg',
191
- image_pathname: 'pic.jpg',
192
- }
193
-
194
- const meta = assembleImageMetadata(row, map, 'remote')
195
-
196
- expect(meta).not.toBeNull()
197
- expect(meta?.storageProvider).toBe('remote')
198
- expect(meta?.url).toBe('https://cdn.example.com/pic.jpg')
199
- })
200
- })
201
- })