@edgestore/server 1.0.0-next.0 → 1.0.0-next.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.
Files changed (115) hide show
  1. package/README.md +10 -4
  2. package/dist/adapters/astro/index.d.ts +7 -12
  3. package/dist/adapters/astro/index.d.ts.map +1 -1
  4. package/dist/adapters/astro/index.js +14 -161
  5. package/dist/adapters/dispatcher.d.ts +30 -0
  6. package/dist/adapters/dispatcher.d.ts.map +1 -0
  7. package/dist/adapters/dispatcher.js +172 -0
  8. package/dist/adapters/express/index.d.ts +7 -12
  9. package/dist/adapters/express/index.d.ts.map +1 -1
  10. package/dist/adapters/express/index.js +24 -94
  11. package/dist/adapters/fastify/index.d.ts +7 -12
  12. package/dist/adapters/fastify/index.d.ts.map +1 -1
  13. package/dist/adapters/fastify/index.js +23 -121
  14. package/dist/adapters/hono/index.d.ts +7 -12
  15. package/dist/adapters/hono/index.d.ts.map +1 -1
  16. package/dist/adapters/hono/index.js +14 -121
  17. package/dist/adapters/next/app/index.d.ts +7 -12
  18. package/dist/adapters/next/app/index.d.ts.map +1 -1
  19. package/dist/adapters/next/app/index.js +21 -148
  20. package/dist/adapters/next/pages/index.d.ts +7 -12
  21. package/dist/adapters/next/pages/index.d.ts.map +1 -1
  22. package/dist/adapters/next/pages/index.js +34 -95
  23. package/dist/adapters/remix/index.d.ts +7 -12
  24. package/dist/adapters/remix/index.d.ts.map +1 -1
  25. package/dist/adapters/remix/index.js +14 -136
  26. package/dist/adapters/shared.d.ts +140 -55
  27. package/dist/adapters/shared.d.ts.map +1 -1
  28. package/dist/adapters/shared.js +188 -179
  29. package/dist/adapters/start/index.d.ts +7 -12
  30. package/dist/adapters/start/index.d.ts.map +1 -1
  31. package/dist/adapters/start/index.js +14 -169
  32. package/dist/core/client/bucketClient.d.ts +7 -0
  33. package/dist/core/client/bucketClient.d.ts.map +1 -0
  34. package/dist/core/client/bucketClient.js +312 -0
  35. package/dist/core/client/index.d.ts +119 -140
  36. package/dist/core/client/index.d.ts.map +1 -1
  37. package/dist/core/client/index.js +13 -218
  38. package/dist/core/index.d.ts +20 -1
  39. package/dist/core/index.d.ts.map +1 -1
  40. package/dist/core/index.js +14 -2
  41. package/dist/core/provider.d.ts +15 -0
  42. package/dist/core/provider.d.ts.map +1 -0
  43. package/dist/core/provider.js +25 -0
  44. package/dist/core/routerRules.d.ts +21 -0
  45. package/dist/core/routerRules.d.ts.map +1 -0
  46. package/dist/core/routerRules.js +54 -0
  47. package/dist/core/validateFile.d.ts +9 -0
  48. package/dist/core/validateFile.d.ts.map +1 -0
  49. package/dist/core/validateFile.js +43 -0
  50. package/dist/index.d.ts +1 -0
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/index.js +3 -0
  53. package/dist/libs/env.d.ts +3 -0
  54. package/dist/libs/env.d.ts.map +1 -0
  55. package/dist/libs/env.js +14 -0
  56. package/dist/libs/logger.d.ts +2 -1
  57. package/dist/libs/logger.d.ts.map +1 -1
  58. package/dist/libs/logger.js +1 -1
  59. package/dist/providers/azure-blob/index.d.ts +119 -0
  60. package/dist/providers/azure-blob/index.d.ts.map +1 -0
  61. package/dist/providers/azure-blob/index.js +166 -0
  62. package/dist/providers/edgestore/index.d.ts +171 -3
  63. package/dist/providers/edgestore/index.d.ts.map +1 -1
  64. package/dist/providers/edgestore/index.js +304 -136
  65. package/dist/providers/{aws → s3}/index.d.ts +68 -11
  66. package/dist/providers/s3/index.d.ts.map +1 -0
  67. package/dist/providers/s3/index.js +146 -0
  68. package/dist/test-utils/edgestoreSmoke.d.ts +0 -2
  69. package/dist/test-utils/edgestoreSmoke.d.ts.map +1 -1
  70. package/dist/version.d.ts +1 -1
  71. package/package.json +13 -12
  72. package/providers/azure-blob/index.d.ts +1 -0
  73. package/providers/azure-blob/index.js +1 -0
  74. package/providers/s3/index.d.ts +1 -0
  75. package/providers/s3/index.js +1 -0
  76. package/src/adapters/astro/index.ts +27 -211
  77. package/src/adapters/dispatcher.ts +261 -0
  78. package/src/adapters/express/index.ts +43 -149
  79. package/src/adapters/fastify/index.ts +43 -191
  80. package/src/adapters/hono/index.ts +28 -183
  81. package/src/adapters/next/app/index.ts +37 -201
  82. package/src/adapters/next/pages/index.ts +55 -156
  83. package/src/adapters/remix/index.ts +27 -190
  84. package/src/adapters/shared.ts +237 -261
  85. package/src/adapters/start/index.ts +28 -200
  86. package/src/core/client/bucketClient.ts +480 -0
  87. package/src/core/client/index.ts +300 -427
  88. package/src/core/index.ts +42 -1
  89. package/src/core/provider.ts +80 -0
  90. package/src/core/routerRules.ts +75 -0
  91. package/src/core/validateFile.ts +50 -0
  92. package/src/index.ts +10 -0
  93. package/src/libs/env.ts +16 -0
  94. package/src/libs/logger.ts +4 -2
  95. package/src/providers/azure-blob/index.ts +265 -0
  96. package/src/providers/edgestore/index.ts +426 -154
  97. package/src/providers/s3/index.ts +289 -0
  98. package/src/test-utils/edgestoreSmoke.ts +0 -11
  99. package/src/version.ts +1 -1
  100. package/dist/core/sdk/index.d.ts +0 -282
  101. package/dist/core/sdk/index.d.ts.map +0 -1
  102. package/dist/core/sdk/index.js +0 -253
  103. package/dist/providers/aws/index.d.ts.map +0 -1
  104. package/dist/providers/aws/index.js +0 -102
  105. package/dist/providers/azure/index.d.ts +0 -39
  106. package/dist/providers/azure/index.d.ts.map +0 -1
  107. package/dist/providers/azure/index.js +0 -84
  108. package/dist/version.js +0 -4
  109. package/providers/aws/index.d.ts +0 -1
  110. package/providers/aws/index.js +0 -1
  111. package/providers/azure/index.d.ts +0 -1
  112. package/providers/azure/index.js +0 -1
  113. package/src/core/sdk/index.ts +0 -542
  114. package/src/providers/aws/index.ts +0 -239
  115. package/src/providers/azure/index.ts +0 -141
