@fgv/ts-http-storage 5.1.0-19 → 5.1.0-20

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 (106) hide show
  1. package/package.json +5 -5
  2. package/.rush/temp/6a0c03e499df249785541cca1357e0ac8db48297.tar.log +0 -61
  3. package/.rush/temp/chunked-rush-logs/ts-http-storage.build.chunks.jsonl +0 -9
  4. package/.rush/temp/operation/build/all.log +0 -9
  5. package/.rush/temp/operation/build/log-chunks.jsonl +0 -9
  6. package/.rush/temp/operation/build/state.json +0 -3
  7. package/.rush/temp/shrinkwrap-deps.json +0 -656
  8. package/config/api-extractor.json +0 -36
  9. package/config/rig.json +0 -10
  10. package/config/typedoc.json +0 -7
  11. package/docs/README.md +0 -298
  12. package/docs/classes/FsStorageProvider.createDirectory.md +0 -20
  13. package/docs/classes/FsStorageProvider.deleteFile.md +0 -20
  14. package/docs/classes/FsStorageProvider.getChildren.md +0 -20
  15. package/docs/classes/FsStorageProvider.getFile.md +0 -20
  16. package/docs/classes/FsStorageProvider.getItem.md +0 -20
  17. package/docs/classes/FsStorageProvider.md +0 -147
  18. package/docs/classes/FsStorageProvider.saveFile.md +0 -22
  19. package/docs/classes/FsStorageProvider.sync.md +0 -13
  20. package/docs/classes/FsStorageProviderFactory.forNamespace.md +0 -20
  21. package/docs/classes/FsStorageProviderFactory.md +0 -69
  22. package/docs/classes/HttpStorageService.createDirectory.md +0 -20
  23. package/docs/classes/HttpStorageService.deleteFile.md +0 -20
  24. package/docs/classes/HttpStorageService.getChildren.md +0 -20
  25. package/docs/classes/HttpStorageService.getFile.md +0 -20
  26. package/docs/classes/HttpStorageService.getItem.md +0 -20
  27. package/docs/classes/HttpStorageService.md +0 -145
  28. package/docs/classes/HttpStorageService.saveFile.md +0 -20
  29. package/docs/classes/HttpStorageService.sync.md +0 -20
  30. package/docs/functions/createStorageRoutes.md +0 -11
  31. package/docs/functions/normalizeRequestPath.md +0 -11
  32. package/docs/functions/sanitizeNamespace.md +0 -11
  33. package/docs/interfaces/ICreateStorageRoutesOptions.logger.md +0 -9
  34. package/docs/interfaces/ICreateStorageRoutesOptions.md +0 -61
  35. package/docs/interfaces/ICreateStorageRoutesOptions.providers.md +0 -9
  36. package/docs/interfaces/IFsStorageProviderFactoryOptions.md +0 -44
  37. package/docs/interfaces/IFsStorageProviderFactoryOptions.rootPath.md +0 -9
  38. package/docs/interfaces/IHttpStorageProvider.createDirectory.md +0 -20
  39. package/docs/interfaces/IHttpStorageProvider.deleteFile.md +0 -20
  40. package/docs/interfaces/IHttpStorageProvider.getChildren.md +0 -20
  41. package/docs/interfaces/IHttpStorageProvider.getFile.md +0 -20
  42. package/docs/interfaces/IHttpStorageProvider.getItem.md +0 -20
  43. package/docs/interfaces/IHttpStorageProvider.md +0 -115
  44. package/docs/interfaces/IHttpStorageProvider.saveFile.md +0 -22
  45. package/docs/interfaces/IHttpStorageProvider.sync.md +0 -13
  46. package/docs/interfaces/IHttpStorageProviderFactory.forNamespace.md +0 -20
  47. package/docs/interfaces/IHttpStorageProviderFactory.md +0 -36
  48. package/docs/interfaces/IStorageFileResponse.contentType.md +0 -9
  49. package/docs/interfaces/IStorageFileResponse.contents.md +0 -9
  50. package/docs/interfaces/IStorageFileResponse.md +0 -78
  51. package/docs/interfaces/IStorageFileResponse.path.md +0 -9
  52. package/docs/interfaces/IStoragePathRequest.md +0 -61
  53. package/docs/interfaces/IStoragePathRequest.namespace.md +0 -9
  54. package/docs/interfaces/IStoragePathRequest.path.md +0 -9
  55. package/docs/interfaces/IStorageSyncRequest.md +0 -44
  56. package/docs/interfaces/IStorageSyncRequest.namespace.md +0 -9
  57. package/docs/interfaces/IStorageSyncResponse.md +0 -44
  58. package/docs/interfaces/IStorageSyncResponse.synced.md +0 -9
  59. package/docs/interfaces/IStorageTreeChildrenResponse.children.md +0 -9
  60. package/docs/interfaces/IStorageTreeChildrenResponse.md +0 -61
  61. package/docs/interfaces/IStorageTreeChildrenResponse.path.md +0 -9
  62. package/docs/interfaces/IStorageTreeItem.md +0 -78
  63. package/docs/interfaces/IStorageTreeItem.name.md +0 -9
  64. package/docs/interfaces/IStorageTreeItem.path.md +0 -9
  65. package/docs/interfaces/IStorageTreeItem.type.md +0 -9
  66. package/docs/interfaces/IStorageWriteFileRequest.contentType.md +0 -9
  67. package/docs/interfaces/IStorageWriteFileRequest.contents.md +0 -9
  68. package/docs/interfaces/IStorageWriteFileRequest.md +0 -97
  69. package/docs/type-aliases/StorageItemType.md +0 -11
  70. package/docs/type-aliases/StorageNamespace.md +0 -11
  71. package/docs/variables/storageFileResponse.md +0 -9
  72. package/docs/variables/storagePathRequest.md +0 -9
  73. package/docs/variables/storageSyncRequest.md +0 -9
  74. package/docs/variables/storageTreeChildrenResponse.md +0 -9
  75. package/docs/variables/storageTreeItem.md +0 -9
  76. package/docs/variables/storageWriteFileRequest.md +0 -9
  77. package/etc/ts-http-storage.api.md +0 -184
  78. package/lib/test/unit/storage/fsProvider.test.d.ts +0 -2
  79. package/lib/test/unit/storage/fsProvider.test.d.ts.map +0 -1
  80. package/lib/test/unit/storage/fsProvider.test.js +0 -106
  81. package/lib/test/unit/storage/fsProvider.test.js.map +0 -1
  82. package/lib/test/unit/storage/routes.test.d.ts +0 -2
  83. package/lib/test/unit/storage/routes.test.d.ts.map +0 -1
  84. package/lib/test/unit/storage/routes.test.js +0 -124
  85. package/lib/test/unit/storage/routes.test.js.map +0 -1
  86. package/lib/test/unit/storage/service.test.d.ts +0 -2
  87. package/lib/test/unit/storage/service.test.d.ts.map +0 -1
  88. package/lib/test/unit/storage/service.test.js +0 -67
  89. package/lib/test/unit/storage/service.test.js.map +0 -1
  90. package/rush-logs/ts-http-storage.build.cache.log +0 -3
  91. package/rush-logs/ts-http-storage.build.log +0 -9
  92. package/src/index.ts +0 -28
  93. package/src/packlets/storage/converters.ts +0 -100
  94. package/src/packlets/storage/fsProvider.ts +0 -263
  95. package/src/packlets/storage/index.ts +0 -33
  96. package/src/packlets/storage/model.ts +0 -113
  97. package/src/packlets/storage/provider.ts +0 -33
  98. package/src/packlets/storage/routes.ts +0 -215
  99. package/src/packlets/storage/service.ts +0 -114
  100. package/src/test/unit/storage/fsProvider.test.ts +0 -129
  101. package/src/test/unit/storage/routes.test.ts +0 -165
  102. package/src/test/unit/storage/service.test.ts +0 -95
  103. package/temp/build/typescript/ts_l9Fw4VUO.json +0 -1
  104. package/temp/ts-http-storage.api.json +0 -3103
  105. package/temp/ts-http-storage.api.md +0 -184
  106. package/tsconfig.json +0 -7
