@fgv/ts-res 5.0.0-16 → 5.0.0-18

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 (32) hide show
  1. package/dist/ts-res.d.ts +461 -0
  2. package/lib/index.d.ts +2 -1
  3. package/lib/index.js +3 -1
  4. package/lib/packlets/zip-archive/convert.d.ts +52 -0
  5. package/lib/packlets/zip-archive/convert.js +104 -0
  6. package/lib/packlets/zip-archive/index.d.ts +23 -0
  7. package/lib/packlets/zip-archive/index.js +95 -0
  8. package/lib/packlets/zip-archive/json.d.ts +64 -0
  9. package/lib/packlets/zip-archive/json.js +24 -0
  10. package/lib/packlets/zip-archive/types.d.ts +98 -0
  11. package/lib/packlets/zip-archive/types.js +39 -0
  12. package/lib/packlets/zip-archive/zipArchiveCreator.d.ts +35 -0
  13. package/lib/packlets/zip-archive/zipArchiveCreator.js +194 -0
  14. package/lib/packlets/zip-archive/zipArchiveFormat.d.ts +70 -0
  15. package/lib/packlets/zip-archive/zipArchiveFormat.js +184 -0
  16. package/lib/packlets/zip-archive/zipArchiveLoader.d.ts +70 -0
  17. package/lib/packlets/zip-archive/zipArchiveLoader.js +285 -0
  18. package/lib/test/unit/zip-archive/convert.test.d.ts +2 -0
  19. package/lib/test/unit/zip-archive/json.test.d.ts +2 -0
  20. package/lib/test/unit/zip-archive/zipArchiveCreator.test.d.ts +2 -0
  21. package/lib/test/unit/zip-archive/zipArchiveFormat.test.d.ts +2 -0
  22. package/lib/test/unit/zip-archive/zipArchiveIdempotency.test.d.ts +2 -0
  23. package/lib/test/unit/zip-archive/zipArchiveLoader.test.d.ts +2 -0
  24. package/package.json +8 -7
  25. package/src/index.ts +3 -1
  26. package/src/packlets/zip-archive/convert.ts +121 -0
  27. package/src/packlets/zip-archive/index.ts +76 -0
  28. package/src/packlets/zip-archive/json.ts +91 -0
  29. package/src/packlets/zip-archive/types.ts +140 -0
  30. package/src/packlets/zip-archive/zipArchiveCreator.ts +229 -0
  31. package/src/packlets/zip-archive/zipArchiveFormat.ts +158 -0
  32. package/src/packlets/zip-archive/zipArchiveLoader.ts +370 -0
