@adobe/aio-lib-web 7.3.0 → 8.0.0

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.
@@ -10,169 +10,171 @@ OF ANY KIND, either express or implied. See the License for the specific languag
10
10
  governing permissions and limitations under the License.
11
11
  */
12
12
 
13
- const mockS3 = {
13
+ const { vol } = global.mockFs()
14
+ const path = require('path')
15
+
16
+ const mockProxyDispatcher = { __mock: 'proxy-dispatcher' }
17
+ jest.mock('undici', () => ({
18
+ EnvHttpProxyAgent: jest.fn(() => mockProxyDispatcher)
19
+ }))
20
+
21
+ const mockS3Instance = {
14
22
  listObjectsV2: jest.fn(),
15
23
  deleteObjects: jest.fn(),
16
24
  putObject: jest.fn()
17
25
  }
26
+ jest.mock('@aws-sdk/client-s3', () => ({
27
+ S3: jest.fn(() => mockS3Instance)
28
+ }))
29
+ jest.mock('proxy-agent', () => ({
30
+ ProxyAgent: jest.fn()
31
+ }))
32
+ jest.mock('@smithy/node-http-handler', () => ({
33
+ NodeHttpHandler: jest.fn()
34
+ }))
35
+
36
+ const { EnvHttpProxyAgent } = require('undici')
37
+ const { S3 } = require('@aws-sdk/client-s3')
38
+ const { ProxyAgent } = require('proxy-agent')
39
+ const { NodeHttpHandler } = require('@smithy/node-http-handler')
40
+ const RemoteStorage = require('../../lib/remote-storage')
18
41
 
19
- jest.mock('@aws-sdk/client-s3', () => Object({ S3: jest.fn(() => { return mockS3 }) }))
42
+ // Helper to create a mock response
43
+ const mockResponse = (body, options = {}) => ({
44
+ ok: options.ok !== false,
45
+ status: options.status || 200,
46
+ statusText: options.statusText || 'OK',
47
+ json: jest.fn().mockResolvedValue(body)
48
+ })
20
49
 
21
- const { S3 } = require('@aws-sdk/client-s3')
22
- const { vol } = global.mockFs()
23
- const path = require('path')
50
+ // Helper to create appConfig (auth token now passed to constructor, not in config)
51
+ const createAppConfig = (overrides = {}) => ({
52
+ ow: {
53
+ namespace: global.fakeNamespace
54
+ },
55
+ app: {
56
+ htmlCacheDuration: 60,
57
+ jsCacheDuration: 604800,
58
+ cssCacheDuration: 604800,
59
+ imageCacheDuration: 604800
60
+ },
61
+ web: {
62
+ 'response-headers': {
63
+ '/*': {
64
+ testHeader: 'foo'
65
+ }
66
+ }
67
+ },
68
+ ...overrides
69
+ })
24
70
 
25
- const RemoteStorage = require('../../lib/remote-storage')
71
+ beforeAll(() => {
72
+ global.fetch = jest.fn()
73
+ })
74
+
75
+ afterAll(() => {
76
+ global.fetch.mockRestore()
77
+ })
26
78
 
27
79
  describe('RemoteStorage', () => {
28
80
  beforeEach(() => {
29
- // resets all mock s3 functions, do not use jest.resetAllMocks() as it also resets the s3 client constructor mock
30
- mockS3.listObjectsV2.mockReset()
31
- mockS3.deleteObjects.mockReset()
32
- mockS3.putObject.mockReset()
33
- S3.mockClear()
34
81
  // resets the mock fs
35
82
  global.cleanFs(vol)
36
- })
37
-
38
- test('Constructor should throw when missing credentials', async () => {
39
- const instantiate = () => new RemoteStorage({})
40
- expect(instantiate.bind(this)).toThrowWithMessageContaining(['required'])
41
- })
42
-
43
- test('Constructor initializes the S3 constructor properly using tvm credentials', async () => {
44
- const rs = new RemoteStorage(global.fakeTVMResponse)
45
- expect(S3).toHaveBeenCalledWith({
46
- credentials: {
47
- accessKeyId: global.fakeTVMResponse.accessKeyId,
48
- secretAccessKey: global.fakeTVMResponse.secretAccessKey,
49
- sessionToken: global.fakeTVMResponse.sessionToken,
50
- expiration: new Date(global.fakeTVMResponse.expiration)
51
- },
52
- region: 'us-east-1',
53
- requestHandler: expect.any(Object)
54
- })
55
- rs.bucket = global.fakeTVMResponse.Bucket
56
- })
57
-
58
- test('Constructor initializes the S3 constructor properly using byo credentials', async () => {
59
- const rs = new RemoteStorage(global.fakeBYOCredentials)
60
- expect(S3).toHaveBeenCalledWith({
61
- credentials: {
62
- accessKeyId: global.fakeTVMResponse.accessKeyId,
63
- secretAccessKey: global.fakeTVMResponse.secretAccessKey,
64
- sessionToken: undefined,
65
- expiration: undefined
66
- },
67
- region: 'us-east-1',
68
- requestHandler: expect.any(Object)
69
- })
70
- rs.bucket = global.fakeTVMResponse.Bucket
83
+ // reset fetch mock
84
+ global.fetch.mockReset()
71
85
  })
72
86
 
73
87
  describe('Proxy configuration', () => {
74
- const originalEnv = process.env
75
-
76
- beforeEach(() => {
77
- // Clear environment variables before each test
78
- delete process.env.https_proxy
79
- delete process.env.HTTPS_PROXY
80
- delete process.env.http_proxy
81
- delete process.env.HTTP_PROXY
88
+ test('uses a shared EnvHttpProxyAgent dispatcher on deploy-service fetch', async () => {
89
+ global.fetch.mockResolvedValue(mockResponse([]))
90
+ const rs = new RemoteStorage()
91
+ const appConfig = createAppConfig()
92
+
93
+ await rs.folderExists(global.fakeAuthToken, 'fakeprefix', appConfig)
94
+
95
+ expect(EnvHttpProxyAgent).toHaveBeenCalledTimes(1)
96
+ expect(global.fetch).toHaveBeenCalledWith(
97
+ expect.any(String),
98
+ expect.objectContaining({ dispatcher: mockProxyDispatcher })
99
+ )
82
100
  })
83
101
 
84
- afterAll(() => {
85
- // Restore original environment
86
- process.env = originalEnv
102
+ test('reuses the same dispatcher across multiple requests', async () => {
103
+ global.fetch.mockResolvedValue(mockResponse([]))
104
+ const rs = new RemoteStorage()
105
+ const appConfig = createAppConfig()
106
+
107
+ await rs.folderExists(global.fakeAuthToken, 'fakeprefix', appConfig)
108
+ await rs.emptyFolder(global.fakeAuthToken, '/', appConfig)
109
+
110
+ expect(EnvHttpProxyAgent).toHaveBeenCalledTimes(1)
111
+ expect(global.fetch).toHaveBeenNthCalledWith(
112
+ 1,
113
+ expect.any(String),
114
+ expect.objectContaining({ dispatcher: mockProxyDispatcher })
115
+ )
116
+ expect(global.fetch).toHaveBeenNthCalledWith(
117
+ 2,
118
+ expect.any(String),
119
+ expect.objectContaining({ dispatcher: mockProxyDispatcher })
120
+ )
87
121
  })
122
+ })
88
123
 
89
- test('Constructor uses HTTPS_PROXY when set (uppercase)', async () => {
90
- process.env.HTTPS_PROXY = 'http://proxy.example.com:8080'
91
- // eslint-disable-next-line no-new
92
- new RemoteStorage(global.fakeTVMResponse)
93
-
94
- expect(S3).toHaveBeenCalledWith(expect.objectContaining({
95
- requestHandler: expect.any(Object),
96
- credentials: expect.any(Object),
97
- region: 'us-east-1'
98
- }))
124
+ describe('folderExists', () => {
125
+ test('missing prefix should throw', async () => {
126
+ const rs = new RemoteStorage()
127
+ const appConfig = createAppConfig()
128
+ await expect(rs.folderExists(global.fakeAuthToken, undefined, appConfig)).rejects.toEqual(
129
+ expect.objectContaining({ message: 'prefix must be a valid string' })
130
+ )
99
131
  })
100
132
 
101
- test('Constructor uses https_proxy when set (lowercase)', async () => {
102
- process.env.https_proxy = 'http://proxy.example.com:3128'
103
- // eslint-disable-next-line no-new
104
- new RemoteStorage(global.fakeTVMResponse)
105
-
106
- expect(S3).toHaveBeenCalledWith(expect.objectContaining({
107
- requestHandler: expect.any(Object),
108
- credentials: expect.any(Object),
109
- region: 'us-east-1'
110
- }))
133
+ test('should return false if there are no files', async () => {
134
+ global.fetch.mockResolvedValue(mockResponse([]))
135
+ const rs = new RemoteStorage()
136
+ const appConfig = createAppConfig()
137
+
138
+ const result = await rs.folderExists(global.fakeAuthToken, 'fakeprefix', appConfig)
139
+
140
+ expect(result).toBe(false)
141
+ expect(global.fetch).toHaveBeenCalledWith(
142
+ expect.stringContaining(`/cdn-api/namespaces/${global.fakeNamespace}/files`),
143
+ expect.objectContaining({
144
+ method: 'GET',
145
+ headers: { Authorization: global.fakeAuthToken }
146
+ })
147
+ )
111
148
  })
112
149
 
113
- test('Constructor uses HTTP_PROXY when HTTPS_PROXY not set', async () => {
114
- process.env.HTTP_PROXY = 'http://proxy.example.com:8080'
115
- // eslint-disable-next-line no-new
116
- new RemoteStorage(global.fakeTVMResponse)
150
+ test('should return true if there are files', async () => {
151
+ global.fetch.mockResolvedValue(mockResponse([{ key: 'file1.txt' }]))
152
+ const rs = new RemoteStorage()
153
+ const appConfig = createAppConfig()
117
154
 
118
- expect(S3).toHaveBeenCalledWith(expect.objectContaining({
119
- requestHandler: expect.any(Object),
120
- credentials: expect.any(Object),
121
- region: 'us-east-1'
122
- }))
123
- })
155
+ const result = await rs.folderExists(global.fakeAuthToken, 'fakeprefix', appConfig)
124
156
 
125
- test('Constructor uses http_proxy when other proxy vars not set', async () => {
126
- process.env.http_proxy = 'http://proxy.example.com:3128'
127
- // eslint-disable-next-line no-new
128
- new RemoteStorage(global.fakeTVMResponse)
129
-
130
- expect(S3).toHaveBeenCalledWith(expect.objectContaining({
131
- requestHandler: expect.any(Object),
132
- credentials: expect.any(Object),
133
- region: 'us-east-1'
134
- }))
157
+ expect(result).toBe(true)
135
158
  })
136
159
 
137
- test('Constructor prioritizes HTTPS_PROXY over HTTP_PROXY', async () => {
138
- process.env.HTTPS_PROXY = 'http://https-proxy.example.com:8080'
139
- process.env.HTTP_PROXY = 'http://http-proxy.example.com:8080'
140
- // eslint-disable-next-line no-new
141
- new RemoteStorage(global.fakeTVMResponse)
160
+ test('should throw if request fails', async () => {
161
+ global.fetch.mockResolvedValue(mockResponse(null, { ok: false, status: 500, statusText: 'Internal Server Error' }))
162
+ const rs = new RemoteStorage()
163
+ const appConfig = createAppConfig()
142
164
 
143
- expect(S3).toHaveBeenCalledWith(expect.objectContaining({
144
- requestHandler: expect.any(Object),
145
- credentials: expect.any(Object),
146
- region: 'us-east-1'
147
- }))
148
- })
149
-
150
- test('Constructor prioritizes https_proxy over HTTP_PROXY', async () => {
151
- process.env.https_proxy = 'http://https-proxy.example.com:3128'
152
- process.env.HTTP_PROXY = 'http://http-proxy.example.com:8080'
153
- // eslint-disable-next-line no-new
154
- new RemoteStorage(global.fakeTVMResponse)
155
-
156
- expect(S3).toHaveBeenCalledWith(expect.objectContaining({
157
- requestHandler: expect.any(Object),
158
- credentials: expect.any(Object),
159
- region: 'us-east-1'
160
- }))
165
+ await expect(rs.folderExists(global.fakeAuthToken, 'fakeprefix', appConfig)).rejects.toThrow(
166
+ 'cannot check if folder exists, request failed: 500 Internal Server Error'
167
+ )
161
168
  })
162
169
 
163
- test('Constructor always includes requestHandler with ProxyAgent', async () => {
164
- // eslint-disable-next-line no-new
165
- new RemoteStorage(global.fakeTVMResponse)
170
+ test('should throw if request fails with non-404 status', async () => {
171
+ global.fetch.mockResolvedValue(mockResponse(null, { ok: false, status: 401, statusText: 'Unauthorized' }))
172
+ const rs = new RemoteStorage()
173
+ const appConfig = createAppConfig()
166
174
 
167
- expect(S3).toHaveBeenCalledWith({
168
- credentials: expect.any(Object),
169
- region: 'us-east-1',
170
- requestHandler: expect.any(Object)
171
- })
172
-
173
- // ProxyAgent handles proxy detection automatically via proxy-from-env
174
- const s3CallArgs = S3.mock.calls[S3.mock.calls.length - 1][0]
175
- expect(s3CallArgs).toHaveProperty('requestHandler')
175
+ await expect(rs.folderExists(global.fakeAuthToken, 'fakeprefix', appConfig)).rejects.toThrow(
176
+ 'cannot check if folder exists, request failed: 401 Unauthorized'
177
+ )
176
178
  })
177
179
  })
178
180
 
@@ -180,7 +182,7 @@ describe('RemoteStorage', () => {
180
182
  let rs
181
183
 
182
184
  beforeEach(() => {
183
- rs = new RemoteStorage(global.fakeTVMResponse)
185
+ rs = new RemoteStorage()
184
186
  })
185
187
 
186
188
  describe('basic path joining', () => {
@@ -440,513 +442,909 @@ describe('RemoteStorage', () => {
440
442
  })
441
443
 
442
444
  test('folderExists missing prefix', async () => {
443
- const rs = new RemoteStorage(global.fakeTVMResponse)
445
+ const rs = new RemoteStorage()
444
446
  await expect(rs.folderExists()).rejects.toEqual(expect.objectContaining({ message: 'prefix must be a valid string' }))
445
447
  })
446
448
 
447
- test('emptyFolder missing prefix', async () => {
448
- const rs = new RemoteStorage(global.fakeTVMResponse)
449
- await expect(rs.emptyFolder()).rejects.toEqual(expect.objectContaining({ message: 'prefix must be a valid string' }))
450
- })
451
-
452
- test('uploadFile missing prefix', async () => {
453
- const rs = new RemoteStorage(global.fakeTVMResponse)
454
- await expect(rs.uploadFile()).rejects.toEqual(expect.objectContaining({ message: 'prefix must be a valid string' }))
455
- })
456
-
457
449
  test('uploadFile with windows path', async () => {
458
- const rs = new RemoteStorage(global.fakeTVMResponse)
450
+ global.fetch.mockResolvedValue(mockResponse({ success: true }))
451
+ const rs = new RemoteStorage()
452
+ const appConfig = createAppConfig()
459
453
  // Create file using platform-agnostic paths
460
454
  await global.addFakeFiles(vol, 'fakeDir', { 'deep/index.js': 'fake content' })
461
455
  // Use platform-specific path for file reading (must match actual file system)
462
456
  const filePath = path.join('fakeDir', 'deep', 'index.js')
463
457
  // Test that Windows-style backslashes in prefix are normalized correctly
464
458
  const prefixPath = 'fakeprefix\\deep\\dir\\'
465
- await expect(rs.uploadFile(filePath, prefixPath, global.fakeConfig, 'fakeDir')).resolves.toBeUndefined()
466
- expect(mockS3.putObject).toHaveBeenCalledWith(
467
- expect.objectContaining({ Bucket: 'fake-bucket', Key: 'fakeprefix/deep/dir/index.js' })
468
- )
469
- })
459
+ await rs.uploadFile(global.fakeAuthToken, filePath, prefixPath, appConfig, 'fakeDir')
470
460
 
471
- test('uploadDir missing prefix', async () => {
472
- const rs = new RemoteStorage(global.fakeTVMResponse)
473
- await expect(rs.uploadDir()).rejects.toEqual(expect.objectContaining({ message: 'prefix must be a valid string' }))
461
+ const callArgs = global.fetch.mock.calls[0]
462
+ const body = JSON.parse(callArgs[1].body)
463
+ // Backslashes should be normalized to forward slashes in the file name
464
+ expect(body.file.name).toBe('fakeprefix/deep/dir/index.js')
474
465
  })
475
466
 
476
- test('folderExists should return false if there are no files', async () => {
477
- mockS3.listObjectsV2.mockResolvedValue({ KeyCount: 0 })
478
- const rs = new RemoteStorage(global.fakeTVMResponse)
479
- expect((await rs.folderExists('fakeprefix'))).toBe(false)
480
- expect(mockS3.listObjectsV2).toHaveBeenCalledWith({ Bucket: 'fake-bucket', Prefix: 'fakeprefix' })
467
+ test('uploadDir missing basePath', async () => {
468
+ const rs = new RemoteStorage()
469
+ await expect(rs.uploadDir(global.fakeAuthToken)).rejects.toEqual(expect.objectContaining({ message: 'basePath must be a valid string' }))
481
470
  })
482
471
 
483
- test('folderExists should return true if there are files', async () => {
484
- mockS3.listObjectsV2.mockResolvedValue({ KeyCount: 1 })
485
- const rs = new RemoteStorage(global.fakeTVMResponse)
486
- expect((await rs.folderExists('fakeprefix'))).toBe(true)
487
- })
472
+ describe('emptyFolder', () => {
473
+ test('missing prefix should throw', async () => {
474
+ const rs = new RemoteStorage()
475
+ const appConfig = createAppConfig()
476
+ await expect(rs.emptyFolder(global.fakeAuthToken, undefined, appConfig)).rejects.toEqual(
477
+ expect.objectContaining({ message: 'prefix must be a valid string' })
478
+ )
479
+ })
488
480
 
489
- test('emptyFolder should not throw if there are no files', async () => {
490
- mockS3.listObjectsV2.mockResolvedValue({ KeyCount: 0 })
491
- const rs = new RemoteStorage(global.fakeTVMResponse)
492
- expect(rs.emptyFolder.bind(rs, 'fakeprefix')).not.toThrow()
493
- })
481
+ test('should call DELETE /files/ when prefix is "/"', async () => {
482
+ global.fetch.mockResolvedValue(mockResponse({ success: true }))
483
+ const rs = new RemoteStorage()
484
+ const appConfig = createAppConfig()
485
+
486
+ const result = await rs.emptyFolder(global.fakeAuthToken, '/', appConfig)
487
+
488
+ expect(result).toBe(true)
489
+ expect(global.fetch).toHaveBeenCalledWith(
490
+ expect.stringContaining(`/cdn-api/namespaces/${global.fakeNamespace}/files/`),
491
+ expect.objectContaining({
492
+ method: 'DELETE',
493
+ headers: { Authorization: global.fakeAuthToken }
494
+ })
495
+ )
496
+ })
494
497
 
495
- test('emptyFolder should not call S3#deleteObjects if already empty', async () => {
496
- mockS3.listObjectsV2.mockResolvedValue({ KeyCount: 0 })
497
- const rs = new RemoteStorage(global.fakeTVMResponse)
498
- await rs.emptyFolder('fakeprefix')
499
- expect(mockS3.deleteObjects).toHaveBeenCalledTimes(0)
500
- })
498
+ test('should call DELETE /files/:key for specific file', async () => {
499
+ global.fetch.mockResolvedValue(mockResponse({ success: true }))
500
+ const rs = new RemoteStorage()
501
+ const appConfig = createAppConfig()
501
502
 
502
- test('emptyFolder should call S3#deleteObjects with correct parameters with one file', async () => {
503
- const content = [{ Key: 'fakeprefix/index.html' }]
504
- mockS3.listObjectsV2.mockResolvedValue({ KeyCount: 1, Contents: content })
505
- const rs = new RemoteStorage(global.fakeTVMResponse)
506
- await rs.emptyFolder('fakeprefix')
507
- expect(mockS3.deleteObjects).toHaveBeenCalledWith({ Bucket: 'fake-bucket', Delete: { Objects: content } })
508
- })
503
+ const result = await rs.emptyFolder(global.fakeAuthToken, 'path/to/file.txt', appConfig)
509
504
 
510
- test('emptyFolder should call S3#deleteObjects with correct parameters with multiple files', async () => {
511
- const content = [{ Key: 'fakeprefix/index.html' }, { Key: 'fakeprefix/index.css' }, { Key: 'fakeprefix/index.css' }]
512
- mockS3.listObjectsV2.mockResolvedValue({ KeyCount: 3, Contents: content })
513
- const rs = new RemoteStorage(global.fakeTVMResponse)
514
- await rs.emptyFolder('fakeprefix')
515
- expect(mockS3.deleteObjects).toHaveBeenCalledWith({ Bucket: 'fake-bucket', Delete: { Objects: content } })
516
- })
505
+ expect(result).toBe(true)
506
+ expect(global.fetch).toHaveBeenCalledWith(
507
+ expect.stringContaining(`/cdn-api/namespaces/${global.fakeNamespace}/files/path/to/file.txt`),
508
+ expect.objectContaining({ method: 'DELETE' })
509
+ )
510
+ })
517
511
 
518
- test('emptyFolder should call S3#deleteObjects multiple time if listObjects is truncated', async () => {
519
- const content = [{ Key: 'fakeprefix/index.html' }, { Key: 'fakeprefix/index.css' }, { Key: 'fakeprefix/index.js' }]
520
- let iterations = 2
521
- mockS3.listObjectsV2.mockImplementation(() => {
522
- const res = { Contents: [content[iterations]], IsTruncated: iterations > 0 }
523
- iterations--
524
- return Promise.resolve(res)
525
- })
526
- const rs = new RemoteStorage(global.fakeTVMResponse)
527
- await rs.emptyFolder('fakeprefix')
528
- expect(mockS3.deleteObjects).toHaveBeenCalledWith({ Bucket: 'fake-bucket', Delete: { Objects: [content[0]] } })
529
- expect(mockS3.deleteObjects).toHaveBeenCalledWith({ Bucket: 'fake-bucket', Delete: { Objects: [content[1]] } })
530
- expect(mockS3.deleteObjects).toHaveBeenCalledWith({ Bucket: 'fake-bucket', Delete: { Objects: [content[2]] } })
531
- })
512
+ test('should return false if delete fails', async () => {
513
+ global.fetch.mockResolvedValue(mockResponse(null, { ok: false, status: 500 }))
514
+ const rs = new RemoteStorage()
515
+ const appConfig = createAppConfig()
532
516
 
533
- test('uploadFile should call S3#upload with the correct parameters', async () => {
534
- global.addFakeFiles(vol, 'fakeDir', { 'index.js': 'fake content' })
535
- const rs = new RemoteStorage(global.fakeTVMResponse)
536
- const fakeConfig = global.fakeConfig
537
- await rs.uploadFile('fakeDir/index.js', 'fakeprefix', fakeConfig, 'fakeDir')
538
- const body = Buffer.from('fake content', 'utf8')
539
- expect(mockS3.putObject).toHaveBeenCalledWith(expect.objectContaining({ Bucket: 'fake-bucket', Key: 'fakeprefix/index.js', Body: body, ContentType: 'application/javascript' }))
540
- })
517
+ const result = await rs.emptyFolder(global.fakeAuthToken, '/', appConfig)
541
518
 
542
- test('uploadFile should call S3#upload with the correct parameters and slash-prefix', async () => {
543
- global.addFakeFiles(vol, 'fakeDir', { 'index.js': 'fake content' })
544
- const rs = new RemoteStorage(global.fakeTVMResponse)
545
- const fakeConfig = global.fakeConfig
546
- await rs.uploadFile('fakeDir/index.js', '/slash-prefix', fakeConfig, 'fakeDir')
547
- const body = Buffer.from('fake content', 'utf8')
548
- expect(mockS3.putObject).toHaveBeenCalledWith(expect.objectContaining({ Bucket: 'fake-bucket', Key: '/slash-prefix/index.js', Body: body, ContentType: 'application/javascript' }))
519
+ expect(result).toBe(false)
520
+ })
549
521
  })
550
522
 
551
- test('uploadFile S3#upload with an unknown Content-Type', async () => {
552
- global.addFakeFiles(vol, 'fakeDir', { 'index.mst': 'fake content' })
553
- const rs = new RemoteStorage(global.fakeTVMResponse)
554
- const fakeConfig = {}
555
- await rs.uploadFile('fakeDir/index.mst', 'fakeprefix', fakeConfig, 'fakeDir')
556
- const body = Buffer.from('fake content', 'utf8')
557
- expect(mockS3.putObject).toHaveBeenCalledWith(expect.objectContaining({ Bucket: 'fake-bucket', Key: 'fakeprefix/index.mst', Body: body }))
558
- expect(mockS3.putObject.mock.calls[0][0]).not.toHaveProperty('ContentType')
559
- })
523
+ describe('uploadFile', () => {
524
+ test('missing filePath should throw', async () => {
525
+ const rs = new RemoteStorage()
526
+ const appConfig = createAppConfig()
527
+ await expect(rs.uploadFile(global.fakeAuthToken, 'file.txt', undefined, appConfig, 'dist')).rejects.toEqual(
528
+ expect.objectContaining({ message: 'filePath must be a valid string' })
529
+ )
530
+ })
560
531
 
561
- test('uploadDir should call S3#upload one time per file', async () => {
562
- await global.addFakeFiles(vol, 'fakeDir', ['index.js', 'index.css', 'index.html'])
563
- const rs = new RemoteStorage(global.fakeTVMResponse)
564
- await rs.uploadDir('fakeDir', 'fakeprefix', global.fakeConfig)
565
- expect(mockS3.putObject).toHaveBeenCalledTimes(3)
566
- })
532
+ test('should call PUT /files with correct parameters', async () => {
533
+ global.addFakeFiles(vol, 'fakeDir', { 'index.js': 'fake content' })
534
+ global.fetch.mockResolvedValue(mockResponse({ success: true }))
535
+ const rs = new RemoteStorage()
536
+ const appConfig = createAppConfig()
537
+
538
+ await rs.uploadFile(global.fakeAuthToken, 'fakeDir/index.js', 'fakeprefix', appConfig, 'fakeDir')
539
+
540
+ expect(global.fetch).toHaveBeenCalledWith(
541
+ expect.stringContaining(`/cdn-api/namespaces/${global.fakeNamespace}/files`),
542
+ expect.objectContaining({
543
+ method: 'PUT',
544
+ headers: {
545
+ 'Content-Type': 'application/json',
546
+ Authorization: global.fakeAuthToken
547
+ }
548
+ })
549
+ )
550
+
551
+ // Verify the body contains expected data
552
+ const callArgs = global.fetch.mock.calls[0]
553
+ const body = JSON.parse(callArgs[1].body)
554
+ expect(body.file).toMatchObject({
555
+ name: 'fakeprefix/index.js',
556
+ contentType: 'application/javascript'
557
+ })
558
+ expect(body.file.content).toBeDefined() // base64 encoded content
559
+ })
567
560
 
568
- test('uploadDir should call a callback once per uploaded file', async () => {
569
- await global.addFakeFiles(vol, 'fakeDir', ['index.js', 'index.css', 'index.html', 'test/i.js'])
570
- const cbMock = jest.fn()
571
- const rs = new RemoteStorage(global.fakeTVMResponse)
561
+ test('should call PUT /files without slash-prefix', async () => {
562
+ global.addFakeFiles(vol, 'fakeDir', { 'index.js': 'fake content' })
563
+ global.fetch.mockResolvedValue(mockResponse({ success: true }))
564
+ const rs = new RemoteStorage()
565
+ const appConfig = createAppConfig()
572
566
 
573
- await rs.uploadDir('fakeDir', 'fakeprefix', global.fakeConfig, cbMock)
574
- expect(cbMock).toHaveBeenCalledTimes(4)
575
- })
567
+ await rs.uploadFile(global.fakeAuthToken, 'fakeDir/index.js', '/slash-prefix', appConfig, 'fakeDir')
576
568
 
577
- test('cachecontrol string for html', async () => {
578
- const rs = new RemoteStorage(global.fakeTVMResponse)
579
- const response = rs._getCacheControlConfig('text/html', global.fakeConfig.app)
580
- expect(response).toBe('s-maxage=60, max-age=60')
581
- })
569
+ const callArgs = global.fetch.mock.calls[0]
570
+ const body = JSON.parse(callArgs[1].body)
571
+ expect(body.file.name).toBe('slash-prefix/index.js')
572
+ })
582
573
 
583
- test('cachecontrol string for JS', async () => {
584
- const rs = new RemoteStorage(global.fakeTVMResponse)
585
- const response = rs._getCacheControlConfig('application/javascript', global.fakeConfig.app)
586
- expect(response).toBe('s-maxage=60, max-age=604800')
587
- })
574
+ test('should preserve filePath when it contains namespace text', async () => {
575
+ global.addFakeFiles(vol, 'fakeDir', { 'index.js': 'fake content' })
576
+ global.fetch.mockResolvedValue(mockResponse({ success: true }))
577
+ const rs = new RemoteStorage()
578
+ const appConfig = createAppConfig()
588
579
 
589
- test('cachecontrol string for CSS', async () => {
590
- const rs = new RemoteStorage(global.fakeTVMResponse)
591
- const response = rs._getCacheControlConfig('text/css', global.fakeConfig.app)
592
- expect(response).toBe('s-maxage=60, max-age=604800')
593
- })
580
+ // filePath should be preserved as-is and only normalized for slashes
581
+ await rs.uploadFile(global.fakeAuthToken, 'fakeDir/index.js', `${global.fakeNamespace}/subpath`, appConfig, 'fakeDir')
594
582
 
595
- test('cachecontrol string for Image', async () => {
596
- const rs = new RemoteStorage(global.fakeTVMResponse)
597
- const response = rs._getCacheControlConfig('image/jpeg', global.fakeConfig.app)
598
- expect(response).toBe('s-maxage=60, max-age=604800')
599
- })
583
+ const callArgs = global.fetch.mock.calls[0]
584
+ const body = JSON.parse(callArgs[1].body)
585
+ expect(body.file.name).toBe(`${global.fakeNamespace}/subpath/index.js`)
586
+ })
600
587
 
601
- test('cachecontrol string for default', async () => {
602
- const rs = new RemoteStorage(global.fakeTVMResponse)
603
- const response = rs._getCacheControlConfig('application/pdf', global.fakeConfig.app)
604
- expect(response).toBe(null)
605
- })
588
+ test('should handle unknown Content-Type', async () => {
589
+ global.addFakeFiles(vol, 'fakeDir', { 'index.mst': 'fake content' })
590
+ global.fetch.mockResolvedValue(mockResponse({ success: true }))
591
+ const rs = new RemoteStorage()
592
+ const appConfig = createAppConfig()
606
593
 
607
- test('cachecontrol string for html when htmlCacheDuration is not defined', async () => {
608
- const rs = new RemoteStorage(global.fakeTVMResponse)
609
- const appConfigWithoutHtmlCache = global.configWithMissing(global.fakeConfig.app, 'htmlCacheDuration')
610
- const response = rs._getCacheControlConfig('text/html', appConfigWithoutHtmlCache)
611
- expect(response).toBe(null)
612
- })
594
+ await rs.uploadFile(global.fakeAuthToken, 'fakeDir/index.mst', 'fakeprefix', appConfig, 'fakeDir')
613
595
 
614
- test('cachecontrol string for JS when jsCacheDuration is not defined', async () => {
615
- const rs = new RemoteStorage(global.fakeTVMResponse)
616
- const appConfigWithoutJsCache = global.configWithMissing(global.fakeConfig.app, 'jsCacheDuration')
617
- const response = rs._getCacheControlConfig('application/javascript', appConfigWithoutJsCache)
618
- expect(response).toBe(null)
596
+ const callArgs = global.fetch.mock.calls[0]
597
+ const body = JSON.parse(callArgs[1].body)
598
+ expect(body.file.name).toBe('fakeprefix/index.mst')
599
+ // contentType will be false for unknown extensions
600
+ expect(body.file.contentType).toBe(false)
601
+ })
602
+
603
+ test('should handle empty filePath (file at root)', async () => {
604
+ global.addFakeFiles(vol, 'fakeDir', { 'index.js': 'fake content' })
605
+ global.fetch.mockResolvedValue(mockResponse({ success: true }))
606
+ const rs = new RemoteStorage()
607
+ const appConfig = createAppConfig()
608
+
609
+ await rs.uploadFile(global.fakeAuthToken, 'fakeDir/index.js', '', appConfig, 'fakeDir')
610
+
611
+ const callArgs = global.fetch.mock.calls[0]
612
+ const body = JSON.parse(callArgs[1].body)
613
+ // When filePath is empty, file.name should just be the filename
614
+ expect(body.file.name).toBe('index.js')
615
+ })
616
+
617
+ test('should throw if upload fails', async () => {
618
+ global.addFakeFiles(vol, 'fakeDir', { 'index.js': 'fake content' })
619
+ global.fetch.mockResolvedValue(mockResponse(null, { ok: false, status: 500, statusText: 'Internal Server Error' }))
620
+ const rs = new RemoteStorage()
621
+ const appConfig = createAppConfig()
622
+ const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
623
+
624
+ await expect(
625
+ rs.uploadFile(global.fakeAuthToken, 'fakeDir/index.js', 'fakeprefix', appConfig, 'fakeDir')
626
+ ).rejects.toThrow('Failed to upload file: Internal Server Error')
627
+
628
+ expect(consoleSpy).toHaveBeenCalledWith('Failed to upload file:', 'fakeDir/index.js')
629
+ consoleSpy.mockRestore()
630
+ })
631
+
632
+ test('should throw if fetch itself throws (network error)', async () => {
633
+ global.addFakeFiles(vol, 'fakeDir', { 'index.js': 'fake content' })
634
+ global.fetch.mockRejectedValue(new Error('Network error'))
635
+ const rs = new RemoteStorage()
636
+ const appConfig = createAppConfig()
637
+ const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
638
+
639
+ await expect(
640
+ rs.uploadFile(global.fakeAuthToken, 'fakeDir/index.js', 'fakeprefix', appConfig, 'fakeDir')
641
+ ).rejects.toThrow('Network error')
642
+
643
+ expect(consoleSpy).toHaveBeenCalledWith('Error uploading file:', 'fakeDir/index.js')
644
+ consoleSpy.mockRestore()
645
+ })
619
646
  })
620
647
 
621
- test('cachecontrol string for CSS when cssCacheDuration is not defined', async () => {
622
- const rs = new RemoteStorage(global.fakeTVMResponse)
623
- const appConfigWithoutCssCache = global.configWithMissing(global.fakeConfig.app, 'cssCacheDuration')
624
- const response = rs._getCacheControlConfig('text/css', appConfigWithoutCssCache)
625
- expect(response).toBe(null)
648
+ describe('uploadDir', () => {
649
+ test('missing basePath should throw', async () => {
650
+ const rs = new RemoteStorage()
651
+ const appConfig = createAppConfig()
652
+ await expect(rs.uploadDir(global.fakeAuthToken, 'fakeDir', undefined, appConfig)).rejects.toEqual(
653
+ expect.objectContaining({ message: 'basePath must be a valid string' })
654
+ )
655
+ })
656
+
657
+ test('should upload all files in directory', async () => {
658
+ global.addFakeFiles(vol, 'fakeDir', ['index.js', 'index.css', 'index.html'])
659
+ global.fetch.mockResolvedValue(mockResponse({ success: true }))
660
+ const rs = new RemoteStorage()
661
+ const appConfig = createAppConfig()
662
+
663
+ await rs.uploadDir(global.fakeAuthToken, 'fakeDir', 'fakeprefix', appConfig)
664
+
665
+ // Should have called fetch for each file
666
+ expect(global.fetch).toHaveBeenCalledTimes(3)
667
+ })
668
+
669
+ test('should call callback once per uploaded file', async () => {
670
+ global.addFakeFiles(vol, 'fakeDir', ['index.js', 'index.css', 'index.html', 'test/i.js'])
671
+ global.fetch.mockResolvedValue(mockResponse({ success: true }))
672
+ const cbMock = jest.fn()
673
+ const rs = new RemoteStorage()
674
+ const appConfig = createAppConfig()
675
+
676
+ await rs.uploadDir(global.fakeAuthToken, 'fakeDir', 'fakeprefix', appConfig, cbMock)
677
+
678
+ expect(cbMock).toHaveBeenCalledTimes(4)
679
+ })
680
+
681
+ test('should return upload results in batches', async () => {
682
+ global.addFakeFiles(vol, 'fakeDir', ['file1.js', 'file2.js', 'file3.js'])
683
+ global.fetch.mockResolvedValue(mockResponse({ success: true }, { status: 200 }))
684
+ const rs = new RemoteStorage()
685
+ const appConfig = createAppConfig()
686
+
687
+ const results = await rs.uploadDir(global.fakeAuthToken, 'fakeDir', 'fakeprefix', appConfig)
688
+
689
+ // Results should be an array of batches, each batch containing upload status codes
690
+ expect(Array.isArray(results)).toBe(true)
691
+ expect(results.length).toBeGreaterThan(0)
692
+ // Each batch result should contain status codes (200)
693
+ expect(results[0]).toEqual([200, 200, 200])
694
+ })
695
+
696
+ test('should call callback with file path for each uploaded file', async () => {
697
+ global.addFakeFiles(vol, 'fakeDir', ['file1.js', 'file2.js'])
698
+ global.fetch.mockResolvedValue(mockResponse({ success: true }))
699
+ const cbMock = jest.fn()
700
+ const rs = new RemoteStorage()
701
+ const appConfig = createAppConfig()
702
+
703
+ await rs.uploadDir(global.fakeAuthToken, 'fakeDir', 'fakeprefix', appConfig, cbMock)
704
+
705
+ // Callback should receive the file path
706
+ expect(cbMock).toHaveBeenCalledTimes(2)
707
+ cbMock.mock.calls.forEach(call => {
708
+ expect(call[0]).toMatch(/fakeDir/)
709
+ })
710
+ })
626
711
  })
627
712
 
628
- test('cachecontrol string for image when imageCacheDuration is not defined', async () => {
629
- const rs = new RemoteStorage(global.fakeTVMResponse)
630
- const appConfigWithoutImageCache = global.configWithMissing(global.fakeConfig.app, 'imageCacheDuration')
631
- const response = rs._getCacheControlConfig('image/jpeg', appConfigWithoutImageCache)
632
- expect(response).toBe(null)
713
+ describe('cache control', () => {
714
+ test('cachecontrol string for html', async () => {
715
+ const rs = new RemoteStorage()
716
+ const response = rs._getCacheControlConfig('text/html', global.fakeConfig.app)
717
+ expect(response).toBe('s-maxage=60, max-age=60')
718
+ })
719
+
720
+ test('cachecontrol string for JS', async () => {
721
+ const rs = new RemoteStorage()
722
+ const response = rs._getCacheControlConfig('application/javascript', global.fakeConfig.app)
723
+ expect(response).toBe('s-maxage=60, max-age=604800')
724
+ })
725
+
726
+ test('cachecontrol string for CSS', async () => {
727
+ const rs = new RemoteStorage()
728
+ const response = rs._getCacheControlConfig('text/css', global.fakeConfig.app)
729
+ expect(response).toBe('s-maxage=60, max-age=604800')
730
+ })
731
+
732
+ test('cachecontrol string for Image', async () => {
733
+ const rs = new RemoteStorage()
734
+ const response = rs._getCacheControlConfig('image/jpeg', global.fakeConfig.app)
735
+ expect(response).toBe('s-maxage=60, max-age=604800')
736
+ })
737
+
738
+ test('cachecontrol string for default', async () => {
739
+ const rs = new RemoteStorage()
740
+ const response = rs._getCacheControlConfig('application/pdf', global.fakeConfig.app)
741
+ expect(response).toBe(null)
742
+ })
743
+
744
+ test('cachecontrol string for html when htmlCacheDuration is not defined', async () => {
745
+ const rs = new RemoteStorage()
746
+ const appConfigWithoutHtmlCache = global.configWithMissing(global.fakeConfig.app, 'htmlCacheDuration')
747
+ const response = rs._getCacheControlConfig('text/html', appConfigWithoutHtmlCache)
748
+ expect(response).toBe(null)
749
+ })
750
+
751
+ test('cachecontrol string for JS when jsCacheDuration is not defined', async () => {
752
+ const rs = new RemoteStorage()
753
+ const appConfigWithoutJsCache = global.configWithMissing(global.fakeConfig.app, 'jsCacheDuration')
754
+ const response = rs._getCacheControlConfig('application/javascript', appConfigWithoutJsCache)
755
+ expect(response).toBe(null)
756
+ })
757
+
758
+ test('cachecontrol string for CSS when cssCacheDuration is not defined', async () => {
759
+ const rs = new RemoteStorage()
760
+ const appConfigWithoutCssCache = global.configWithMissing(global.fakeConfig.app, 'cssCacheDuration')
761
+ const response = rs._getCacheControlConfig('text/css', appConfigWithoutCssCache)
762
+ expect(response).toBe(null)
763
+ })
764
+
765
+ test('cachecontrol string for image when imageCacheDuration is not defined', async () => {
766
+ const rs = new RemoteStorage()
767
+ const appConfigWithoutImageCache = global.configWithMissing(global.fakeConfig.app, 'imageCacheDuration')
768
+ const response = rs._getCacheControlConfig('image/jpeg', appConfigWithoutImageCache)
769
+ expect(response).toBe(null)
770
+ })
633
771
  })
634
772
 
635
- // response header tests
636
- test('get response header from config with multiple rules', async () => {
637
- const rs = new RemoteStorage(global.fakeTVMResponse)
638
- const newConfig = global.configWithModifiedWeb(global.fakeConfig, {
639
- 'response-headers': {
640
- '/*': {
641
- testHeader: 'generic-header'
642
- },
643
- '/testFolder/*': {
644
- testHeader: 'folder-header'
645
- },
646
- '/testFolder/*.js': {
647
- testHeader: 'all-js-file-in-folder-header'
648
- },
649
- '/test.js': {
650
- testHeader: 'specific-file-header'
773
+ describe('response headers', () => {
774
+ test('get response header from config with multiple rules', async () => {
775
+ const rs = new RemoteStorage()
776
+ const newConfig = global.configWithModifiedWeb(global.fakeConfig, {
777
+ 'response-headers': {
778
+ '/*': {
779
+ testHeader: 'generic-header'
780
+ },
781
+ '/testFolder/*': {
782
+ testHeader: 'folder-header'
783
+ },
784
+ '/testFolder/*.js': {
785
+ testHeader: 'all-js-file-in-folder-header'
786
+ },
787
+ '/test.js': {
788
+ testHeader: 'specific-file-header'
789
+ }
651
790
  }
791
+ })
792
+
793
+ const folderPath1 = 'testFolder' + path.sep + 'index.html'
794
+ const folderPath2 = 'testFolder' + path.sep + 'test.js'
795
+ await global.addFakeFiles(vol, 'fakeDir', ['index.html', 'test.js', folderPath1, folderPath2])
796
+ const files = await rs.walkDir('fakeDir')
797
+ const fakeDistRoot = path.parse(files[0]).dir
798
+
799
+ const expectedValMap = {
800
+ 'index.html': { 'adp-testHeader': 'generic-header' },
801
+ 'test.js': { 'adp-testHeader': 'specific-file-header' }
652
802
  }
803
+ expectedValMap[folderPath1] = { 'adp-testHeader': 'folder-header' }
804
+ expectedValMap[folderPath2] = { 'adp-testHeader': 'all-js-file-in-folder-header' }
805
+
806
+ files.forEach(f => {
807
+ const fileName = f.replace(path.join(fakeDistRoot, path.sep), '')
808
+ const response = rs.getResponseHeadersForFile(f, fakeDistRoot, newConfig)
809
+ const expected = expectedValMap[fileName]
810
+ expect(response).toStrictEqual(expected)
811
+ })
653
812
  })
654
813
 
655
- const folderPath1 = 'testFolder' + path.sep + 'index.html'
656
- const folderPath2 = 'testFolder' + path.sep + 'test.js'
657
- await global.addFakeFiles(vol, 'fakeDir', ['index.html', 'test.js', folderPath1, folderPath2])
658
- const files = await rs.walkDir('fakeDir')
659
- const fakeDistRoot = path.parse(files[0]).dir
814
+ test('get response header for folder based path rules', async () => {
815
+ const rs = new RemoteStorage()
816
+ const folderPath1 = 'css' + path.sep + 'ui.css'
817
+ const folderPath2 = 'scripts' + path.sep + 'test.js'
818
+ const folderPath3 = 'images' + path.sep + 'image.png'
819
+ const folderPath4 = 'images' + path.sep + 'thumbnails' + path.sep + 'test.jpeg'
820
+ await global.addFakeFiles(vol, 'fakeDir', ['index.html', 'test.js', folderPath1, folderPath2, folderPath3, folderPath4])
821
+ const files = await rs.walkDir('fakeDir')
822
+ const fakeDistRoot = path.parse(files[0]).dir
823
+
824
+ const newConfig = global.configWithModifiedWeb(global.fakeConfig, {
825
+ 'response-headers': {
826
+ '/*': {
827
+ testHeader: 'generic-header'
828
+ },
829
+ '/css/*': {
830
+ testHeader: 'all-files-in-css-folder-header'
831
+ },
832
+ '/scripts/*': {
833
+ testHeader: 'all-files-in-js-folder-header'
834
+ },
835
+ '/images/*': {
836
+ testHeader: 'all-files-in-images-folder-header'
837
+ }
838
+ }
839
+ })
660
840
 
661
- const expectedValMap = {
662
- 'index.html': { 'adp-testHeader': 'generic-header' },
663
- 'test.js': { 'adp-testHeader': 'specific-file-header' }
664
- }
665
- expectedValMap[folderPath1] = { 'adp-testHeader': 'folder-header' }
666
- expectedValMap[folderPath2] = { 'adp-testHeader': 'all-js-file-in-folder-header' }
841
+ const expectedValMap = {
842
+ 'index.html': { 'adp-testHeader': 'generic-header' },
843
+ 'test.js': { 'adp-testHeader': 'generic-header' }
844
+ }
845
+ expectedValMap[folderPath1] = { 'adp-testHeader': 'all-files-in-css-folder-header' }
846
+ expectedValMap[folderPath2] = { 'adp-testHeader': 'all-files-in-js-folder-header' }
847
+ expectedValMap[folderPath3] = { 'adp-testHeader': 'all-files-in-images-folder-header' }
848
+ expectedValMap[folderPath4] = { 'adp-testHeader': 'all-files-in-images-folder-header' }
849
+
850
+ files.forEach(f => {
851
+ const fileName = f.replace(path.join(fakeDistRoot, path.sep), '')
852
+ const response = rs.getResponseHeadersForFile(f, fakeDistRoot, newConfig)
853
+ const expected = expectedValMap[fileName]
854
+ expect(response).toStrictEqual(expected)
855
+ })
856
+ })
857
+
858
+ test('get response header for specific file based path rules', async () => {
859
+ const rs = new RemoteStorage()
860
+ const folderPath1 = 'css' + path.sep + 'ui.css'
861
+ const folderPath2 = 'scripts' + path.sep + 'test.js'
862
+ const folderPath3 = 'images' + path.sep + 'image.png'
863
+ await global.addFakeFiles(vol, 'fakeDir', ['index.html', 'test.js', folderPath1, folderPath2, folderPath3])
864
+ const files = await rs.walkDir('fakeDir')
865
+ const fakeDistRoot = path.parse(files[0]).dir
866
+
867
+ const newConfig = global.configWithModifiedWeb(global.fakeConfig, {
868
+ 'response-headers': {
869
+ '/*': {
870
+ testHeader: 'generic-header'
871
+ },
872
+ '/css/*': {
873
+ testHeader: 'all-files-in-css-folder-header'
874
+ },
875
+ '/css/ui.css': {
876
+ testHeader: 'specific-css-file-header'
877
+ },
878
+ '/scripts/*': {
879
+ testHeader: 'all-files-in-js-folder-header'
880
+ },
881
+ '/scripts/test.js': {
882
+ testHeader: 'specific-js-file-header'
883
+ },
884
+ '/images/*': {
885
+ testHeader: 'all-files-in-images-folder-header'
886
+ },
887
+ '/images/image.png': {
888
+ testHeader: 'specific-image-file-header'
889
+ }
890
+ }
891
+ })
667
892
 
668
- files.forEach(f => {
669
- const fileName = f.replace(path.join(fakeDistRoot, path.sep), '')
670
- const response = rs.getResponseHeadersForFile(f, fakeDistRoot, newConfig)
671
- const expected = expectedValMap[fileName]
672
- expect(response).toStrictEqual(expected)
893
+ const expectedValMap = {
894
+ 'index.html': { 'adp-testHeader': 'generic-header' },
895
+ 'test.js': { 'adp-testHeader': 'generic-header' }
896
+ }
897
+ expectedValMap[folderPath1] = { 'adp-testHeader': 'specific-css-file-header' }
898
+ expectedValMap[folderPath2] = { 'adp-testHeader': 'specific-js-file-header' }
899
+ expectedValMap[folderPath3] = { 'adp-testHeader': 'specific-image-file-header' }
900
+
901
+ files.forEach(f => {
902
+ const fileName = f.replace(path.join(fakeDistRoot, path.sep), '')
903
+ const response = rs.getResponseHeadersForFile(f, fakeDistRoot, newConfig)
904
+ const expected = expectedValMap[fileName]
905
+ expect(response).toStrictEqual(expected)
906
+ })
673
907
  })
674
- })
675
908
 
676
- test('get response header for folder based path rules', async () => {
677
- // setup files and paths
678
- const rs = new RemoteStorage(global.fakeTVMResponse)
679
- const folderPath1 = 'css' + path.sep + 'ui.css'
680
- const folderPath2 = 'scripts' + path.sep + 'test.js'
681
- const folderPath3 = 'images' + path.sep + 'image.png'
682
- const folderPath4 = 'images' + path.sep + 'thumbnails' + path.sep + 'test.jpeg'
683
- await global.addFakeFiles(vol, 'fakeDir', ['index.html', 'test.js', folderPath1, folderPath2, folderPath3, folderPath4])
684
- const files = await rs.walkDir('fakeDir')
685
- const fakeDistRoot = path.parse(files[0]).dir
686
-
687
- // create a config of rules for files in specific folder
688
- const newConfig = global.configWithModifiedWeb(global.fakeConfig, {
689
- 'response-headers': {
690
- '/*': {
691
- testHeader: 'generic-header'
692
- },
693
- '/css/*': {
694
- testHeader: 'all-files-in-css-folder-header'
695
- },
696
- '/scripts/*': {
697
- testHeader: 'all-files-in-js-folder-header'
698
- },
699
- '/images/*': {
700
- testHeader: 'all-files-in-images-folder-header'
909
+ test('get response header for file extension based path rules', async () => {
910
+ const rs = new RemoteStorage()
911
+ const folderPath1 = 'css' + path.sep + 'ui.css'
912
+ const folderPath2 = 'scripts' + path.sep + 'test.js'
913
+ const folderPath3 = 'images' + path.sep + 'image.png'
914
+ await global.addFakeFiles(vol, 'fakeDir', ['index.html', 'test.js', folderPath1, folderPath2, folderPath3])
915
+ const files = await rs.walkDir('fakeDir')
916
+ const fakeDistRoot = path.parse(files[0]).dir
917
+
918
+ const newConfig = global.configWithModifiedWeb(global.fakeConfig, {
919
+ 'response-headers': {
920
+ '/*': {
921
+ testHeader: 'generic-header'
922
+ },
923
+ '/*.css': {
924
+ testHeader: 'all-css-files-header'
925
+ },
926
+ '/*.js': {
927
+ testHeader: 'all-js-files-header'
928
+ },
929
+ '/*.png': {
930
+ testHeader: 'all-png-files-header'
931
+ }
701
932
  }
933
+ })
934
+
935
+ const expectedValMap = {
936
+ 'index.html': { 'adp-testHeader': 'generic-header' },
937
+ 'test.js': { 'adp-testHeader': 'all-js-files-header' }
702
938
  }
939
+ expectedValMap[folderPath1] = { 'adp-testHeader': 'all-css-files-header' }
940
+ expectedValMap[folderPath2] = { 'adp-testHeader': 'all-js-files-header' }
941
+ expectedValMap[folderPath3] = { 'adp-testHeader': 'all-png-files-header' }
942
+
943
+ files.forEach(f => {
944
+ const fileName = f.replace(path.join(fakeDistRoot, path.sep), '')
945
+ const response = rs.getResponseHeadersForFile(f, fakeDistRoot, newConfig)
946
+ const expected = expectedValMap[fileName]
947
+ expect(response).toStrictEqual(expected)
948
+ })
703
949
  })
704
950
 
705
- // set the expectation
706
- const expectedValMap = {
707
- 'index.html': { 'adp-testHeader': 'generic-header' },
708
- 'test.js': { 'adp-testHeader': 'generic-header' }
709
- }
710
- expectedValMap[folderPath1] = { 'adp-testHeader': 'all-files-in-css-folder-header' }
711
- expectedValMap[folderPath2] = { 'adp-testHeader': 'all-files-in-js-folder-header' }
712
- expectedValMap[folderPath3] = { 'adp-testHeader': 'all-files-in-images-folder-header' }
713
- expectedValMap[folderPath4] = { 'adp-testHeader': 'all-files-in-images-folder-header' }
714
-
715
- // check header application per file
716
- files.forEach(f => {
717
- const fileName = f.replace(path.join(fakeDistRoot, path.sep), '')
718
- const response = rs.getResponseHeadersForFile(f, fakeDistRoot, newConfig)
719
- const expected = expectedValMap[fileName]
720
- expect(response).toStrictEqual(expected)
951
+ test('get response header with invalid header name', async () => {
952
+ const rs = new RemoteStorage()
953
+ const newConfig = global.configWithModifiedWeb(global.fakeConfig, {
954
+ 'response-headers': {
955
+ '/*': {
956
+ 無効な名前: 'generic-header'
957
+ }
958
+ }
959
+ })
960
+
961
+ const fakeDistRoot = '/fake/web-prod/'
962
+ expect(() => rs.getResponseHeadersForFile(fakeDistRoot + 'index.html', fakeDistRoot, newConfig)).toThrowWithMessageContaining(
963
+ '[WebLib:ERROR_INVALID_HEADER_NAME] `無効な名前` is not a valid response header name')
964
+ })
965
+
966
+ test('get response header with invalid header value', async () => {
967
+ const rs = new RemoteStorage()
968
+ const newConfig = global.configWithModifiedWeb(global.fakeConfig, {
969
+ 'response-headers': {
970
+ '/*': {
971
+ testHeader: '無効な値'
972
+ }
973
+ }
974
+ })
975
+
976
+ const fakeDistRoot = '/fake/web-prod/'
977
+ expect(() => rs.getResponseHeadersForFile(fakeDistRoot + 'index.html', fakeDistRoot, newConfig)).toThrowWithMessageContaining(
978
+ '[WebLib:ERROR_INVALID_HEADER_VALUE] `無効な値` is not a valid response header value for `testHeader`')
721
979
  })
722
980
  })
723
981
 
724
- test('get response header for specific file based path rules', async () => {
725
- // setup files and paths
726
- const rs = new RemoteStorage(global.fakeTVMResponse)
727
- const folderPath1 = 'css' + path.sep + 'ui.css'
728
- const folderPath2 = 'scripts' + path.sep + 'test.js'
729
- const folderPath3 = 'images' + path.sep + 'image.png'
730
- await global.addFakeFiles(vol, 'fakeDir', ['index.html', 'test.js', folderPath1, folderPath2, folderPath3])
731
- const files = await rs.walkDir('fakeDir')
732
- const fakeDistRoot = path.parse(files[0]).dir
733
-
734
- // create a config of rules for spcefic files which overrider folder rules
735
- const newConfig = global.configWithModifiedWeb(global.fakeConfig, {
736
- 'response-headers': {
737
- '/*': {
738
- testHeader: 'generic-header'
739
- },
740
- '/css/*': {
741
- testHeader: 'all-files-in-css-folder-header'
742
- },
743
- '/css/ui.css': {
744
- testHeader: 'specific-css-file-header' // overrides previous css folder rule
745
- },
746
- '/scripts/*': {
747
- testHeader: 'all-files-in-js-folder-header'
748
- },
749
- '/scripts/test.js': {
750
- testHeader: 'specific-js-file-header' // overrides previous js folder rule
751
- },
752
- '/images/*': {
753
- testHeader: 'all-files-in-images-folder-header'
754
- },
755
- '/images/image.png': {
756
- testHeader: 'specific-image-file-header' // overrides previous image folder rule
982
+ describe('uploadFile with response headers', () => {
983
+ test('includes response headers in upload request', async () => {
984
+ global.addFakeFiles(vol, 'fakeDir', { 'index.js': 'fake content' })
985
+ global.fetch.mockResolvedValue(mockResponse({ success: true }))
986
+ const rs = new RemoteStorage()
987
+ const files = await rs.walkDir('fakeDir')
988
+ const fakeDistRoot = files[0].substring(0, files[0].indexOf('index.js'))
989
+ const newConfig = global.configWithModifiedWeb(createAppConfig(), {
990
+ 'response-headers': {
991
+ '/*': {
992
+ testHeader: 'generic-header'
993
+ }
757
994
  }
758
- }
995
+ })
996
+
997
+ await rs.uploadFile(global.fakeAuthToken, 'fakeDir/index.js', 'fakeprefix', newConfig, fakeDistRoot)
998
+
999
+ const callArgs = global.fetch.mock.calls[0]
1000
+ const body = JSON.parse(callArgs[1].body)
1001
+ expect(body.file.customHeaders).toMatchObject({
1002
+ 'adp-testHeader': 'generic-header'
1003
+ })
759
1004
  })
760
1005
 
761
- // set the expectation
762
- const expectedValMap = {
763
- 'index.html': { 'adp-testHeader': 'generic-header' },
764
- 'test.js': { 'adp-testHeader': 'generic-header' }
765
- }
766
- expectedValMap[folderPath1] = { 'adp-testHeader': 'specific-css-file-header' }
767
- expectedValMap[folderPath2] = { 'adp-testHeader': 'specific-js-file-header' }
768
- expectedValMap[folderPath3] = { 'adp-testHeader': 'specific-image-file-header' }
1006
+ test('cache control override from response headers', async () => {
1007
+ global.addFakeFiles(vol, 'fakeDir', { 'index.html': 'fake content' })
1008
+ global.fetch.mockResolvedValue(mockResponse({ success: true }))
1009
+ const rs = new RemoteStorage()
1010
+ const files = await rs.walkDir('fakeDir')
1011
+ const fakeDistRoot = path.parse(files[0]).dir
1012
+ const filePath = files[0]
1013
+ const newConfig = global.configWithModifiedWeb(createAppConfig(), {
1014
+ 'response-headers': {
1015
+ '/*.html': {
1016
+ 'cache-control': 'max-age=3600, s-maxage=7200',
1017
+ testHeader: 'generic-header'
1018
+ }
1019
+ }
1020
+ })
1021
+
1022
+ await rs.uploadFile(global.fakeAuthToken, filePath, 'fakeprefix', newConfig, fakeDistRoot)
769
1023
 
770
- // check header application per file
771
- files.forEach(f => {
772
- const fileName = f.replace(path.join(fakeDistRoot, path.sep), '')
773
- const response = rs.getResponseHeadersForFile(f, fakeDistRoot, newConfig)
774
- const expected = expectedValMap[fileName]
775
- expect(response).toStrictEqual(expected)
1024
+ const callArgs = global.fetch.mock.calls[0]
1025
+ const body = JSON.parse(callArgs[1].body)
1026
+ // cache-control from response-headers should override the computed cacheControl
1027
+ expect(body.file.cacheControl).toBe('max-age=3600, s-maxage=7200')
1028
+ // adp-cache-control should be removed from customHeaders
1029
+ expect(body.file.customHeaders).not.toHaveProperty('adp-cache-control')
1030
+ expect(body.file.customHeaders).toMatchObject({
1031
+ 'adp-testHeader': 'generic-header'
1032
+ })
776
1033
  })
1034
+
1035
+ test('does not set customHeaders when responseHeaders is empty', async () => {
1036
+ global.addFakeFiles(vol, 'fakeDir', { 'index.js': 'fake content' })
1037
+ global.fetch.mockResolvedValue(mockResponse({ success: true }))
1038
+ const rs = new RemoteStorage()
1039
+ const appConfig = createAppConfig()
1040
+ delete appConfig.web // No web.response-headers
1041
+
1042
+ await rs.uploadFile(global.fakeAuthToken, 'fakeDir/index.js', 'fakeprefix', appConfig, 'fakeDir')
1043
+
1044
+ const callArgs = global.fetch.mock.calls[0]
1045
+ const body = JSON.parse(callArgs[1].body)
1046
+ // When no response-headers config, getResponseHeadersForFile returns undefined
1047
+ // which becomes {} after the ?? {} fallback
1048
+ expect(body.file.customHeaders).toEqual({})
1049
+ })
1050
+
1051
+ test('sets cacheControl even when responseHeaders is empty', async () => {
1052
+ global.addFakeFiles(vol, 'fakeDir', { 'index.html': 'fake content' })
1053
+ global.fetch.mockResolvedValue(mockResponse({ success: true }))
1054
+ const rs = new RemoteStorage()
1055
+ const appConfig = createAppConfig()
1056
+ delete appConfig.web // No web.response-headers
1057
+
1058
+ await rs.uploadFile(global.fakeAuthToken, 'fakeDir/index.html', 'fakeprefix', appConfig, 'fakeDir')
1059
+
1060
+ const callArgs = global.fetch.mock.calls[0]
1061
+ const body = JSON.parse(callArgs[1].body)
1062
+ expect(body.file.cacheControl).toBe('s-maxage=60, max-age=60')
1063
+ expect(body.file.customHeaders).toEqual({})
1064
+ })
1065
+
1066
+ test('uploadFile does not set customHeaders when responseHeaders is empty', async () => {
1067
+ global.addFakeFiles(vol, 'fakeDir', { 'index.js': 'fake content' })
1068
+ global.fetch.mockResolvedValue(mockResponse({ success: true }))
1069
+ const rs = new RemoteStorage()
1070
+ const appConfig = createAppConfig()
1071
+ delete appConfig.web // No web.response-headers
1072
+
1073
+ await rs.uploadFile(global.fakeAuthToken, 'fakeDir/index.js', 'fakeprefix', appConfig, 'fakeDir')
1074
+
1075
+ const callArgs = global.fetch.mock.calls[0]
1076
+ const body = JSON.parse(callArgs[1].body)
1077
+ expect(body.file.customHeaders).toEqual({})
1078
+ expect(body.file.name).toBe('fakeprefix/index.js')
1079
+ expect(body.file.contentType).toBe('application/javascript')
1080
+ })
1081
+ })
1082
+ })
1083
+
1084
+ describe('RemoteStorage BYO S3', () => {
1085
+ const byoCreds = () => ({ ...global.fakeBYOCredentials })
1086
+
1087
+ beforeEach(() => {
1088
+ global.cleanFs(vol)
1089
+ global.fetch.mockReset()
1090
+ S3.mockClear()
1091
+ ProxyAgent.mockClear()
1092
+ NodeHttpHandler.mockClear()
1093
+ mockS3Instance.listObjectsV2.mockReset()
1094
+ mockS3Instance.deleteObjects.mockReset()
1095
+ mockS3Instance.putObject.mockReset()
777
1096
  })
778
1097
 
779
- test('get response header for file extension based path rules', async () => {
780
- // setup files and paths
781
- const rs = new RemoteStorage(global.fakeTVMResponse)
782
- const folderPath1 = 'css' + path.sep + 'ui.css'
783
- const folderPath2 = 'scripts' + path.sep + 'test.js'
784
- const folderPath3 = 'images' + path.sep + 'image.png'
785
- await global.addFakeFiles(vol, 'fakeDir', ['index.html', 'test.js', folderPath1, folderPath2, folderPath3])
786
- const files = await rs.walkDir('fakeDir')
787
- const fakeDistRoot = path.parse(files[0]).dir
788
-
789
- // create a config of rules for spcefic files which overrider folder rules
790
- const newConfig = global.configWithModifiedWeb(global.fakeConfig, {
791
- 'response-headers': {
792
- '/*': {
793
- testHeader: 'generic-header'
794
- },
795
- '/*.css': {
796
- testHeader: 'all-css-files-header'
797
- },
798
- '/*.js': {
799
- testHeader: 'all-js-files-header'
800
- },
801
- '/*.png': {
802
- testHeader: 'all-png-files-header'
1098
+ describe('constructor', () => {
1099
+ test('null creds uses deploy-service mode', () => {
1100
+ const rs = new RemoteStorage(null)
1101
+ expect(rs.s3).toBeUndefined()
1102
+ expect(S3).not.toHaveBeenCalled()
1103
+ })
1104
+
1105
+ test('throws on invalid creds', () => {
1106
+ expect(() => new RemoteStorage({ accessKeyId: 'fake' })).toThrow()
1107
+ expect(S3).not.toHaveBeenCalled()
1108
+ })
1109
+
1110
+ test('creates S3 client with default region and proxy agent', () => {
1111
+ const rs = new RemoteStorage(byoCreds())
1112
+
1113
+ expect(rs.bucket).toBe(global.fakeS3Bucket)
1114
+ expect(rs.s3).toBe(mockS3Instance)
1115
+ expect(ProxyAgent).toHaveBeenCalledTimes(1)
1116
+ const agent = ProxyAgent.mock.instances[0]
1117
+ expect(NodeHttpHandler).toHaveBeenCalledWith({ httpAgent: agent, httpsAgent: agent })
1118
+ expect(S3).toHaveBeenCalledWith(expect.objectContaining({
1119
+ region: 'us-east-1',
1120
+ credentials: {
1121
+ accessKeyId: 'fake',
1122
+ secretAccessKey: 'fake',
1123
+ sessionToken: undefined,
1124
+ expiration: undefined
803
1125
  }
804
- }
1126
+ }))
805
1127
  })
806
1128
 
807
- // set the expectation
808
- const expectedValMap = {
809
- 'index.html': { 'adp-testHeader': 'generic-header' },
810
- 'test.js': { 'adp-testHeader': 'all-js-files-header' }
811
- }
812
- expectedValMap[folderPath1] = { 'adp-testHeader': 'all-css-files-header' }
813
- expectedValMap[folderPath2] = { 'adp-testHeader': 'all-js-files-header' }
814
- expectedValMap[folderPath3] = { 'adp-testHeader': 'all-png-files-header' }
1129
+ test('uses region, sessionToken and expiration from creds', () => {
1130
+ // eslint-disable-next-line no-new
1131
+ new RemoteStorage({ ...global.fakeTVMResponse, region: 'eu-west-1' })
815
1132
 
816
- // check header application per file
817
- files.forEach(f => {
818
- const fileName = f.replace(path.join(fakeDistRoot, path.sep), '')
819
- const response = rs.getResponseHeadersForFile(f, fakeDistRoot, newConfig)
820
- const expected = expectedValMap[fileName]
821
- expect(response).toStrictEqual(expected)
1133
+ expect(S3).toHaveBeenCalledWith(expect.objectContaining({
1134
+ region: 'eu-west-1',
1135
+ credentials: {
1136
+ accessKeyId: 'fake',
1137
+ secretAccessKey: 'fake',
1138
+ sessionToken: 'fake',
1139
+ expiration: new Date('1970-01-01T00:00:00.000Z')
1140
+ }
1141
+ }))
822
1142
  })
823
1143
  })
824
1144
 
825
- test('get response header with invalid header name', async () => {
826
- const rs = new RemoteStorage(global.fakeTVMResponse)
827
- const newConfig = global.configWithModifiedWeb(global.fakeConfig, {
828
- 'response-headers': {
829
- '/*': {
830
- 無効な名前: 'generic-header'
831
- }
832
- }
1145
+ describe('folderExists', () => {
1146
+ test('returns true if objects exist under prefix', async () => {
1147
+ mockS3Instance.listObjectsV2.mockResolvedValue({ KeyCount: 2 })
1148
+ const rs = new RemoteStorage(byoCreds())
1149
+
1150
+ await expect(rs.folderExists(undefined, 'fakeprefix/', createAppConfig())).resolves.toBe(true)
1151
+ expect(mockS3Instance.listObjectsV2).toHaveBeenCalledWith({ Bucket: global.fakeS3Bucket, Prefix: 'fakeprefix/' })
1152
+ expect(global.fetch).not.toHaveBeenCalled()
833
1153
  })
834
1154
 
835
- const fakeDistRoot = '/fake/web-prod/'
836
- expect(() => rs.getResponseHeadersForFile(fakeDistRoot + 'index.html', fakeDistRoot, newConfig)).toThrowWithMessageContaining(
837
- '[WebLib:ERROR_INVALID_HEADER_NAME] `無効な名前` is not a valid response header name')
1155
+ test('returns false if no objects under prefix', async () => {
1156
+ mockS3Instance.listObjectsV2.mockResolvedValue({ KeyCount: 0 })
1157
+ const rs = new RemoteStorage(byoCreds())
1158
+
1159
+ await expect(rs.folderExists(undefined, 'fakeprefix/', createAppConfig())).resolves.toBe(false)
1160
+ })
838
1161
  })
839
1162
 
840
- test('get response header with invalid header value', async () => {
841
- const rs = new RemoteStorage(global.fakeTVMResponse)
842
- const newConfig = global.configWithModifiedWeb(global.fakeConfig, {
843
- 'response-headers': {
844
- '/*': {
845
- testHeader: '無効な値'
846
- }
847
- }
1163
+ describe('emptyFolder', () => {
1164
+ test('does nothing if there are no objects', async () => {
1165
+ mockS3Instance.listObjectsV2.mockResolvedValue({ KeyCount: 0 })
1166
+ const rs = new RemoteStorage(byoCreds())
1167
+
1168
+ await expect(rs.emptyFolder(undefined, 'fakeprefix/', createAppConfig())).resolves.toBeUndefined()
1169
+ expect(mockS3Instance.deleteObjects).not.toHaveBeenCalled()
848
1170
  })
849
1171
 
850
- const fakeDistRoot = '/fake/web-prod/'
851
- expect(() => rs.getResponseHeadersForFile(fakeDistRoot + 'index.html', fakeDistRoot, newConfig)).toThrowWithMessageContaining(
852
- '[WebLib:ERROR_INVALID_HEADER_VALUE] `無効な値` is not a valid response header value for `testHeader`')
1172
+ test('deletes all listed objects', async () => {
1173
+ mockS3Instance.listObjectsV2.mockResolvedValue({
1174
+ KeyCount: 2,
1175
+ Contents: [{ Key: 'fakeprefix/a.js' }, { Key: 'fakeprefix/b.js' }],
1176
+ IsTruncated: false
1177
+ })
1178
+ const rs = new RemoteStorage(byoCreds())
1179
+
1180
+ await expect(rs.emptyFolder(undefined, 'fakeprefix/', createAppConfig())).resolves.toBeUndefined()
1181
+ expect(mockS3Instance.listObjectsV2).toHaveBeenCalledTimes(1)
1182
+ expect(mockS3Instance.deleteObjects).toHaveBeenCalledWith({
1183
+ Bucket: global.fakeS3Bucket,
1184
+ Delete: { Objects: [{ Key: 'fakeprefix/a.js' }, { Key: 'fakeprefix/b.js' }] }
1185
+ })
1186
+ })
1187
+
1188
+ test('recurses while the listing is truncated', async () => {
1189
+ mockS3Instance.listObjectsV2
1190
+ .mockResolvedValueOnce({ KeyCount: 1, Contents: [{ Key: 'fakeprefix/a.js' }], IsTruncated: true })
1191
+ .mockResolvedValueOnce({ KeyCount: 1, Contents: [{ Key: 'fakeprefix/b.js' }], IsTruncated: false })
1192
+ const rs = new RemoteStorage(byoCreds())
1193
+
1194
+ await rs.emptyFolder(undefined, 'fakeprefix/', createAppConfig())
1195
+
1196
+ expect(mockS3Instance.listObjectsV2).toHaveBeenCalledTimes(2)
1197
+ expect(mockS3Instance.deleteObjects).toHaveBeenCalledTimes(2)
1198
+ })
853
1199
  })
854
1200
 
855
- test('Metadata check for response headers', async () => {
856
- global.addFakeFiles(vol, 'fakeDir', { 'index.js': 'fake content' })
857
- const rs = new RemoteStorage(global.fakeTVMResponse)
858
- const files = await rs.walkDir('fakeDir')
859
- const fakeDistRoot = files[0].substring(0, files[0].indexOf('index.js'))
860
- const newConfig = global.configWithModifiedWeb(global.fakeConfig, {
861
- 'response-headers': {
862
- '/*': {
863
- testHeader: 'generic-header'
1201
+ describe('uploadFile', () => {
1202
+ test('puts object with key, body, content type, cache control and metadata', async () => {
1203
+ global.addFakeFiles(vol, 'fakeDir', { 'index.js': 'fake content' })
1204
+ mockS3Instance.putObject.mockResolvedValue({ ETag: 'etag' })
1205
+ const rs = new RemoteStorage(byoCreds())
1206
+
1207
+ const result = await rs.uploadFile(undefined, 'fakeDir/index.js', 'fakeprefix', createAppConfig(), 'fakeDir')
1208
+
1209
+ expect(result).toEqual({ ETag: 'etag' })
1210
+ expect(mockS3Instance.putObject).toHaveBeenCalledWith({
1211
+ Bucket: global.fakeS3Bucket,
1212
+ Key: 'fakeprefix/index.js',
1213
+ Body: Buffer.from('fake content'),
1214
+ CacheControl: 's-maxage=60, max-age=604800',
1215
+ ContentType: 'application/javascript',
1216
+ Metadata: { 'adp-testHeader': 'foo' }
1217
+ })
1218
+ expect(global.fetch).not.toHaveBeenCalled()
1219
+ })
1220
+
1221
+ test('omits Metadata and CacheControl when there is nothing to set', async () => {
1222
+ global.addFakeFiles(vol, 'fakeDir', { 'index.js': 'fake content' })
1223
+ const rs = new RemoteStorage(byoCreds())
1224
+ const appConfig = createAppConfig({ app: {} })
1225
+ delete appConfig.web
1226
+
1227
+ await rs.uploadFile(undefined, 'fakeDir/index.js', 'fakeprefix', appConfig, 'fakeDir')
1228
+
1229
+ const params = mockS3Instance.putObject.mock.calls[0][0]
1230
+ expect(params).not.toHaveProperty('Metadata')
1231
+ expect(params).not.toHaveProperty('CacheControl')
1232
+ expect(params.ContentType).toBe('application/javascript')
1233
+ })
1234
+
1235
+ test('omits ContentType and CacheControl for unknown mime types', async () => {
1236
+ global.addFakeFiles(vol, 'fakeDir', { 'index.mst': 'fake content' })
1237
+ const rs = new RemoteStorage(byoCreds())
1238
+
1239
+ await rs.uploadFile(undefined, 'fakeDir/index.mst', 'fakeprefix', createAppConfig(), 'fakeDir')
1240
+
1241
+ const params = mockS3Instance.putObject.mock.calls[0][0]
1242
+ expect(params).not.toHaveProperty('ContentType')
1243
+ expect(params).not.toHaveProperty('CacheControl')
1244
+ expect(params.Key).toBe('fakeprefix/index.mst')
1245
+ })
1246
+
1247
+ test('adp-cache-control response header overrides CacheControl and is not sent as Metadata', async () => {
1248
+ global.addFakeFiles(vol, 'fakeDir', { 'index.js': 'fake content' })
1249
+ const rs = new RemoteStorage(byoCreds())
1250
+ const appConfig = global.configWithModifiedWeb(createAppConfig(), {
1251
+ 'response-headers': {
1252
+ '/*': {
1253
+ 'cache-control': 'max-age=3600',
1254
+ testHeader: 'foo'
1255
+ }
864
1256
  }
865
- }
1257
+ })
1258
+
1259
+ await rs.uploadFile(undefined, 'fakeDir/index.js', 'fakeprefix', appConfig, 'fakeDir')
1260
+
1261
+ const params = mockS3Instance.putObject.mock.calls[0][0]
1262
+ expect(params.CacheControl).toBe('max-age=3600')
1263
+ expect(params.Metadata).toEqual({ 'adp-testHeader': 'foo' })
866
1264
  })
867
- // const fakeConfig = {}
868
- await rs.uploadFile('fakeDir/index.js', 'fakeprefix', newConfig, fakeDistRoot)
869
- const body = Buffer.from('fake content', 'utf8')
870
- const expected = {
871
- Bucket: 'fake-bucket',
872
- Key: 'fakeprefix/index.js',
873
- Body: body,
874
- ContentType: 'application/javascript',
875
- Metadata: {
876
- 'adp-testHeader': 'generic-header'
877
- }
878
- }
879
- expect(mockS3.putObject).toHaveBeenCalledWith(expect.objectContaining(expected))
880
- })
881
1265
 
882
- test('Cache control override from response headers', async () => {
883
- global.addFakeFiles(vol, 'fakeDir', { 'index.html': 'fake content' })
884
- const rs = new RemoteStorage(global.fakeTVMResponse)
885
- const files = await rs.walkDir('fakeDir')
886
- const fakeDistRoot = path.parse(files[0]).dir
887
- const filePath = files[0] // Use absolute path from walkDir
888
- const newConfig = global.configWithModifiedWeb(global.fakeConfig, {
889
- 'response-headers': {
890
- '/*.html': {
891
- 'cache-control': 'max-age=3600, s-maxage=7200',
892
- testHeader: 'generic-header'
1266
+ test('adp-cache-control as only response header leaves Metadata unset', async () => {
1267
+ global.addFakeFiles(vol, 'fakeDir', { 'index.js': 'fake content' })
1268
+ const rs = new RemoteStorage(byoCreds())
1269
+ const appConfig = global.configWithModifiedWeb(createAppConfig(), {
1270
+ 'response-headers': {
1271
+ '/*': { 'cache-control': 'max-age=3600' }
893
1272
  }
894
- }
1273
+ })
1274
+
1275
+ await rs.uploadFile(undefined, 'fakeDir/index.js', 'fakeprefix', appConfig, 'fakeDir')
1276
+
1277
+ const params = mockS3Instance.putObject.mock.calls[0][0]
1278
+ expect(params.CacheControl).toBe('max-age=3600')
1279
+ expect(params).not.toHaveProperty('Metadata')
895
1280
  })
896
- await rs.uploadFile(filePath, 'fakeprefix', newConfig, fakeDistRoot)
897
- const body = Buffer.from('fake content', 'utf8')
898
- const expected = {
899
- Bucket: 'fake-bucket',
900
- Key: 'fakeprefix/index.html',
901
- Body: body,
902
- ContentType: 'text/html',
903
- CacheControl: 'max-age=3600, s-maxage=7200',
904
- Metadata: {
905
- 'adp-testHeader': 'generic-header'
906
- }
907
- }
908
- expect(mockS3.putObject).toHaveBeenCalledWith(expect.objectContaining(expected))
909
- // Verify that adp-cache-control was removed from metadata
910
- const putObjectCall = mockS3.putObject.mock.calls[0][0]
911
- expect(putObjectCall.Metadata).not.toHaveProperty('adp-cache-control')
912
1281
  })
913
1282
 
914
- test('uploadFile does not set Metadata when responseHeaders is empty', async () => {
915
- global.addFakeFiles(vol, 'fakeDir', { 'index.js': 'fake content' })
916
- const rs = new RemoteStorage(global.fakeTVMResponse)
917
- const fakeConfig = {
918
- app: global.fakeConfig.app
919
- // No web.response-headers
920
- }
921
- await rs.uploadFile('fakeDir/index.js', 'fakeprefix', fakeConfig, 'fakeDir')
922
- const body = Buffer.from('fake content', 'utf8')
923
- const putObjectCall = mockS3.putObject.mock.calls[0][0]
924
- expect(putObjectCall).not.toHaveProperty('Metadata')
925
- expect(putObjectCall).toMatchObject({
926
- Bucket: 'fake-bucket',
927
- Key: 'fakeprefix/index.js',
928
- Body: body,
929
- ContentType: 'application/javascript'
930
- })
1283
+ test('uploadDir uploads each file to S3', async () => {
1284
+ global.addFakeFiles(vol, 'fakeDir', ['index.js', 'css/index.css'])
1285
+ const rs = new RemoteStorage(byoCreds())
1286
+
1287
+ await rs.uploadDir(undefined, 'fakeDir', 'fakeprefix', createAppConfig())
1288
+
1289
+ const keys = mockS3Instance.putObject.mock.calls.map(c => c[0].Key).sort()
1290
+ expect(keys).toEqual(['fakeprefix/css/index.css', 'fakeprefix/index.js'])
1291
+ })
1292
+ })
1293
+
1294
+ describe('RemoteStorage environment URL selection', () => {
1295
+ const aioLibEnv = require('@adobe/aio-lib-env')
1296
+ const originalDeploymentServiceUrl = process.env.AIO_DEPLOYMENT_SERVICE_URL
1297
+
1298
+ beforeEach(() => {
1299
+ global.fetch.mockReset()
1300
+ delete process.env.AIO_DEPLOYMENT_SERVICE_URL
931
1301
  })
932
1302
 
933
- test('uploadFile sets CacheControl even when responseHeaders is empty', async () => {
934
- global.addFakeFiles(vol, 'fakeDir', { 'index.html': 'fake content' })
935
- const rs = new RemoteStorage(global.fakeTVMResponse)
936
- const fakeConfig = {
937
- app: global.fakeConfig.app
938
- // No web.response-headers
1303
+ afterEach(() => {
1304
+ if (originalDeploymentServiceUrl === undefined) {
1305
+ delete process.env.AIO_DEPLOYMENT_SERVICE_URL
1306
+ } else {
1307
+ process.env.AIO_DEPLOYMENT_SERVICE_URL = originalDeploymentServiceUrl
939
1308
  }
940
- await rs.uploadFile('fakeDir/index.html', 'fakeprefix', fakeConfig, 'fakeDir')
941
- const body = Buffer.from('fake content', 'utf8')
942
- const putObjectCall = mockS3.putObject.mock.calls[0][0]
943
- expect(putObjectCall).not.toHaveProperty('Metadata')
944
- expect(putObjectCall).toMatchObject({
945
- Bucket: 'fake-bucket',
946
- Key: 'fakeprefix/index.html',
947
- Body: body,
948
- ContentType: 'text/html',
949
- CacheControl: 's-maxage=60, max-age=60'
950
- })
1309
+ jest.restoreAllMocks()
1310
+ })
1311
+
1312
+ test('uses AIO_DEPLOYMENT_SERVICE_URL when set', async () => {
1313
+ process.env.AIO_DEPLOYMENT_SERVICE_URL = 'http://localhost:3000'
1314
+ global.fetch.mockResolvedValue(mockResponse([]))
1315
+ const rs = new RemoteStorage()
1316
+
1317
+ await rs.folderExists(global.fakeAuthToken, 'fakeprefix', createAppConfig())
1318
+
1319
+ expect(global.fetch).toHaveBeenCalledWith(
1320
+ expect.stringContaining('http://localhost:3000'),
1321
+ expect.any(Object)
1322
+ )
1323
+ })
1324
+
1325
+ test('uses stage url when in stage environment', async () => {
1326
+ jest.spyOn(aioLibEnv, 'getCliEnv').mockReturnValue('stage')
1327
+ global.fetch.mockResolvedValue(mockResponse([]))
1328
+ const rs = new RemoteStorage()
1329
+
1330
+ await rs.folderExists(global.fakeAuthToken, 'fakeprefix', createAppConfig())
1331
+
1332
+ expect(global.fetch).toHaveBeenCalledWith(
1333
+ expect.stringContaining('https://deploy-service.stg.app-builder.corp.adp.adobe.io'),
1334
+ expect.any(Object)
1335
+ )
1336
+ })
1337
+
1338
+ test('uses prod url when in prod environment', async () => {
1339
+ jest.spyOn(aioLibEnv, 'getCliEnv').mockReturnValue(aioLibEnv.PROD_ENV)
1340
+ global.fetch.mockResolvedValue(mockResponse([]))
1341
+ const rs = new RemoteStorage()
1342
+
1343
+ await rs.folderExists(global.fakeAuthToken, 'fakeprefix', createAppConfig())
1344
+
1345
+ expect(global.fetch).toHaveBeenCalledWith(
1346
+ expect.stringContaining('https://deploy-service.app-builder.adp.adobe.io'),
1347
+ expect.any(Object)
1348
+ )
951
1349
  })
952
1350
  })