11import { env } from 'cloudflare:test' ;
2+ import { join } from 'node:path' ;
23import { inject } from 'vitest' ;
3- import type { Env } from '../env' ;
4- import type { Directory } from '../../vitest-setup' ;
4+ import type { Env } from '../src/env' ;
5+ import type { Directory } from '../vitest-setup' ;
6+ import type { ReadDirectoryResult , File } from '../src/providers/provider' ;
57
68async function populateR2BucketDirectory ( directory : Directory ) : Promise < void > {
79 const promises : Array < Promise < unknown > > = [ ] ;
@@ -10,7 +12,7 @@ async function populateR2BucketDirectory(directory: Directory): Promise<void> {
1012 const file = directory . files [ path ] ;
1113
1214 promises . push (
13- env . R2_BUCKET . put ( path , file . contents , {
15+ env . R2_BUCKET . put ( join ( directory . name , path ) , file . contents , {
1416 customMetadata : {
1517 // This is added by rclone when copying the release assets to the
1618 // bucket.
@@ -27,6 +29,41 @@ async function populateR2BucketDirectory(directory: Directory): Promise<void> {
2729 await Promise . all ( promises ) ;
2830}
2931
32+ async function populateDirectoryCache ( directory : Directory ) : Promise < void > {
33+ let hasIndexHtmlFile = false ;
34+
35+ const files : File [ ] = Object . keys ( directory . files ) . map ( name => {
36+ const file = directory . files [ name ] ;
37+
38+ if ( ! hasIndexHtmlFile && name . match ( / i n d e x .h t m (?: l ) $ / ) ) {
39+ hasIndexHtmlFile = true ;
40+ }
41+
42+ return {
43+ name,
44+ lastModified : new Date ( file . lastModified ) ,
45+ size : file . size ,
46+ } ;
47+ } ) ;
48+
49+ const cachedDirectory : ReadDirectoryResult = {
50+ subdirectories : Object . keys ( directory . subdirectories ) ,
51+ files,
52+ hasIndexHtmlFile,
53+ lastModified : new Date ( ) ,
54+ } ;
55+
56+ const promises : Array < Promise < void > > = [
57+ env . DIRECTORY_CACHE . put (
58+ `${ directory . name } /` ,
59+ JSON . stringify ( cachedDirectory )
60+ ) ,
61+ ...Object . values ( directory . subdirectories ) . map ( populateDirectoryCache ) ,
62+ ] ;
63+
64+ await Promise . all ( promises ) ;
65+ }
66+
3067/**
3168 * Writes the contents of the dev bucket into the R2 bucket given in {@link env}
3269 */
@@ -38,6 +75,14 @@ export async function populateR2WithDevBucket(): Promise<void> {
3875 await populateR2BucketDirectory ( devBucket ) ;
3976}
4077
78+ export async function populateDirectoryCacheWithDevBucket ( ) : Promise < void > {
79+ // Grab the contents of the dev bucket
80+ const devBucket = inject ( 'devBucket' ) ;
81+
82+ // Write it to KV
83+ await populateDirectoryCache ( devBucket ) ;
84+ }
85+
4186declare module 'cloudflare:test' {
4287 // eslint-disable-next-line @typescript-eslint/no-empty-object-type
4388 interface ProvidedEnv extends Env { }
0 commit comments