@@ -0,0 +1,370 @@
1
+ /*
2
+ * Copyright (c) 2025 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 { Result, succeed, fail, FileTree } from '@fgv/ts-utils';
24
+ import { ZipFileTree } from '@fgv/ts-extras';
25
+ import type {
26
+ IZipArchiveLoadOptions,
27
+ IZipArchiveLoadResult,
28
+ ZipArchiveProgressCallback,
29
+ IImportedFile,
30
+ IImportedDirectory
31
+ } from './types';
32
+ import { Model as ConfigModel } from '../config';
33
+ import * as Json from './json';
34
+ import { parseZipArchiveManifest, parseZipArchiveConfiguration, isZipFile } from './zipArchiveFormat';
35
+
36
+ /**
37
+ * ZIP archive loader extending ts-extras foundation
38
+ * @public
39
+ */
40
+ export class ZipArchiveLoader {
41
+ /**
42
+ * Load ZIP archive from File object (Browser)
43
+ * @param file - File object from file input
44
+ * @param options - Loading options
45
+ * @param onProgress - Optional progress callback
46
+ * @returns Result containing loaded archive data
47
+ */
48
+ public async loadFromFile(
49
+ file: File,
50
+ options: IZipArchiveLoadOptions = {},
51
+ onProgress?: ZipArchiveProgressCallback
52
+ ): Promise<Result<IZipArchiveLoadResult>> {
53
+ onProgress?.('reading-file', 0, `Reading file: ${file.name}`);
54
+
55
+ if (!isZipFile(file.name)) {
56
+ return fail(`File ${file.name} is not a ZIP file`);
57
+ }
58
+
59
+ try {
60
+ const buffer = await file.arrayBuffer();
61
+ onProgress?.('reading-file', 100, 'File read complete');
62
+
63
+ return await this.loadFromBuffer(buffer, options, onProgress);
64
+ /* c8 ignore next 3 - defense in depth against internal error */
65
+ } catch (error) {
66
+ return fail(`Failed to read file: ${error instanceof Error ? error.message : String(error)}`);
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Load ZIP archive from ArrayBuffer (Universal)
72
+ * @param buffer - ZIP data buffer
73
+ * @param options - Loading options
74
+ * @param onProgress - Optional progress callback
75
+ * @returns Result containing loaded archive data
76
+ */
77
+ public async loadFromBuffer(
78
+ buffer: ArrayBuffer,
79
+ options: IZipArchiveLoadOptions = {},
80
+ onProgress?: ZipArchiveProgressCallback
81
+ ): Promise<Result<IZipArchiveLoadResult>> {
82
+ onProgress?.('parsing-zip', 0, 'Parsing ZIP archive');
83
+
84
+ const zipAccessorsResult = ZipFileTree.ZipFileTreeAccessors.fromBuffer(buffer);
85
+ if (zipAccessorsResult.isFailure()) {
86
+ return fail(`Failed to parse ZIP: ${zipAccessorsResult.message}`);
87
+ }
88
+
89
+ const zipAccessors = zipAccessorsResult.value;
90
+ onProgress?.('parsing-zip', 100, 'ZIP archive parsed');
91
+
92
+ // Load manifest
93
+ onProgress?.('loading-manifest', 0, 'Loading manifest');
94
+ const manifestResult = this._loadManifestFromAccessors(zipAccessors);
95
+ if (manifestResult.isFailure()) {
96
+ return fail(manifestResult.message);
97
+ }
98
+ const manifest = manifestResult.value;
99
+ onProgress?.('loading-manifest', 100, 'Manifest loaded');
100
+
101
+ // Load configuration
102
+ onProgress?.('loading-config', 0, 'Loading configuration');
103
+ const configResult = this._loadConfigurationFromAccessors(zipAccessors, manifest, options);
104
+ if (configResult.isFailure()) {
105
+ return fail(configResult.message);
106
+ }
107
+ const config = configResult.value;
108
+ onProgress?.('loading-config', 100, 'Configuration loaded');
109
+
110
+ // Extract files and directory structure
111
+ onProgress?.('extracting-files', 0, 'Extracting files');
112
+ const filesResult = await this._extractFilesFromAccessors(zipAccessors, onProgress);
113
+ /* c8 ignore next 3 - defense in depth against internal error */
114
+ if (filesResult.isFailure()) {
115
+ return fail(filesResult.message);
116
+ }
117
+
118
+ const { files, directory } = filesResult.value;
119
+ onProgress?.('extracting-files', 100, `Extracted ${files.length} files`);
120
+
121
+ onProgress?.('extracting-files', 100, 'ZIP loading complete');
122
+
123
+ return succeed({
124
+ manifest,
125
+ config,
126
+ files,
127
+ directory
128
+ });
129
+ }
130
+
131
+ /**
132
+ * Load manifest from ZIP using ZipFileTreeAccessors
133
+ * @param zipAccessors - ZIP file tree accessors
134
+ * @returns Result containing parsed manifest
135
+ */
136
+ private _loadManifestFromAccessors(
137
+ zipAccessors: ZipFileTree.ZipFileTreeAccessors
138
+ ): Result<Json.IZipArchiveManifest | undefined> {
139
+ const manifestResult = zipAccessors.getFileContents('manifest.json');
140
+ if (manifestResult.isFailure()) {
141
+ // Manifest is optional - return success with undefined
142
+ return succeed(undefined);
143
+ }
144
+
145
+ const parseResult = parseZipArchiveManifest(manifestResult.value);
146
+ if (parseResult.isFailure()) {
147
+ return fail(`Failed to parse manifest.json: ${parseResult.message}`);
148
+ }
149
+
150
+ return succeed(parseResult.value);
151
+ }
152
+
153
+ /**
154
+ * Load configuration from ZIP using ZipFileTreeAccessors
155
+ * @param zipAccessors - ZIP file tree accessors
156
+ * @param manifest - Parsed manifest (may be undefined)
157
+ * @param options - Loading options
158
+ * @returns Result containing parsed configuration
159
+ */
160
+ private _loadConfigurationFromAccessors(
161
+ zipAccessors: ZipFileTree.ZipFileTreeAccessors,
162
+ manifest: Json.IZipArchiveManifest | undefined,
163
+ options: IZipArchiveLoadOptions
164
+ ): Result<ConfigModel.ISystemConfiguration | undefined> {
165
+ // Check if manifest specifies a config file
166
+ const manifestSpecifiesConfig = manifest?.config !== undefined;
167
+
168
+ if (!manifestSpecifiesConfig) {
169
+ // If no config specified in manifest, config is optional
170
+ return succeed(undefined);
171
+ }
172
+
173
+ // Get the config path from the manifest
174
+ const configPath = manifest!.config!.archivePath;
175
+ return zipAccessors
176
+ .getFileContents(configPath)
177
+ .withErrorFormat(
178
+ () => `Manifest specifies config file at '${configPath}' but it was not found in archive`
179
+ )
180
+ .onSuccess((configContent) => parseZipArchiveConfiguration(configContent))
181
+ .withErrorFormat((e) => `Failed to parse config file '${configPath}': ${e}`);
182
+ }
183
+
184
+ /**
185
+ * Extract files and directory structure from ZIP
186
+ * @param zipAccessors - ZIP file tree accessors
187
+ * @param onProgress - Optional progress callback
188
+ * @returns Result containing files and directory structure
189
+ */
190
+ private async _extractFilesFromAccessors(
191
+ zipAccessors: ZipFileTree.ZipFileTreeAccessors,
192
+ onProgress?: ZipArchiveProgressCallback
193
+ ): Promise<Result<{ files: IImportedFile[]; directory: IImportedDirectory | undefined }>> {
194
+ try {
195
+ const files: IImportedFile[] = [];
196
+ const directories = new Map<string, IImportedDirectory>();
197
+
198
+ // Get all children from root
199
+ const rootChildrenResult = zipAccessors.getChildren('/');
200
+ /* c8 ignore next 3 - defense in depth against internal error */
201
+ if (rootChildrenResult.isFailure()) {
202
+ return fail(`Failed to read ZIP contents: ${rootChildrenResult.message}`);
203
+ }
204
+
205
+ // Process all items recursively
206
+ await this._processFileTreeItems(
207
+ zipAccessors,
208
+ '/',
209
+ rootChildrenResult.value,
210
+ files,
211
+ directories,
212
+ onProgress
213
+ );
214
+
215
+ // Build directory structure
216
+ const directory = this._buildDirectoryStructure(files, directories);
217
+
218
+ return succeed({ files, directory });
219
+ /* c8 ignore next 3 - defense in depth against internal error */
220
+ } catch (error) {
221
+ return fail(`Failed to extract files: ${error instanceof Error ? error.message : String(error)}`);
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Recursively process file tree items
227
+ * @param zipAccessors - ZIP file tree accessors
228
+ * @param currentPath - Current directory path
229
+ * @param items - Items to process
230
+ * @param files - Files collection
231
+ * @param directories - Directories collection
232
+ * @param onProgress - Optional progress callback
233
+ * @param processed - Processing counter
234
+ */
235
+ private async _processFileTreeItems(
236
+ zipAccessors: ZipFileTree.ZipFileTreeAccessors,
237
+ currentPath: string,
238
+ items: readonly FileTree.FileTreeItem[],
239
+ files: IImportedFile[],
240
+ directories: Map<string, IImportedDirectory>,
241
+ onProgress?: ZipArchiveProgressCallback,
242
+ processed: { count: number } = { count: 0 }
243
+ ): Promise<void> {
244
+ for (const item of items) {
245
+ /* c8 ignore next 1 - defense in depth */
246
+ const itemPath = item.absolutePath.startsWith('/') ? item.absolutePath.substring(1) : item.absolutePath;
247
+
248
+ if (item.type === 'directory') {
249
+ // Track directory
250
+ if (!directories.has(itemPath)) {
251
+ directories.set(itemPath, {
252
+ name: item.name,
253
+ files: [],
254
+ subdirectories: []
255
+ });
256
+ }
257
+
258
+ // Recursively process children
259
+ const childrenResult = zipAccessors.getChildren(item.absolutePath);
260
+ if (childrenResult.isSuccess()) {
261
+ await this._processFileTreeItems(
262
+ zipAccessors,
263
+ item.absolutePath,
264
+ childrenResult.value,
265
+ files,
266
+ directories,
267
+ onProgress,
268
+ processed
269
+ );
270
+ }
271
+ } else if (item.type === 'file') {
272
+ // Get file content
273
+ const contentResult = item.getRawContents();
274
+ const content = contentResult.orDefault('');
275
+
276
+ files.push({
277
+ name: item.name,
278
+ path: itemPath,
279
+ content,
280
+ type: this._getFileType(item.name)
281
+ });
282
+ }
283
+
284
+ processed.count++;
285
+ onProgress?.('extracting-files', 0, `Processing ${itemPath}`);
286
+ }
287
+ }
288
+
289
+ /**
290
+ * Build directory structure from files
291
+ * @param files - Extracted files
292
+ * @param directories - Directories map
293
+ * @returns Root directory structure or null
294
+ */
295
+ private _buildDirectoryStructure(
296
+ files: IImportedFile[],
297
+ directories: Map<string, IImportedDirectory>
298
+ ): IImportedDirectory | undefined {
299
+ /* c8 ignore next 3 - should never happen with fflate */
300
+ if (files.length === 0) {
301
+ return undefined;
302
+ }
303
+
304
+ const rootDir: IImportedDirectory = {
305
+ name: 'root',
306
+ files: [],
307
+ subdirectories: []
308
+ };
309
+
310
+ // Process files to build directory structure
311
+ for (const file of files) {
312
+ const pathParts = file.path.split('/').filter((part: string) => part.length > 0);
313
+
314
+ /* c8 ignore next 1 - defense in depth should never happen */
315
+ if (pathParts.length === 0) continue;
316
+
317
+ // Ensure all parent directories exist
318
+ let currentDir = rootDir;
319
+ for (let i = 0; i < pathParts.length - 1; i++) {
320
+ const dirName = pathParts[i];
321
+ let foundDir = currentDir.subdirectories.find((d) => d.name === dirName);
322
+
323
+ if (!foundDir) {
324
+ foundDir = {
325
+ name: dirName,
326
+ files: [],
327
+ subdirectories: []
328
+ };
329
+ currentDir.subdirectories.push(foundDir);
330
+ }
331
+
332
+ currentDir = foundDir;
333
+ }
334
+
335
+ // Add file to its parent directory
336
+ currentDir.files.push(file);
337
+ }
338
+
339
+ return rootDir;
340
+ }
341
+
342
+ /**
343
+ * Get file MIME type based on extension
344
+ * @param filename - Filename
345
+ * @returns MIME type
346
+ */
347
+ private _getFileType(filename: string): string {
348
+ const ext = filename.toLowerCase().split('.').pop();
349
+ /* c8 ignore next 20 - no need to test every one */
350
+ switch (ext) {
351
+ case 'json':
352
+ return 'application/json';
353
+ case 'yaml':
354
+ case 'yml':
355
+ return 'application/yaml';
356
+ case 'xml':
357
+ return 'application/xml';
358
+ case 'txt':
359
+ return 'text/plain';
360
+ case 'md':
361
+ return 'text/markdown';
362
+ case 'js':
363
+ return 'application/javascript';
364
+ case 'ts':
365
+ return 'application/typescript';
366
+ default:
367
+ return 'application/octet-stream';
368
+ }
369
+ }
370
+ }