@@ -1,9 +1,11 @@
1
1
  import {
2
2
  EdgeStoreError,
3
- type AnyBuilder,
3
+ type AnyContext,
4
+ type AnyEdgeStoreProvider,
4
5
  type EdgeStoreRouter,
5
- type Provider,
6
- type SharedDeleteFileRes,
6
+ type ProviderFileMutationResult,
7
+ type SharedConfirmUploadsRes,
8
+ type SharedDeleteFilesRes,
7
9
  type SharedInitRes,
8
10
  type SharedRequestUploadPartsRes,
9
11
  type SharedRequestUploadRes,
@@ -11,14 +13,19 @@ import {
11
13
  import { hkdf } from '@panva/hkdf';
12
14
  import { stringifySetCookie } from 'cookie';
13
15
  import { EncryptJWT, jwtDecrypt } from 'jose';
14
- import type Logger from '../libs/logger';
15
- import { IMAGE_MIME_TYPES } from './imageTypes';
16
+ import { z } from 'zod';
17
+ import { getProviderBaseUrl, referenceFromUrl } from '../core/provider';
18
+ import { buildPath, parseBucketInput, parsePath } from '../core/routerRules';
19
+ import { validateFileForBucket } from '../core/validateFile';
20
+ import { getEnv, isDev } from '../libs/env';
21
+ import type { LoggerLike } from '../libs/logger';
16
22
 
17
23
  // TODO: change it to 1 hour when we have a way to refresh the token
18
24
  const DEFAULT_MAX_AGE = 30 * 24 * 60 * 60; // 30 days
19
25
 
20
- declare const globalThis: {
21
- _EDGE_STORE_LOGGER: Logger;
26
+ export type HandlerEdgeStore<TCtx extends AnyContext> = {
27
+ provider: AnyEdgeStoreProvider;
28
+ router: EdgeStoreRouter<TCtx>;
22
29
  };
23
30
 
24
31
  const NO_BODY_STATUSES = new Set([204, 205, 304]);
@@ -158,37 +165,20 @@ export function getCookieConfig(
158
165
  };
159
166
  }
160
167
 
161
- export async function init<TCtx>(params: {
162
- provider: Provider;
168
+ export async function init<TCtx extends AnyContext>(params: {
169
+ provider: AnyEdgeStoreProvider;
163
170
  router: EdgeStoreRouter<TCtx>;
164
171
  ctx: TCtx;
172
+ logger: LoggerLike;
165
173
  cookieConfig?: CookieConfig;
166
174
  }): Promise<SharedInitRes> {
167
- const log = globalThis._EDGE_STORE_LOGGER;
168
- const { ctx, provider, router, cookieConfig } = params;
169
- log.debug('Running [init]', { ctx });
175
+ const { ctx, provider, router, logger, cookieConfig } = params;
176
+ logger.debug('Running [init]', { ctx });
170
177
 
171
178
  const resolvedCookieConfig = getCookieConfig(cookieConfig);
172
179
 
173
180
  const ctxToken = await encryptJWT(ctx);
174
- const requiresFileAccessCookie =
175
- provider.name === 'edgestore' &&
176
- Object.values(router.buckets).some(
177
- (bucket) =>
178
- bucket._def.accessControl !== undefined &&
179
- bucket._def.accessControl !== 'private',
180
- );
181
- const shouldRunProviderInit =
182
- provider.name !== 'edgestore' || requiresFileAccessCookie;
183
-
184
- let token: string | undefined;
185
- if (shouldRunProviderInit) {
186
- const initRes = await provider.init({
187
- ctx,
188
- router: router,
189
- });
190
- token = initRes.token;
191
- }
181
+ const initRes = await provider.init({ ctx, router });
192
182
  const newCookies = [
193
183
  stringifySetCookie({
194
184
  name: resolvedCookieConfig.ctx.name,
@@ -196,62 +186,65 @@ export async function init<TCtx>(params: {
196
186
  ...resolvedCookieConfig.ctx.options,
197
187
  }),
198
188
  ];
199
- if (token) {
189
+ if (initRes.token) {
200
190
  newCookies.push(
201
191
  stringifySetCookie({
202
192
  name: resolvedCookieConfig.token.name,
203
- value: token,
193
+ value: initRes.token,
204
194
  ...resolvedCookieConfig.token.options,
205
195
  }),
206
196
  );
207
197
  }
208
- const baseUrl = await provider.getBaseUrl();
198
+ const baseUrl = await getProviderBaseUrl(provider);
209
199
 
210
- log.debug('Finished [init]', {
200
+ logger.debug('Finished [init]', {
211
201
  ctx,
212
202
  newCookies,
213
- token,
214
203
  baseUrl,
215
204
  providerName: provider.name,
216
- requiresFileAccessCookie,
205
+ clientInit: initRes.clientInit,
217
206
  });
218
207
 
219
208
  return {
220
209
  newCookies,
221
- token,
222
210
  baseUrl,
223
211
  providerName: provider.name,
224
- requiresFileAccessCookie,
212
+ clientInit: initRes.clientInit,
225
213
  };
226
214
  }
227
215
 
228
- export type RequestUploadBody = {
229
- bucketName: string;
230
- input: any;
231
- fileInfo: {
232
- size: number;
233
- type: string;
234
- extension: string;
235
- fileName?: string;
236
- replaceTargetUrl?: string;
237
- temporary: boolean;
238
- };
239
- };
240
-
241
- export async function requestUpload<TCtx>(params: {
242
- provider: Provider;
216
+ const nonEmptyStringSchema = z.string().min(1);
217
+
218
+ export const requestUploadBodySchema = z.object({
219
+ bucketName: nonEmptyStringSchema,
220
+ input: z.unknown().default({}),
221
+ fileInfo: z.object({
222
+ size: z.number().finite().nonnegative(),
223
+ type: z.string(),
224
+ extension: z.string(),
225
+ fileName: z.string().optional(),
226
+ replaceTargetUrl: nonEmptyStringSchema.optional(),
227
+ temporary: z.boolean().default(false),
228
+ }),
229
+ });
230
+
231
+ export type RequestUploadBody = z.infer<typeof requestUploadBodySchema>;
232
+
233
+ export async function requestUpload<TCtx extends AnyContext>(params: {
234
+ provider: AnyEdgeStoreProvider;
243
235
  router: EdgeStoreRouter<TCtx>;
244
236
  ctxToken: string | undefined;
245
237
  body: RequestUploadBody;
238
+ logger: LoggerLike;
246
239
  }): Promise<SharedRequestUploadRes> {
247
240
  const {
248
241
  provider,
249
242
  router,
250
243
  ctxToken,
244
+ logger,
251
245
  body: { bucketName, input, fileInfo },
252
246
  } = params;
253
- const log = globalThis._EDGE_STORE_LOGGER;
254
- log.debug('Running [requestUpload]', { bucketName, input, fileInfo });
247
+ logger.debug('Running [requestUpload]', { bucketName, input, fileInfo });
255
248
 
256
249
  if (!ctxToken) {
257
250
  throw new EdgeStoreError({
@@ -261,7 +254,7 @@ export async function requestUpload<TCtx>(params: {
261
254
  }
262
255
  const ctx = await getContext(ctxToken);
263
256
 
264
- log.debug('Decrypted Context', { ctx });
257
+ logger.debug('Decrypted Context', { ctx });
265
258
 
266
259
  const bucket = router.buckets[bucketName];
267
260
  if (!bucket) {
@@ -270,11 +263,12 @@ export async function requestUpload<TCtx>(params: {
270
263
  code: 'BAD_REQUEST',
271
264
  });
272
265
  }
266
+ const parsedInput = await parseBucketInput(bucket, input);
273
267
  if (bucket._def.beforeUpload) {
274
- log.debug('Running [beforeUpload]');
268
+ logger.debug('Running [beforeUpload]');
275
269
  const canUpload = await bucket._def.beforeUpload?.({
276
270
  ctx,
277
- input,
271
+ input: parsedInput,
278
272
  fileInfo: {
279
273
  size: fileInfo.size,
280
274
  type: fileInfo.type,
@@ -284,7 +278,7 @@ export async function requestUpload<TCtx>(params: {
284
278
  temporary: fileInfo.temporary,
285
279
  },
286
280
  });
287
- log.debug('Finished [beforeUpload]', { canUpload });
281
+ logger.debug('Finished [beforeUpload]', { canUpload });
288
282
  if (!canUpload) {
289
283
  throw new EdgeStoreError({
290
284
  message: 'Upload not allowed for the current context',
@@ -293,78 +287,28 @@ export async function requestUpload<TCtx>(params: {
293
287
  }
294
288
  }
295
289
 
296
- if (bucket._def.type === 'IMAGE') {
297
- if (!IMAGE_MIME_TYPES.includes(fileInfo.type)) {
298
- throw new EdgeStoreError({
299
- code: 'MIME_TYPE_NOT_ALLOWED',
300
- message: 'Only images are allowed in this bucket',
301
- details: {
302
- allowedMimeTypes: IMAGE_MIME_TYPES,
303
- mimeType: fileInfo.type,
304
- },
305
- });
306
- }
307
- }
308
-
309
- if (bucket._def.bucketConfig?.maxSize) {
310
- if (fileInfo.size > bucket._def.bucketConfig.maxSize) {
311
- throw new EdgeStoreError({
312
- code: 'FILE_TOO_LARGE',
313
- message: `File size is too big. Max size is ${bucket._def.bucketConfig.maxSize}`,
314
- details: {
315
- maxFileSize: bucket._def.bucketConfig.maxSize,
316
- fileSize: fileInfo.size,
317
- },
318
- });
319
- }
320
- }
321
-
322
- if (bucket._def.bucketConfig?.accept) {
323
- const accept = bucket._def.bucketConfig.accept;
324
- let accepted = false;
325
- for (const acceptedMimeType of accept) {
326
- if (acceptedMimeType.endsWith('/*')) {
327
- const mimeType = acceptedMimeType.replace('/*', '');
328
- if (fileInfo.type.startsWith(mimeType)) {
329
- accepted = true;
330
- break;
331
- }
332
- } else if (fileInfo.type === acceptedMimeType) {
333
- accepted = true;
334
- break;
335
- }
336
- }
337
- if (!accepted) {
338
- throw new EdgeStoreError({
339
- code: 'MIME_TYPE_NOT_ALLOWED',
340
- message: `"${
341
- fileInfo.type
342
- }" is not allowed. Accepted types are ${JSON.stringify(accept)}`,
343
- details: {
344
- allowedMimeTypes: accept,
345
- mimeType: fileInfo.type,
346
- },
347
- });
348
- }
349
- }
290
+ validateFileForBucket({ bucket, fileInfo });
350
291
 
351
292
  const path = buildPath({
352
- fileInfo,
353
293
  bucket,
354
- pathAttrs: { ctx, input },
294
+ pathAttrs: { ctx, input: parsedInput },
355
295
  });
356
- const metadata = await bucket._def.metadata?.({ ctx, input });
296
+ const metadata =
297
+ (await bucket._def.metadata?.({
298
+ ctx,
299
+ input: parsedInput,
300
+ })) ?? {};
357
301
  const isPublic = bucket._def.accessControl === undefined;
358
302
  const autoSignedUrls = bucket._def.autoSignedUrls;
359
303
 
360
- log.debug('upload info', {
304
+ logger.debug('upload info', {
361
305
  path,
362
306
  metadata,
363
307
  isPublic,
364
308
  bucketType: bucket._def.type,
365
309
  });
366
310
 
367
- const requestUploadRes = await provider.requestUpload({
311
+ const requestUploadRes = await provider.uploads.request({
368
312
  bucketName,
369
313
  bucketType: bucket._def.type,
370
314
  fileInfo: {
@@ -377,7 +321,7 @@ export async function requestUpload<TCtx>(params: {
377
321
  });
378
322
  const { parsedPath, pathOrder } = parsePath(path);
379
323
 
380
- log.debug('Finished [requestUpload]');
324
+ logger.debug('Finished [requestUpload]');
381
325
 
382
326
  return {
383
327
  ...requestUploadRes,
@@ -389,28 +333,33 @@ export async function requestUpload<TCtx>(params: {
389
333
  };
390
334
  }
391
335
 
392
- export type RequestUploadPartsParams = {
393
- multipart: {
394
- uploadId: string;
395
- parts: number[];
396
- };
397
- path: string;
398
- };
336
+ export const requestUploadPartsBodySchema = z.object({
337
+ multipart: z.object({
338
+ uploadId: nonEmptyStringSchema,
339
+ parts: z.array(z.number().int().positive()),
340
+ }),
341
+ path: nonEmptyStringSchema,
342
+ });
343
+
344
+ export type RequestUploadPartsParams = z.infer<
345
+ typeof requestUploadPartsBodySchema
346
+ >;
399
347
 
400
- export async function requestUploadParts<TCtx>(params: {
401
- provider: Provider;
348
+ export async function requestUploadParts<TCtx extends AnyContext>(params: {
349
+ provider: AnyEdgeStoreProvider;
402
350
  router: EdgeStoreRouter<TCtx>;
403
351
  ctxToken: string | undefined;
404
352
  body: RequestUploadPartsParams;
353
+ logger: LoggerLike;
405
354
  }): Promise<SharedRequestUploadPartsRes> {
406
355
  const {
407
356
  provider,
408
357
  ctxToken,
358
+ logger,
409
359
  body: { multipart, path },
410
360
  } = params;
411
361
 
412
- const log = globalThis._EDGE_STORE_LOGGER;
413
- log.debug('Running [requestUploadParts]', { multipart, path });
362
+ logger.debug('Running [requestUploadParts]', { multipart, path });
414
363
 
415
364
  if (!ctxToken) {
416
365
  throw new EdgeStoreError({
@@ -420,41 +369,55 @@ export async function requestUploadParts<TCtx>(params: {
420
369
  }
421
370
  await getContext(ctxToken); // just to check if the token is valid
422
371
 
423
- const res = await provider.requestUploadParts({
372
+ const multipartUploads = provider.uploads.multipart;
373
+ if (!multipartUploads) {
374
+ throw new EdgeStoreError({
375
+ message: `Provider ${provider.name} does not support multipart uploads.`,
376
+ code: 'BAD_REQUEST',
377
+ });
378
+ }
379
+ const res = await multipartUploads.requestParts({
424
380
  multipart,
425
381
  path,
426
382
  });
427
383
 
428
- log.debug('Finished [requestUploadParts]');
384
+ logger.debug('Finished [requestUploadParts]');
429
385
 
430
386
  return res;
431
387
  }
432
388
 
433
- export type CompleteMultipartUploadBody = {
434
- bucketName: string;
435
- uploadId: string;
436
- key: string;
437
- parts: {
438
- partNumber: number;
439
- eTag: string;
440
- }[];
441
- };
389
+ export const completeMultipartUploadBodySchema = z.object({
390
+ bucketName: nonEmptyStringSchema,
391
+ uploadId: nonEmptyStringSchema,
392
+ key: nonEmptyStringSchema,
393
+ parts: z.array(
394
+ z.object({
395
+ partNumber: z.number().int().positive(),
396
+ eTag: nonEmptyStringSchema,
397
+ }),
398
+ ),
399
+ });
442
400
 
443
- export async function completeMultipartUpload<TCtx>(params: {
444
- provider: Provider;
401
+ export type CompleteMultipartUploadBody = z.infer<
402
+ typeof completeMultipartUploadBodySchema
403
+ >;
404
+
405
+ export async function completeMultipartUpload<TCtx extends AnyContext>(params: {
406
+ provider: AnyEdgeStoreProvider;
445
407
  router: EdgeStoreRouter<TCtx>;
446
408
  ctxToken: string | undefined;
447
409
  body: CompleteMultipartUploadBody;
410
+ logger: LoggerLike;
448
411
  }) {
449
412
  const {
450
413
  provider,
451
414
  router,
452
415
  ctxToken,
416
+ logger,
453
417
  body: { bucketName, uploadId, key, parts },
454
418
  } = params;
455
419
 
456
- const log = globalThis._EDGE_STORE_LOGGER;
457
- log.debug('Running [completeMultipartUpload]', {
420
+ logger.debug('Running [completeMultipartUpload]', {
458
421
  bucketName,
459
422
  uploadId,
460
423
  key,
@@ -475,37 +438,45 @@ export async function completeMultipartUpload<TCtx>(params: {
475
438
  });
476
439
  }
477
440
 
478
- const res = await provider.completeMultipartUpload({
441
+ const multipartUploads = provider.uploads.multipart;
442
+ if (!multipartUploads) {
443
+ throw new EdgeStoreError({
444
+ message: `Provider ${provider.name} does not support multipart uploads.`,
445
+ code: 'BAD_REQUEST',
446
+ });
447
+ }
448
+ await multipartUploads.complete({
479
449
  uploadId,
480
450
  key,
481
451
  parts,
482
452
  });
483
453
 
484
- log.debug('Finished [completeMultipartUpload]');
485
-
486
- return res;
454
+ logger.debug('Finished [completeMultipartUpload]');
487
455
  }
488
456
 
489
- export type ConfirmUploadBody = {
490
- bucketName: string;
491
- url: string;
492
- };
457
+ export const confirmUploadsBodySchema = z.object({
458
+ bucketName: nonEmptyStringSchema,
459
+ urls: z.array(nonEmptyStringSchema),
460
+ });
461
+
462
+ export type ConfirmUploadsBody = z.infer<typeof confirmUploadsBodySchema>;
493
463
 
494
- export async function confirmUpload<TCtx>(params: {
495
- provider: Provider;
464
+ export async function confirmUploads<TCtx extends AnyContext>(params: {
465
+ provider: AnyEdgeStoreProvider;
496
466
  router: EdgeStoreRouter<TCtx>;
497
467
  ctxToken: string | undefined;
498
- body: ConfirmUploadBody;
499
- }) {
468
+ body: ConfirmUploadsBody;
469
+ logger: LoggerLike;
470
+ }): Promise<SharedConfirmUploadsRes> {
500
471
  const {
501
472
  provider,
502
473
  router,
503
474
  ctxToken,
504
- body: { bucketName, url },
475
+ logger,
476
+ body: { bucketName, urls },
505
477
  } = params;
506
478
 
507
- const log = globalThis._EDGE_STORE_LOGGER;
508
- log.debug('Running [confirmUpload]', { bucketName, url });
479
+ logger.debug('Running [confirmUploads]', { bucketName, urls });
509
480
 
510
481
  if (!ctxToken) {
511
482
  throw new EdgeStoreError({
@@ -522,35 +493,47 @@ export async function confirmUpload<TCtx>(params: {
522
493
  });
523
494
  }
524
495
 
525
- const res = await provider.confirmUpload({
526
- bucket,
527
- url: unproxyUrl(url),
496
+ if (!provider.files.confirm) {
497
+ throw new EdgeStoreError({
498
+ message: `Provider ${provider.name} does not support file confirmation.`,
499
+ code: 'SERVER_ERROR',
500
+ });
501
+ }
502
+ const files = await Promise.all(
503
+ urls.map((url) => referenceFromUrl(provider, unproxyUrl(url))),
504
+ );
505
+ const result = await provider.files.confirm({
506
+ bucketName,
507
+ files,
528
508
  });
529
509
 
530
- log.debug('Finished [confirmUpload]');
531
- return res;
510
+ logger.debug('Finished [confirmUploads]');
511
+ return mapFrontendMutationResult(urls, result);
532
512
  }
533
513
 
534
- export type DeleteFileBody = {
535
- bucketName: string;
536
- url: string;
537
- };
514
+ export const deleteFilesBodySchema = z.object({
515
+ bucketName: nonEmptyStringSchema,
516
+ urls: z.array(nonEmptyStringSchema),
517
+ });
518
+
519
+ export type DeleteFilesBody = z.infer<typeof deleteFilesBodySchema>;
538
520
 
539
- export async function deleteFile<TCtx>(params: {
540
- provider: Provider;
521
+ export async function deleteFiles<TCtx extends AnyContext>(params: {
522
+ provider: AnyEdgeStoreProvider;
541
523
  router: EdgeStoreRouter<TCtx>;
542
524
  ctxToken: string | undefined;
543
- body: DeleteFileBody;
544
- }): Promise<SharedDeleteFileRes> {
525
+ body: DeleteFilesBody;
526
+ logger: LoggerLike;
527
+ }): Promise<SharedDeleteFilesRes> {
545
528
  const {
546
529
  provider,
547
530
  router,
548
531
  ctxToken,
549
- body: { bucketName, url },
532
+ logger,
533
+ body: { bucketName, urls },
550
534
  } = params;
551
535
 
552
- const log = globalThis._EDGE_STORE_LOGGER;
553
- log.debug('Running [deleteFile]', { bucketName, url });
536
+ logger.debug('Running [deleteFiles]', { bucketName, urls });
554
537
 
555
538
  if (!ctxToken) {
556
539
  throw new EdgeStoreError({
@@ -575,31 +558,84 @@ export async function deleteFile<TCtx>(params: {
575
558
  });
576
559
  }
577
560
 
578
- const fileInfo = await provider.getFile({
579
- url: unproxyUrl(url),
580
- });
581
-
582
- const canDelete = await bucket._def.beforeDelete({
583
- ctx,
584
- fileInfo,
585
- });
586
- if (!canDelete) {
561
+ if (!provider.files.delete) {
562
+ throw new EdgeStoreError({
563
+ message: `Provider ${provider.name} does not support file deletion.`,
564
+ code: 'SERVER_ERROR',
565
+ });
566
+ }
567
+ const files = await Promise.all(
568
+ urls.map((url) => referenceFromUrl(provider, unproxyUrl(url))),
569
+ );
570
+ const fileRecords = await Promise.all(
571
+ files.map((file) =>
572
+ Promise.resolve(provider.files.get({ bucketName, file })),
573
+ ),
574
+ );
575
+ const authorizations = await Promise.all(
576
+ fileRecords.map((file) => {
577
+ if (file.path === undefined && bucket._def.path.length > 0) {
578
+ throw new EdgeStoreError({
579
+ message: `Provider ${provider.name} must return path from files.get to authorize frontend deletion for a bucket with configured path fields.`,
580
+ code: 'SERVER_ERROR',
581
+ });
582
+ }
583
+ if (file.metadata === undefined && bucket._def.metadata !== undefined) {
584
+ throw new EdgeStoreError({
585
+ message: `Provider ${provider.name} must return metadata from files.get to authorize frontend deletion for a bucket with configured metadata fields.`,
586
+ code: 'SERVER_ERROR',
587
+ });
588
+ }
589
+ return Promise.resolve(
590
+ bucket._def.beforeDelete!({
591
+ ctx,
592
+ fileInfo: {
593
+ url: file.url,
594
+ size: file.sizeBytes,
595
+ uploadedAt: new Date(file.uploadedAt),
596
+ path: file.path ?? {},
597
+ metadata: file.metadata ?? {},
598
+ },
599
+ }),
600
+ );
601
+ }),
602
+ );
603
+ if (authorizations.some((allowed) => !allowed)) {
587
604
  throw new EdgeStoreError({
588
605
  message: 'Delete not allowed for the current context',
589
606
  code: 'DELETE_NOT_ALLOWED',
590
607
  });
591
608
  }
592
- const res = await provider.deleteFile({
593
- bucket,
594
- url: unproxyUrl(url),
609
+ const result = await provider.files.delete({
610
+ bucketName,
611
+ files,
595
612
  });
596
613
 
597
- log.debug('Finished [deleteFile]');
614
+ logger.debug('Finished [deleteFiles]');
598
615
 
599
- return res;
616
+ return mapFrontendMutationResult(urls, result);
617
+ }
618
+
619
+ function mapFrontendMutationResult(
620
+ urls: string[],
621
+ result: ProviderFileMutationResult<string>,
622
+ ): SharedDeleteFilesRes {
623
+ if (result.results.length !== urls.length) {
624
+ throw new Error(
625
+ `The provider returned ${result.results.length} mutation results for ${urls.length} files.`,
626
+ );
627
+ }
628
+ const succeeded: string[] = [];
629
+ const failed: SharedDeleteFilesRes['failed'] = [];
630
+ result.results.forEach((item, index) => {
631
+ const url = urls[index]!;
632
+ if (item.success) succeeded.push(url);
633
+ else failed.push({ url, error: item.error });
634
+ });
635
+ return { succeeded, failed };
600
636
  }
601
637
 
602
- async function encryptJWT(ctx: any) {
638
+ async function encryptJWT(ctx: AnyContext) {
603
639
  const secret =
604
640
  getEnv('EDGE_STORE_JWT_SECRET') ?? getEnv('EDGE_STORE_SECRET_KEY');
605
641
  if (!secret) {
@@ -609,7 +645,7 @@ async function encryptJWT(ctx: any) {
609
645
  });
610
646
  }
611
647
  const encryptionSecret = await getDerivedEncryptionKey(secret);
612
- return await new EncryptJWT(ctx)
648
+ return await new EncryptJWT({ ctx })
613
649
  .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
614
650
  .setIssuedAt()
615
651
  .setExpirationTime(Date.now() / 1000 + DEFAULT_MAX_AGE)
@@ -630,7 +666,15 @@ async function decryptJWT(token: string) {
630
666
  const { payload } = await jwtDecrypt(token, encryptionSecret, {
631
667
  clockTolerance: 15,
632
668
  });
633
- return payload;
669
+ const result = z.object({ ctx: z.record(z.string()) }).safeParse(payload);
670
+ if (!result.success) {
671
+ throw new EdgeStoreError({
672
+ message: 'Invalid edgestore-ctx cookie',
673
+ code: 'UNAUTHORIZED',
674
+ cause: result.error,
675
+ });
676
+ }
677
+ return result.data.ctx;
634
678
  }
635
679
 
636
680
  async function getDerivedEncryptionKey(secret: string) {
@@ -643,57 +687,6 @@ async function getDerivedEncryptionKey(secret: string) {
643
687
  );
644
688
  }
645
689
 
646
- export function buildPath(params: {
647
- fileInfo: RequestUploadBody['fileInfo'];
648
- bucket: AnyBuilder;
649
- pathAttrs: {
650
- ctx: any;
651
- input: any;
652
- };
653
- }) {
654
- const { bucket } = params;
655
- const pathParams = bucket._def.path;
656
- const path = pathParams.map((param) => {
657
- const paramEntries = Object.entries(param);
658
- if (paramEntries[0] === undefined) {
659
- throw new EdgeStoreError({
660
- message: `Empty path param found in: ${JSON.stringify(pathParams)}`,
661
- code: 'SERVER_ERROR',
662
- });
663
- }
664
- const [key, value] = paramEntries[0];
665
- // this is a string like: "ctx.xxx" or "input.yyy.zzz"
666
- const currParamVal = value()
667
- .split('.')
668
- .reduce((acc2: any, key: string) => {
669
- if (acc2[key] === undefined) {
670
- throw new EdgeStoreError({
671
- message: `Missing key ${key} in ${JSON.stringify(acc2)}`,
672
- code: 'BAD_REQUEST',
673
- });
674
- }
675
- return acc2[key];
676
- }, params.pathAttrs as any) as string;
677
- return {
678
- key,
679
- value: currParamVal,
680
- };
681
- });
682
- return path;
683
- }
684
-
685
- export function parsePath(path: { key: string; value: string }[]) {
686
- const parsedPath = path.reduce<Record<string, string>>((acc, curr) => {
687
- acc[curr.key] = curr.value;
688
- return acc;
689
- }, {});
690
- const pathOrder = path.map((p) => p.key);
691
- return {
692
- parsedPath,
693
- pathOrder,
694
- };
695
- }
696
-
697
690
  async function getContext(token: string) {
698
691
  return await decryptJWT(token);
699
692
  }
@@ -715,20 +708,3 @@ function unproxyUrl(url: string) {
715
708
  }
716
709
  return url;
717
710
  }
718
-
719
- export function getEnv(key: string): string | undefined {
720
- if (typeof process !== 'undefined' && process.env) {
721
- // @ts-expect-error - In Vite/Astro, the env variables are available on `import.meta`.
722
- return process.env[key] ?? import.meta.env?.[key];
723
- }
724
- // @ts-expect-error - In Vite/Astro, the env variables are available on `import.meta`.
725
- return import.meta.env?.[key];
726
- }
727
-
728
- export function isDev(): boolean {
729
- return (
730
- process?.env?.NODE_ENV === 'development' ||
731
- // @ts-expect-error - In Vite/Astro, the env variables are available on `import.meta`.
732
- import.meta.env?.DEV
733
- );
734
- }