@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,140 @@
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 { Model as ConfigModel } from '../config';
24
+ import * as Json from './json';
25
+ import { FileTree } from '@fgv/ts-utils';
26
+
27
+ /**
28
+ * Options for creating a ZIP archive buffer
29
+ * @public
30
+ */
31
+ export interface IZipArchivePathOptions {
32
+ /** File or directory path to include in the archive */
33
+ inputPath?: string;
34
+ /** Optional configuration file path */
35
+ configPath?: string;
36
+ }
37
+
38
+ /**
39
+ * Options for creating a ZIP archive buffer from a file tree
40
+ * @public
41
+ */
42
+ export interface IZipArchiveFileTreeOptions {
43
+ /** Input file or directory */
44
+ inputItem?: FileTree.FileTreeItem;
45
+ /** Optional configuration file */
46
+ configItem?: FileTree.IFileTreeFileItem;
47
+ }
48
+
49
+ /**
50
+ * Options for creating a ZIP archive buffer
51
+ * @public
52
+ */
53
+ export type ZipArchiveOptions = IZipArchivePathOptions | IZipArchiveFileTreeOptions;
54
+
55
+ /**
56
+ * Standardized ZIP archive manifest format (compatible with existing tools)
57
+ * @public
58
+ */
59
+ export type IZipArchiveManifest = Json.IZipArchiveManifest;
60
+
61
+ /**
62
+ * Result of ZIP archive buffer creation
63
+ * @public
64
+ */
65
+ export interface IZipArchiveResult {
66
+ /** Raw ZIP data buffer */
67
+ zipBuffer: Uint8Array;
68
+ /** Archive manifest with metadata */
69
+ manifest: IZipArchiveManifest;
70
+ /** Total ZIP size in bytes */
71
+ size: number;
72
+ }
73
+
74
+ /**
75
+ * Options for loading a ZIP archive
76
+ * @public
77
+ */
78
+ export interface IZipArchiveLoadOptions {
79
+ /** Validate manifest strictly */
80
+ strictManifestValidation?: boolean;
81
+ }
82
+
83
+ /**
84
+ * Result of ZIP archive loading
85
+ * @public
86
+ */
87
+ export interface IZipArchiveLoadResult {
88
+ /** Parsed archive manifest */
89
+ manifest: IZipArchiveManifest | undefined;
90
+ /** Loaded configuration */
91
+ config: ConfigModel.ISystemConfiguration | undefined;
92
+ /** All files extracted from the archive */
93
+ files: IImportedFile[];
94
+ /** Directory structure if available */
95
+ directory: IImportedDirectory | undefined;
96
+ }
97
+
98
+ /**
99
+ * Imported file representation
100
+ * @public
101
+ */
102
+ export type IImportedFile = Json.IImportedFile;
103
+
104
+ /**
105
+ * Imported directory structure
106
+ * @public
107
+ */
108
+ export type IImportedDirectory = Json.IImportedDirectory;
109
+
110
+ /**
111
+ * Progress callback for ZIP operations
112
+ * @public
113
+ */
114
+ export type ZipArchiveProgressCallback = (
115
+ stage:
116
+ | 'reading-file'
117
+ | 'parsing-zip'
118
+ | 'loading-manifest'
119
+ | 'loading-config'
120
+ | 'extracting-files'
121
+ | 'processing-resources'
122
+ | 'creating-zip',
123
+ progress: number, // 0-100
124
+ details: string
125
+ ) => void;
126
+
127
+ /**
128
+ * Constants for ZIP archive structure
129
+ * @public
130
+ */
131
+ export const ZipArchiveConstants = {
132
+ /** Manifest file name */
133
+ MANIFEST_FILE: 'manifest.json',
134
+ /** Configuration file name */
135
+ CONFIG_FILE: 'config.json',
136
+ /** Input files directory */
137
+ INPUT_DIR: 'input',
138
+ /** Configuration files directory */
139
+ CONFIG_DIR: 'config'
140
+ } as const;
@@ -0,0 +1,229 @@
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 { zipSync } from 'fflate';
24
+ import { Result, succeed, fail, FileTree } from '@fgv/ts-utils';
25
+ import type { IZipArchiveResult, ZipArchiveOptions, ZipArchiveProgressCallback } from './types';
26
+ import { normalizePath } from './zipArchiveFormat';
27
+ import * as Json from './json';
28
+
29
+ /**
30
+ * ZIP archive creator using fflate for universal compatibility
31
+ * @public
32
+ */
33
+ export class ZipArchiveCreator {
34
+ /**
35
+ * Create a ZIP archive buffer from a supplied buffer
36
+ * @param options - Input paths and configuration
37
+ * @param onProgress - Optional progress callback
38
+ * @returns Result containing ZIP buffer and manifest
39
+ */
40
+ public async createFromBuffer(
41
+ options: ZipArchiveOptions,
42
+ onProgress?: ZipArchiveProgressCallback
43
+ ): Promise<Result<IZipArchiveResult>> {
44
+ try {
45
+ onProgress?.('creating-zip', 0, 'Starting ZIP archive creation');
46
+
47
+ const files: Record<string, Uint8Array> = {};
48
+ const manifest: Json.IZipArchiveManifest = {
49
+ timestamp: new Date().toISOString()
50
+ };
51
+
52
+ const { value: inputItem, message: inputItemError } = this._getInputFileTreeItem(options);
53
+ if (inputItemError !== undefined) {
54
+ return fail(inputItemError);
55
+ }
56
+
57
+ if (inputItem !== undefined) {
58
+ onProgress?.('reading-file', 10, `Processing input: ${inputItem.absolutePath}`);
59
+
60
+ if (inputItem.type === 'directory') {
61
+ // Add entire directory recursively, preserving structure
62
+ const archivePath = `input/${inputItem.name}`;
63
+
64
+ const addDirResult = await this._addDirectoryTreeToZip(files, inputItem, archivePath, onProgress);
65
+ /* c8 ignore next 3 - defense in depth against internal error */
66
+ if (addDirResult.isFailure()) {
67
+ return fail(addDirResult.message);
68
+ }
69
+
70
+ manifest.input = {
71
+ type: 'directory',
72
+ originalPath: inputItem.absolutePath,
73
+ archivePath
74
+ };
75
+ } else if (inputItem.type === 'file') {
76
+ // Add single file
77
+ const archivePath = `input/${inputItem.name}`;
78
+
79
+ const addFileResult = await this._addFileTreeItemToZip(files, inputItem, archivePath);
80
+ /* c8 ignore next 3 - defense in depth against internal error */
81
+ if (addFileResult.isFailure()) {
82
+ return fail(addFileResult.message);
83
+ }
84
+
85
+ manifest.input = {
86
+ type: 'file',
87
+ originalPath: inputItem.absolutePath,
88
+ archivePath
89
+ };
90
+ }
91
+ }
92
+
93
+ const { value: configItem, message: configItemError } = this._getConfigFileTreeItem(options);
94
+ if (configItemError !== undefined) {
95
+ return fail(configItemError);
96
+ }
97
+
98
+ if (configItem !== undefined) {
99
+ onProgress?.('reading-file', 40, `Processing config: ${configItem.absolutePath}`);
100
+
101
+ const archivePath = `config/${configItem.name}`;
102
+
103
+ const addConfigResult = await this._addFileTreeItemToZip(files, configItem, archivePath);
104
+ /* c8 ignore next 3 - defense in depth against internal error */
105
+ if (addConfigResult.isFailure()) {
106
+ return fail(addConfigResult.message);
107
+ }
108
+
109
+ // Update manifest with config info
110
+ manifest.config = {
111
+ type: 'file',
112
+ originalPath: configItem.absolutePath,
113
+ archivePath
114
+ };
115
+ }
116
+
117
+ // Add manifest to ZIP
118
+ onProgress?.('creating-zip', 70, 'Adding manifest');
119
+ const manifestJson = JSON.stringify(manifest, null, 2);
120
+ files['manifest.json'] = new TextEncoder().encode(manifestJson);
121
+
122
+ // Create ZIP buffer using fflate
123
+ onProgress?.('creating-zip', 80, 'Compressing files');
124
+ const zipBuffer = zipSync(files, { level: 6 });
125
+
126
+ const result: IZipArchiveResult = {
127
+ zipBuffer,
128
+ manifest,
129
+ size: zipBuffer.length
130
+ };
131
+
132
+ onProgress?.('creating-zip', 100, 'ZIP archive buffer created');
133
+
134
+ return succeed(result);
135
+ /* c8 ignore next 3 - defense in depth against internal error */
136
+ } catch (error) {
137
+ return fail(`Failed to create ZIP archive: ${error instanceof Error ? error.message : String(error)}`);
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Add a single FileTree item to the ZIP archive
143
+ * @param files - ZIP files collection
144
+ * @param fileItem - FileTree file item to add
145
+ * @param archivePath - Path within the archive
146
+ * @returns Result indicating success or failure
147
+ */
148
+ private async _addFileTreeItemToZip(
149
+ files: Record<string, Uint8Array>,
150
+ fileItem: FileTree.IFileTreeFileItem,
151
+ archivePath: string
152
+ ): Promise<Result<void>> {
153
+ return fileItem.getRawContents().onSuccess((content) => {
154
+ const contentBuffer = new TextEncoder().encode(content);
155
+ files[normalizePath(archivePath)] = contentBuffer;
156
+ return succeed(undefined);
157
+ });
158
+ }
159
+
160
+ /**
161
+ * Add a directory recursively to the ZIP archive using FileTree
162
+ * @param files - ZIP files collection
163
+ * @param directoryItem - FileTree directory item to add
164
+ * @param archivePrefix - Prefix path within the archive
165
+ * @param onProgress - Optional progress callback
166
+ * @returns Result indicating success or failure
167
+ */
168
+ private async _addDirectoryTreeToZip(
169
+ files: Record<string, Uint8Array>,
170
+ directoryItem: FileTree.IFileTreeDirectoryItem,
171
+ archivePrefix: string,
172
+ onProgress?: ZipArchiveProgressCallback
173
+ ): Promise<Result<void>> {
174
+ const childrenResult = directoryItem.getChildren();
175
+ /* c8 ignore next 3 - defense in depth against internal error */
176
+ if (childrenResult.isFailure()) {
177
+ return fail(`Failed to read directory ${directoryItem.absolutePath}: ${childrenResult.message}`);
178
+ }
179
+
180
+ for (const child of childrenResult.value) {
181
+ const itemArchivePath = normalizePath(`${archivePrefix}/${child.name}`);
182
+
183
+ if (child.type === 'directory') {
184
+ // Recursively add subdirectory
185
+ const addDirResult = await this._addDirectoryTreeToZip(files, child, itemArchivePath, onProgress);
186
+ /* c8 ignore next 3 - defense in depth against internal error */
187
+ if (addDirResult.isFailure()) {
188
+ return fail(addDirResult.message);
189
+ }
190
+ } else if (child.type === 'file') {
191
+ // Add file
192
+ const addFileResult = await this._addFileTreeItemToZip(files, child, itemArchivePath);
193
+ /* c8 ignore next 3 - defense in depth against internal error */
194
+ if (addFileResult.isFailure()) {
195
+ return fail(addFileResult.message);
196
+ }
197
+ onProgress?.('reading-file', 0, `Added file: ${itemArchivePath}`);
198
+ }
199
+ }
200
+
201
+ return succeed(undefined);
202
+ }
203
+
204
+ private _getInputFileTreeItem(options: ZipArchiveOptions): Result<FileTree.FileTreeItem | undefined> {
205
+ if ('inputPath' in options && options.inputPath !== undefined) {
206
+ return FileTree.forFilesystem()
207
+ .withErrorFormat((msg) => `Failed to create file tree: ${msg}`)
208
+ .onSuccess((fileTree) =>
209
+ fileTree.getItem(options.inputPath!).withErrorFormat((msg) => `Failed to get item: ${msg}`)
210
+ );
211
+ } else if ('inputItem' in options) {
212
+ return succeed(options.inputItem);
213
+ }
214
+ return succeed(undefined);
215
+ }
216
+
217
+ private _getConfigFileTreeItem(options: ZipArchiveOptions): Result<FileTree.IFileTreeFileItem | undefined> {
218
+ if ('configPath' in options && options.configPath !== undefined) {
219
+ return FileTree.forFilesystem()
220
+ .withErrorFormat((msg) => `Failed to create file tree: ${msg}`)
221
+ .onSuccess((fileTree) =>
222
+ fileTree.getFile(options.configPath!).withErrorFormat((msg) => `Failed to get config file: ${msg}`)
223
+ );
224
+ } else if ('configItem' in options && options.configItem !== undefined) {
225
+ return succeed(options.configItem);
226
+ }
227
+ return succeed(undefined);
228
+ }
229
+ }
@@ -0,0 +1,158 @@
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, captureResult } from '@fgv/ts-utils';
24
+ import { Model as ConfigModel } from '../config';
25
+ import * as Json from './json';
26
+ import * as Convert from './convert';
27
+
28
+ /**
29
+ * Create a ZIP archive manifest object
30
+ * @param inputType - Type of input (file or directory)
31
+ * @param originalPath - Original file/directory path
32
+ * @param archivePath - Path within the archive
33
+ * @param configPath - Optional configuration file path
34
+ * @returns ZIP archive manifest
35
+ * @public
36
+ */
37
+ export function createZipArchiveManifest(
38
+ inputType: 'file' | 'directory',
39
+ originalPath: string,
40
+ archivePath: string,
41
+ configPath?: string
42
+ ): Json.IZipArchiveManifest {
43
+ const manifest: Json.IZipArchiveManifest = {
44
+ timestamp: new Date().toISOString(),
45
+ input: {
46
+ type: inputType,
47
+ originalPath,
48
+ archivePath
49
+ }
50
+ };
51
+
52
+ if (configPath) {
53
+ manifest.config = {
54
+ type: 'file',
55
+ originalPath: configPath,
56
+ archivePath: 'config.json'
57
+ };
58
+ }
59
+
60
+ return manifest;
61
+ }
62
+
63
+ /**
64
+ * Parse and validate a ZIP archive manifest
65
+ * @param manifestData - JSON string containing manifest data
66
+ * @returns Result containing validated manifest
67
+ * @public
68
+ */
69
+ export function parseZipArchiveManifest(manifestData: string): Result<Json.IZipArchiveManifest> {
70
+ return captureResult(() => {
71
+ const parsed = JSON.parse(manifestData);
72
+ return parsed;
73
+ })
74
+ .onSuccess((parsed) => Convert.zipArchiveManifest.validate(parsed))
75
+ .withErrorFormat((e) => `Failed to parse ZIP archive manifest: ${e}`);
76
+ }
77
+
78
+ /**
79
+ * Validate a ZIP archive manifest object
80
+ * @param manifest - Object to validate as manifest
81
+ * @returns Result containing validated manifest
82
+ * @public
83
+ */
84
+ export function validateZipArchiveManifest(manifest: unknown): Result<Json.IZipArchiveManifest> {
85
+ return Convert.zipArchiveManifest.validate(manifest);
86
+ }
87
+
88
+ /**
89
+ * Parse and validate configuration JSON
90
+ * @param configData - JSON string containing configuration
91
+ * @returns Result containing validated configuration
92
+ * @public
93
+ */
94
+ export function parseZipArchiveConfiguration(configData: string): Result<ConfigModel.ISystemConfiguration> {
95
+ return captureResult(() => {
96
+ const parsed = JSON.parse(configData);
97
+ return parsed;
98
+ })
99
+ .onSuccess((parsed) => Convert.systemConfiguration.validate(parsed))
100
+ .withErrorFormat((e) => `Failed to parse ZIP archive configuration: ${e}`);
101
+ }
102
+
103
+ /**
104
+ * Generate a timestamp-based filename for ZIP archives
105
+ * @param customName - Optional custom name prefix
106
+ * @returns Generated filename
107
+ * @public
108
+ */
109
+ export function generateZipArchiveFilename(customName?: string): string {
110
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-').replace('T', '_').slice(0, -5);
111
+ return customName ? `${customName}-${timestamp}.zip` : `ts-res-archive-${timestamp}.zip`;
112
+ }
113
+
114
+ /**
115
+ * Normalize path separators for cross-platform compatibility
116
+ * @param path - Path to normalize
117
+ * @returns Normalized path
118
+ * @public
119
+ */
120
+ export function normalizePath(path: string): string {
121
+ return path.replace(/\\/g, '/').replace(/\/+/g, '/');
122
+ }
123
+
124
+ /**
125
+ * Extract directory name from a file path
126
+ * @param path - File path
127
+ * @returns Directory name
128
+ * @public
129
+ */
130
+ export function getDirectoryName(path: string): string {
131
+ const normalized = normalizePath(path);
132
+ const parts = normalized.split('/');
133
+ return parts[parts.length - 1] || 'archive';
134
+ }
135
+
136
+ /**
137
+ * Create a safe filename by removing invalid characters
138
+ * @param filename - Original filename
139
+ * @returns Sanitized filename
140
+ * @public
141
+ */
142
+ export function sanitizeFilename(filename: string): string {
143
+ return filename
144
+ .replace(/[<>:"/\\|?*]/g, '_')
145
+ .replace(/\s+/g, '_')
146
+ .replace(/_+/g, '_')
147
+ .trim();
148
+ }
149
+
150
+ /**
151
+ * Validate ZIP file extension
152
+ * @param filename - Filename to validate
153
+ * @returns True if filename has .zip extension
154
+ * @public
155
+ */
156
+ export function isZipFile(filename: string): boolean {
157
+ return filename.toLowerCase().endsWith('.zip');
158
+ }