@@ -1,33 +0,0 @@
1
- /*
2
- * Copyright (c) 2026 Erik Fortune
3
- *
4
- * Permission is hereby granted, free of charge, to any person obtaining a copy
5
- * of this software and associated documentation files (the "Software"), to deal
6
- * in the Software without restriction, including without limitation the rights
7
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- * copies of the Software, and to permit persons to whom the Software is
9
- * furnished to do so, subject to the following conditions:
10
- *
11
- * The above copyright notice and this permission notice shall be included in all
12
- * copies or substantial portions of the Software.
13
- *
14
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
- * SOFTWARE.
21
- */
22
-
23
- import type { Result } from '@fgv/ts-utils';
24
-
25
- import type { IHttpStorageProvider, StorageNamespace } from './model';
26
-
27
- /**
28
- * Factory for creating namespace-scoped storage providers.
29
- * @public
30
- */
31
- export interface IHttpStorageProviderFactory {
32
- forNamespace(namespace?: StorageNamespace): Result<IHttpStorageProvider>;
33
- }
@@ -1,215 +0,0 @@
1
- /*
2
- * Copyright (c) 2026 Erik Fortune
3
- *
4
- * Permission is hereby granted, free of charge, to any person obtaining a copy
5
- * of this software and associated documentation files (the "Software"), to deal
6
- * in the Software without restriction, including without limitation the rights
7
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- * copies of the Software, and to permit persons to whom the Software is
9
- * furnished to do so, subject to the following conditions:
10
- *
11
- * The above copyright notice and this permission notice shall be included in all
12
- * copies or substantial portions of the Software.
13
- *
14
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
- * SOFTWARE.
21
- */
22
-
23
- import { Hono } from 'hono';
24
-
25
- import type { Logging } from '@fgv/ts-utils';
26
-
27
- import {
28
- storagePathRequest,
29
- storageSyncRequest,
30
- storageWriteFileRequest,
31
- storageTreeChildrenResponse,
32
- storageTreeItem,
33
- storageFileResponse
34
- } from './converters';
35
- import { HttpStorageService } from './service';
36
- import type { IStoragePathRequest, IStorageSyncRequest } from './model';
37
- import type { IHttpStorageProviderFactory } from './provider';
38
-
39
- /**
40
- * Options for creating storage routes.
41
- * @public
42
- */
43
- export interface ICreateStorageRoutesOptions {
44
- readonly providers: IHttpStorageProviderFactory;
45
- readonly logger?: Logging.ILogger;
46
- }
47
-
48
- function parsePathQuery(path: string | undefined, namespace: string | undefined): IStoragePathRequest {
49
- return {
50
- path: path ?? '/',
51
- namespace
52
- };
53
- }
54
-
55
- function parseSyncRequest(namespace: string | undefined): IStorageSyncRequest {
56
- return { namespace };
57
- }
58
-
59
- /**
60
- * Builds storage routes for a Hono app.
61
- * @public
62
- */
63
- export function createStorageRoutes(options: ICreateStorageRoutesOptions): Hono {
64
- const routes = new Hono();
65
- const service = new HttpStorageService(options.providers);
66
-
67
- routes.get('/health', async (c) => {
68
- const namespace = c.req.query('namespace');
69
- const syncResult = await service.sync(parseSyncRequest(namespace));
70
- if (syncResult.isFailure()) {
71
- return c.json({ error: syncResult.message }, 500);
72
- }
73
- return c.json({ status: 'ok', namespace: namespace ?? 'default' });
74
- });
75
-
76
- routes.get('/tree/item', async (c) => {
77
- const parsed = storagePathRequest.convert(parsePathQuery(c.req.query('path'), c.req.query('namespace')));
78
- if (parsed.isFailure()) {
79
- return c.json({ error: `invalid request: ${parsed.message}` }, 400);
80
- }
81
-
82
- const result = await service.getItem(parsed.value);
83
- if (result.isFailure()) {
84
- return c.json({ error: result.message }, 404);
85
- }
86
-
87
- const converted = storageTreeItem.convert(result.value);
88
- if (converted.isFailure()) {
89
- return c.json({ error: `invalid response: ${converted.message}` }, 500);
90
- }
91
- return c.json(converted.value);
92
- });
93
-
94
- routes.get('/tree/children', async (c) => {
95
- const parsed = storagePathRequest.convert(parsePathQuery(c.req.query('path'), c.req.query('namespace')));
96
- if (parsed.isFailure()) {
97
- return c.json({ error: `invalid request: ${parsed.message}` }, 400);
98
- }
99
-
100
- const result = await service.getChildren(parsed.value);
101
- if (result.isFailure()) {
102
- return c.json({ error: result.message }, 404);
103
- }
104
-
105
- const converted = storageTreeChildrenResponse.convert(result.value);
106
- if (converted.isFailure()) {
107
- return c.json({ error: `invalid response: ${converted.message}` }, 500);
108
- }
109
- return c.json(converted.value);
110
- });
111
-
112
- routes.get('/file', async (c) => {
113
- const parsed = storagePathRequest.convert(parsePathQuery(c.req.query('path'), c.req.query('namespace')));
114
- if (parsed.isFailure()) {
115
- return c.json({ error: `invalid request: ${parsed.message}` }, 400);
116
- }
117
-
118
- const result = await service.getFile(parsed.value);
119
- if (result.isFailure()) {
120
- return c.json({ error: result.message }, 404);
121
- }
122
-
123
- const converted = storageFileResponse.convert(result.value);
124
- if (converted.isFailure()) {
125
- return c.json({ error: `invalid response: ${converted.message}` }, 500);
126
- }
127
- return c.json(converted.value);
128
- });
129
-
130
- routes.put('/file', async (c) => {
131
- const raw = await c.req.json().catch(() => undefined);
132
- if (raw === undefined) {
133
- return c.json({ error: 'invalid JSON body' }, 400);
134
- }
135
-
136
- const parsed = storageWriteFileRequest.convert(raw);
137
- if (parsed.isFailure()) {
138
- return c.json({ error: `invalid request: ${parsed.message}` }, 400);
139
- }
140
-
141
- const result = await service.saveFile(parsed.value);
142
- if (result.isFailure()) {
143
- return c.json({ error: result.message }, 400);
144
- }
145
-
146
- const converted = storageFileResponse.convert(result.value);
147
- if (converted.isFailure()) {
148
- return c.json({ error: `invalid response: ${converted.message}` }, 500);
149
- }
150
-
151
- options.logger?.detail(`storage write: ${parsed.value.namespace ?? 'default'}:${parsed.value.path}`);
152
- return c.json(converted.value);
153
- });
154
-
155
- routes.delete('/file', async (c) => {
156
- const parsed = storagePathRequest.convert(parsePathQuery(c.req.query('path'), c.req.query('namespace')));
157
- if (parsed.isFailure()) {
158
- return c.json({ error: `invalid request: ${parsed.message}` }, 400);
159
- }
160
-
161
- const result = await service.deleteFile(parsed.value);
162
- if (result.isFailure()) {
163
- return c.json({ error: result.message }, 404);
164
- }
165
-
166
- options.logger?.detail(`storage delete: ${parsed.value.namespace ?? 'default'}:${parsed.value.path}`);
167
- return c.json({ deleted: result.value });
168
- });
169
-
170
- routes.post('/directories', async (c) => {
171
- const raw = await c.req.json().catch(() => undefined);
172
- if (raw === undefined) {
173
- return c.json({ error: 'invalid JSON body' }, 400);
174
- }
175
-
176
- const parsed = storagePathRequest.convert(raw);
177
- if (parsed.isFailure()) {
178
- return c.json({ error: `invalid request: ${parsed.message}` }, 400);
179
- }
180
-
181
- const result = await service.createDirectory(parsed.value);
182
- if (result.isFailure()) {
183
- return c.json({ error: result.message }, 400);
184
- }
185
-
186
- const converted = storageTreeItem.convert(result.value);
187
- if (converted.isFailure()) {
188
- return c.json({ error: `invalid response: ${converted.message}` }, 500);
189
- }
190
- return c.json(converted.value);
191
- });
192
-
193
- routes.post('/sync', async (c) => {
194
- const raw = await c.req.json().catch(() => ({}));
195
- const parsed = storageSyncRequest.convert(raw);
196
- if (parsed.isFailure()) {
197
- return c.json({ error: `invalid request: ${parsed.message}` }, 400);
198
- }
199
-
200
- const result = await service.sync(parsed.value);
201
- if (result.isFailure()) {
202
- return c.json({ error: result.message }, 500);
203
- }
204
-
205
- return c.json(result.value);
206
- });
207
-
208
- routes.onError((err, c) => {
209
- const message = err instanceof Error ? err.message : String(err);
210
- options.logger?.error(`storage route error: ${message}`);
211
- return c.json({ error: message }, 500);
212
- });
213
-
214
- return routes;
215
- }
@@ -1,114 +0,0 @@
1
- /*
2
- * Copyright (c) 2026 Erik Fortune
3
- *
4
- * Permission is hereby granted, free of charge, to any person obtaining a copy
5
- * of this software and associated documentation files (the "Software"), to deal
6
- * in the Software without restriction, including without limitation the rights
7
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- * copies of the Software, and to permit persons to whom the Software is
9
- * furnished to do so, subject to the following conditions:
10
- *
11
- * The above copyright notice and this permission notice shall be included in all
12
- * copies or substantial portions of the Software.
13
- *
14
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
- * SOFTWARE.
21
- */
22
-
23
- import { fail, type Result, succeed } from '@fgv/ts-utils';
24
-
25
- import type {
26
- IHttpStorageProvider,
27
- IStorageFileResponse,
28
- IStoragePathRequest,
29
- IStorageSyncRequest,
30
- IStorageSyncResponse,
31
- IStorageTreeChildrenResponse,
32
- IStorageTreeItem,
33
- IStorageWriteFileRequest
34
- } from './model';
35
- import type { IHttpStorageProviderFactory } from './provider';
36
-
37
- /**
38
- * Service layer for storage API operations.
39
- * @public
40
- */
41
- export class HttpStorageService {
42
- private readonly _providers: IHttpStorageProviderFactory;
43
-
44
- public constructor(providers: IHttpStorageProviderFactory) {
45
- this._providers = providers;
46
- }
47
-
48
- public async getItem(request: IStoragePathRequest): Promise<Result<IStorageTreeItem>> {
49
- const providerResult = this._getProvider(request.namespace);
50
- if (providerResult.isFailure()) {
51
- return fail(providerResult.message);
52
- }
53
- return providerResult.value.getItem(request.path);
54
- }
55
-
56
- public async getChildren(request: IStoragePathRequest): Promise<Result<IStorageTreeChildrenResponse>> {
57
- const providerResult = this._getProvider(request.namespace);
58
- if (providerResult.isFailure()) {
59
- return fail(providerResult.message);
60
- }
61
- const childrenResult = await providerResult.value.getChildren(request.path);
62
- if (childrenResult.isFailure()) {
63
- return fail(childrenResult.message);
64
- }
65
- return succeed({
66
- path: request.path,
67
- children: childrenResult.value
68
- });
69
- }
70
-
71
- public async getFile(request: IStoragePathRequest): Promise<Result<IStorageFileResponse>> {
72
- const providerResult = this._getProvider(request.namespace);
73
- if (providerResult.isFailure()) {
74
- return fail(providerResult.message);
75
- }
76
- return providerResult.value.getFile(request.path);
77
- }
78
-
79
- public async saveFile(request: IStorageWriteFileRequest): Promise<Result<IStorageFileResponse>> {
80
- const providerResult = this._getProvider(request.namespace);
81
- if (providerResult.isFailure()) {
82
- return fail(providerResult.message);
83
- }
84
- return providerResult.value.saveFile(request.path, request.contents, request.contentType);
85
- }
86
-
87
- public async deleteFile(request: IStoragePathRequest): Promise<Result<boolean>> {
88
- const providerResult = this._getProvider(request.namespace);
89
- if (providerResult.isFailure()) {
90
- return fail(providerResult.message);
91
- }
92
- return providerResult.value.deleteFile(request.path);
93
- }
94
-
95
- public async createDirectory(request: IStoragePathRequest): Promise<Result<IStorageTreeItem>> {
96
- const providerResult = this._getProvider(request.namespace);
97
- if (providerResult.isFailure()) {
98
- return fail(providerResult.message);
99
- }
100
- return providerResult.value.createDirectory(request.path);
101
- }
102
-
103
- public async sync(request: IStorageSyncRequest): Promise<Result<IStorageSyncResponse>> {
104
- const providerResult = this._getProvider(request.namespace);
105
- if (providerResult.isFailure()) {
106
- return fail(providerResult.message);
107
- }
108
- return providerResult.value.sync();
109
- }
110
-
111
- private _getProvider(namespace?: string): Result<IHttpStorageProvider> {
112
- return this._providers.forNamespace(namespace).withErrorFormat((msg) => `provider: ${msg}`);
113
- }
114
- }
@@ -1,129 +0,0 @@
1
- import fs from 'fs';
2
- import os from 'os';
3
- import path from 'path';
4
-
5
- import { FsStorageProvider, FsStorageProviderFactory, sanitizeNamespace } from '../../../packlets/storage';
6
-
7
- describe('sanitizeNamespace', () => {
8
- test('returns default when namespace is empty', () => {
9
- expect(sanitizeNamespace(undefined).isSuccess()).toBe(true);
10
- expect(sanitizeNamespace(' ').isSuccess()).toBe(true);
11
- expect(sanitizeNamespace(' ').orThrow()).toBe('default');
12
- });
13
-
14
- test('accepts valid namespace values', () => {
15
- const result = sanitizeNamespace('team.alpha_01-dev');
16
- expect(result.isSuccess()).toBe(true);
17
- expect(result.orThrow()).toBe('team.alpha_01-dev');
18
- });
19
-
20
- test('rejects invalid namespace characters', () => {
21
- const result = sanitizeNamespace('../escape');
22
- expect(result.isFailure()).toBe(true);
23
- expect(result.message).toContain('only [a-zA-Z0-9._-] allowed');
24
- });
25
- });
26
-
27
- describe('FsStorageProvider', () => {
28
- let rootPath: string;
29
-
30
- beforeEach(() => {
31
- rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'ts-http-storage-test-'));
32
- });
33
-
34
- afterEach(() => {
35
- fs.rmSync(rootPath, { recursive: true, force: true });
36
- });
37
-
38
- test('saves and loads files', async () => {
39
- const provider = new FsStorageProvider(rootPath);
40
-
41
- const saveResult = await provider.saveFile('/data/example.txt', 'hello');
42
- expect(saveResult.isSuccess()).toBe(true);
43
-
44
- const fileResult = await provider.getFile('/data/example.txt');
45
- expect(fileResult.isSuccess()).toBe(true);
46
- expect(fileResult.orThrow()).toEqual({
47
- path: '/data/example.txt',
48
- contents: 'hello'
49
- });
50
- });
51
-
52
- test('lists children in a directory', async () => {
53
- const provider = new FsStorageProvider(rootPath);
54
- await provider.saveFile('/data/one.txt', 'one');
55
- await provider.saveFile('/data/two.txt', 'two');
56
-
57
- const childrenResult = await provider.getChildren('/data');
58
- expect(childrenResult.isSuccess()).toBe(true);
59
-
60
- const childNames = childrenResult
61
- .orThrow()
62
- .map((child) => child.name)
63
- .sort();
64
- expect(childNames).toEqual(['one.txt', 'two.txt']);
65
- });
66
-
67
- test('normalizes traversal-like request paths under storage root', async () => {
68
- const provider = new FsStorageProvider(rootPath);
69
-
70
- const result = await provider.getItem('../../etc/passwd');
71
- expect(result.isFailure()).toBe(true);
72
- expect(result.message).toContain('ENOENT');
73
- expect(result.message).toContain(path.join(rootPath, 'etc/passwd'));
74
- });
75
-
76
- test('deletes an existing file', async () => {
77
- const provider = new FsStorageProvider(rootPath);
78
- await provider.saveFile('/data/delete-me.txt', 'temporary');
79
-
80
- const deleteResult = await provider.deleteFile('/data/delete-me.txt');
81
- expect(deleteResult.isSuccess()).toBe(true);
82
- expect(deleteResult.orThrow()).toBe(true);
83
-
84
- const readResult = await provider.getFile('/data/delete-me.txt');
85
- expect(readResult.isFailure()).toBe(true);
86
- });
87
- });
88
-
89
- describe('FsStorageProviderFactory', () => {
90
- let rootPath: string;
91
-
92
- beforeEach(() => {
93
- rootPath = fs.mkdtempSync(path.join(os.tmpdir(), 'ts-http-storage-factory-'));
94
- });
95
-
96
- afterEach(() => {
97
- fs.rmSync(rootPath, { recursive: true, force: true });
98
- });
99
-
100
- test('creates namespace-scoped providers', async () => {
101
- const factory = new FsStorageProviderFactory({ rootPath });
102
-
103
- const providerResult = factory.forNamespace('team-a');
104
- expect(providerResult.isSuccess()).toBe(true);
105
-
106
- const provider = providerResult.orThrow();
107
- const saveResult = await provider.saveFile('/notes.txt', 'namespaced');
108
- expect(saveResult.isSuccess()).toBe(true);
109
-
110
- const expectedPath = path.join(rootPath, 'team-a', 'notes.txt');
111
- expect(fs.existsSync(expectedPath)).toBe(true);
112
- });
113
-
114
- test('fails for invalid namespace', () => {
115
- const factory = new FsStorageProviderFactory({ rootPath });
116
- const result = factory.forNamespace('bad/name');
117
-
118
- expect(result.isFailure()).toBe(true);
119
- expect(result.message).toContain('only [a-zA-Z0-9._-] allowed');
120
- });
121
-
122
- test('rejects namespace that resolves outside root', () => {
123
- const factory = new FsStorageProviderFactory({ rootPath });
124
- const result = factory.forNamespace('..');
125
-
126
- expect(result.isFailure()).toBe(true);
127
- expect(result.message).toContain('outside root');
128
- });
129
- });
@@ -1,165 +0,0 @@
1
- import { fail, type Result, succeed } from '@fgv/ts-utils';
2
-
3
- import {
4
- createStorageRoutes,
5
- type IHttpStorageProvider,
6
- type IHttpStorageProviderFactory,
7
- type IStorageFileResponse,
8
- type IStorageSyncResponse,
9
- type IStorageTreeItem
10
- } from '../../../packlets/storage';
11
-
12
- class InMemoryProvider implements IHttpStorageProvider {
13
- private readonly _files: Map<string, string> = new Map();
14
-
15
- private _basename(path: string): string {
16
- const parts = path.split('/');
17
- return parts[parts.length - 1] ?? '';
18
- }
19
-
20
- public async getItem(path: string): Promise<Result<IStorageTreeItem>> {
21
- if (this._files.has(path)) {
22
- return succeed({ path, name: this._basename(path), type: 'file' as const });
23
- }
24
- return fail(`${path}: not found`);
25
- }
26
-
27
- public async getChildren(path: string): Promise<Result<ReadonlyArray<IStorageTreeItem>>> {
28
- const children: IStorageTreeItem[] = [];
29
- for (const filePath of this._files.keys()) {
30
- if (filePath.startsWith(`${path}/`)) {
31
- const name = filePath.substring(path.length + 1);
32
- if (!name.includes('/')) {
33
- children.push({ path: filePath, name, type: 'file' });
34
- }
35
- }
36
- }
37
- return succeed(children);
38
- }
39
-
40
- public async getFile(path: string): Promise<Result<IStorageFileResponse>> {
41
- const contents = this._files.get(path);
42
- if (contents === undefined) {
43
- return fail(`${path}: not found`);
44
- }
45
- return succeed({ path, contents });
46
- }
47
-
48
- public async saveFile(path: string, contents: string): Promise<Result<IStorageFileResponse>> {
49
- this._files.set(path, contents);
50
- return succeed({ path, contents });
51
- }
52
-
53
- public async deleteFile(path: string): Promise<Result<boolean>> {
54
- if (!this._files.has(path)) {
55
- return fail(`${path}: not found`);
56
- }
57
- this._files.delete(path);
58
- return succeed(true);
59
- }
60
-
61
- public async createDirectory(path: string): Promise<Result<IStorageTreeItem>> {
62
- return succeed({ path, name: this._basename(path), type: 'directory' });
63
- }
64
-
65
- public async sync(): Promise<Result<IStorageSyncResponse>> {
66
- return succeed({ synced: this._files.size });
67
- }
68
- }
69
-
70
- class TestProviderFactory implements IHttpStorageProviderFactory {
71
- private readonly _provider: InMemoryProvider;
72
-
73
- public constructor(provider: InMemoryProvider) {
74
- this._provider = provider;
75
- }
76
-
77
- public forNamespace(): Result<IHttpStorageProvider> {
78
- return succeed(this._provider);
79
- }
80
- }
81
-
82
- describe('createStorageRoutes', () => {
83
- test('writes then reads a file', async () => {
84
- const provider = new InMemoryProvider();
85
- const app = createStorageRoutes({ providers: new TestProviderFactory(provider) });
86
-
87
- const putResponse = await app.request(
88
- new Request('http://localhost/file', {
89
- method: 'PUT',
90
- headers: { 'Content-Type': 'application/json' },
91
- body: JSON.stringify({ path: '/data/demo.txt', contents: 'hello' })
92
- })
93
- );
94
- expect(putResponse.status).toBe(200);
95
-
96
- const getResponse = await app.request(new Request('http://localhost/file?path=/data/demo.txt'));
97
- expect(getResponse.status).toBe(200);
98
- await expect(getResponse.json()).resolves.toEqual({ path: '/data/demo.txt', contents: 'hello' });
99
- });
100
-
101
- test('returns 400 for invalid put body', async () => {
102
- const provider = new InMemoryProvider();
103
- const app = createStorageRoutes({ providers: new TestProviderFactory(provider) });
104
-
105
- const response = await app.request(
106
- new Request('http://localhost/file', {
107
- method: 'PUT',
108
- headers: { 'Content-Type': 'application/json' },
109
- body: '{ not-json'
110
- })
111
- );
112
-
113
- expect(response.status).toBe(400);
114
- const payload = (await response.json()) as { error?: string };
115
- expect(payload.error).toContain('invalid JSON body');
116
- });
117
-
118
- test('returns sync payload from provider', async () => {
119
- const provider = new InMemoryProvider();
120
- const app = createStorageRoutes({ providers: new TestProviderFactory(provider) });
121
-
122
- await app.request(
123
- new Request('http://localhost/file', {
124
- method: 'PUT',
125
- headers: { 'Content-Type': 'application/json' },
126
- body: JSON.stringify({ path: '/alpha.txt', contents: 'a' })
127
- })
128
- );
129
-
130
- const response = await app.request(
131
- new Request('http://localhost/sync', {
132
- method: 'POST',
133
- headers: { 'Content-Type': 'application/json' },
134
- body: JSON.stringify({})
135
- })
136
- );
137
-
138
- expect(response.status).toBe(200);
139
- await expect(response.json()).resolves.toEqual({ synced: 1 });
140
- });
141
-
142
- test('deletes a file through DELETE /file', async () => {
143
- const provider = new InMemoryProvider();
144
- const app = createStorageRoutes({ providers: new TestProviderFactory(provider) });
145
-
146
- await app.request(
147
- new Request('http://localhost/file', {
148
- method: 'PUT',
149
- headers: { 'Content-Type': 'application/json' },
150
- body: JSON.stringify({ path: '/data/remove-me.txt', contents: 'gone soon' })
151
- })
152
- );
153
-
154
- const deleteResponse = await app.request(
155
- new Request('http://localhost/file?path=/data/remove-me.txt', {
156
- method: 'DELETE'
157
- })
158
- );
159
- expect(deleteResponse.status).toBe(200);
160
- await expect(deleteResponse.json()).resolves.toEqual({ deleted: true });
161
-
162
- const getResponse = await app.request(new Request('http://localhost/file?path=/data/remove-me.txt'));
163
- expect(getResponse.status).toBe(404);
164
- });
165
- });