@fgv/ts-res 5.0.1-9 → 5.0.2-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.
Files changed (162) hide show
  1. package/dist/index.browser.js +53 -0
  2. package/dist/index.js +45 -0
  3. package/dist/packlets/bundle/bundleBuilder.js +130 -0
  4. package/dist/packlets/bundle/bundleLoader.js +101 -0
  5. package/dist/packlets/bundle/bundleNormalizer.js +138 -0
  6. package/dist/packlets/bundle/bundleUtils.js +113 -0
  7. package/dist/packlets/bundle/convert.js +75 -0
  8. package/dist/packlets/bundle/index.js +42 -0
  9. package/dist/packlets/bundle/model.js +23 -0
  10. package/dist/packlets/common/conditions.js +47 -0
  11. package/dist/packlets/common/convert.js +172 -0
  12. package/dist/packlets/common/helpers/conditions.js +66 -0
  13. package/dist/packlets/common/helpers/context.js +70 -0
  14. package/dist/packlets/common/helpers/index.js +26 -0
  15. package/dist/packlets/common/helpers/qualifierDefaultValues.js +66 -0
  16. package/dist/packlets/common/helpers/resources.js +93 -0
  17. package/dist/packlets/common/index.js +28 -0
  18. package/dist/packlets/common/resources.js +27 -0
  19. package/dist/packlets/common/validate/conditions.js +544 -0
  20. package/dist/packlets/common/validate/index.js +26 -0
  21. package/dist/packlets/common/validate/regularExpressions.js +84 -0
  22. package/dist/packlets/common/validate/resources.js +209 -0
  23. package/dist/packlets/conditions/condition.js +252 -0
  24. package/dist/packlets/conditions/conditionCollector.js +69 -0
  25. package/dist/packlets/conditions/conditionDecls.js +23 -0
  26. package/dist/packlets/conditions/conditionSet.js +247 -0
  27. package/dist/packlets/conditions/conditionSetCollector.js +89 -0
  28. package/dist/packlets/conditions/conditionSetDecls.js +23 -0
  29. package/dist/packlets/conditions/conditionToken.js +147 -0
  30. package/dist/packlets/conditions/convert/conditionSetDecls.js +51 -0
  31. package/dist/packlets/conditions/convert/decls.js +75 -0
  32. package/dist/packlets/conditions/convert/index.js +24 -0
  33. package/dist/packlets/conditions/index.js +31 -0
  34. package/dist/packlets/config/common.js +78 -0
  35. package/dist/packlets/config/configInitFactory.js +258 -0
  36. package/dist/packlets/config/convert.js +56 -0
  37. package/dist/packlets/config/index.browser.js +34 -0
  38. package/dist/packlets/config/index.js +28 -0
  39. package/dist/packlets/config/json.js +23 -0
  40. package/dist/packlets/config/predefined/default.js +138 -0
  41. package/dist/packlets/config/predefined/extended.js +190 -0
  42. package/dist/packlets/config/predefined/index.js +25 -0
  43. package/dist/packlets/config/systemConfiguration.js +147 -0
  44. package/dist/packlets/context/contextDecls.js +23 -0
  45. package/dist/packlets/context/contextToken.js +202 -0
  46. package/dist/packlets/context/convert/decls.js +91 -0
  47. package/dist/packlets/context/convert/index.js +23 -0
  48. package/dist/packlets/context/index.js +26 -0
  49. package/dist/packlets/decisions/abstractDecision.js +68 -0
  50. package/dist/packlets/decisions/abstractDecisionCollector.js +90 -0
  51. package/dist/packlets/decisions/candidate.js +76 -0
  52. package/dist/packlets/decisions/common.js +23 -0
  53. package/dist/packlets/decisions/concreteDecision.js +111 -0
  54. package/dist/packlets/decisions/decision.js +126 -0
  55. package/dist/packlets/decisions/index.js +28 -0
  56. package/dist/packlets/import/fsItem.js +134 -0
  57. package/dist/packlets/import/importContext.js +129 -0
  58. package/dist/packlets/import/importManager.js +129 -0
  59. package/dist/packlets/import/importable.js +32 -0
  60. package/dist/packlets/import/importers/collectionImporter.js +118 -0
  61. package/dist/packlets/import/importers/fsItemImporter.js +116 -0
  62. package/dist/packlets/import/importers/importer.js +23 -0
  63. package/dist/packlets/import/importers/index.browser.js +29 -0
  64. package/dist/packlets/import/importers/index.js +27 -0
  65. package/dist/packlets/import/importers/jsonImporter.js +94 -0
  66. package/dist/packlets/import/importers/pathImporter.js +84 -0
  67. package/dist/packlets/import/index.browser.js +34 -0
  68. package/dist/packlets/import/index.js +28 -0
  69. package/dist/packlets/qualifier-types/config/convert.js +124 -0
  70. package/dist/packlets/qualifier-types/config/index.js +25 -0
  71. package/dist/packlets/qualifier-types/config/json.js +32 -0
  72. package/dist/packlets/qualifier-types/convert.js +56 -0
  73. package/dist/packlets/qualifier-types/helpers.js +82 -0
  74. package/dist/packlets/qualifier-types/index.js +32 -0
  75. package/dist/packlets/qualifier-types/languageQualifierType.js +142 -0
  76. package/dist/packlets/qualifier-types/literalQualifierType.js +200 -0
  77. package/dist/packlets/qualifier-types/literalValueHierarchy.js +236 -0
  78. package/dist/packlets/qualifier-types/qualifierType.js +184 -0
  79. package/dist/packlets/qualifier-types/qualifierTypeCollector.js +66 -0
  80. package/dist/packlets/qualifier-types/territoryQualifierType.js +200 -0
  81. package/dist/packlets/qualifiers/convert/decls.js +70 -0
  82. package/dist/packlets/qualifiers/convert/index.js +24 -0
  83. package/dist/packlets/qualifiers/convert/qualifier.js +40 -0
  84. package/dist/packlets/qualifiers/index.js +29 -0
  85. package/dist/packlets/qualifiers/qualifier.js +108 -0
  86. package/dist/packlets/qualifiers/qualifierCollector.js +123 -0
  87. package/dist/packlets/qualifiers/qualifierDecl.js +23 -0
  88. package/dist/packlets/qualifiers/qualifierDefaultValueDecls.js +23 -0
  89. package/dist/packlets/qualifiers/qualifierDefaultValueToken.js +175 -0
  90. package/dist/packlets/resource-json/compiled/common.js +23 -0
  91. package/dist/packlets/resource-json/compiled/convert.js +132 -0
  92. package/dist/packlets/resource-json/compiled/index.js +26 -0
  93. package/dist/packlets/resource-json/compiled/json.js +2 -0
  94. package/dist/packlets/resource-json/convert.js +171 -0
  95. package/dist/packlets/resource-json/helpers.js +241 -0
  96. package/dist/packlets/resource-json/index.js +31 -0
  97. package/dist/packlets/resource-json/json.js +36 -0
  98. package/dist/packlets/resource-json/normalized.js +23 -0
  99. package/dist/packlets/resource-json/resourceDeclCollection.js +88 -0
  100. package/dist/packlets/resource-json/resourceDeclContainer.js +23 -0
  101. package/dist/packlets/resource-json/resourceDeclTree.js +94 -0
  102. package/dist/packlets/resource-types/config/convert.js +35 -0
  103. package/dist/packlets/resource-types/config/index.js +25 -0
  104. package/dist/packlets/resource-types/config/json.js +23 -0
  105. package/dist/packlets/resource-types/helpers.js +42 -0
  106. package/dist/packlets/resource-types/index.js +28 -0
  107. package/dist/packlets/resource-types/jsonResourceType.js +66 -0
  108. package/dist/packlets/resource-types/resourceType.js +95 -0
  109. package/dist/packlets/resource-types/resourceTypeCollector.js +61 -0
  110. package/dist/packlets/resources/candidateReducer.js +246 -0
  111. package/dist/packlets/resources/candidateValue.js +92 -0
  112. package/dist/packlets/resources/candidateValueCollector.js +94 -0
  113. package/dist/packlets/resources/common.js +23 -0
  114. package/dist/packlets/resources/deltaGenerator.js +338 -0
  115. package/dist/packlets/resources/index.js +31 -0
  116. package/dist/packlets/resources/resource.js +207 -0
  117. package/dist/packlets/resources/resourceBuilder.js +183 -0
  118. package/dist/packlets/resources/resourceCandidate.js +216 -0
  119. package/dist/packlets/resources/resourceManagerBuilder.js +890 -0
  120. package/dist/packlets/runtime/cacheListener.js +58 -0
  121. package/dist/packlets/runtime/cacheMetrics.js +149 -0
  122. package/dist/packlets/runtime/compiledResourceCollection.js +473 -0
  123. package/dist/packlets/runtime/conditionSetResolutionResult.js +134 -0
  124. package/dist/packlets/runtime/context/contextQualifierProvider.js +29 -0
  125. package/dist/packlets/runtime/context/contextQualifierProviderValidator.js +146 -0
  126. package/dist/packlets/runtime/context/index.js +26 -0
  127. package/dist/packlets/runtime/context/simpleContextQualifierProvider.js +196 -0
  128. package/dist/packlets/runtime/context/validatingSimpleContextQualifierProvider.js +60 -0
  129. package/dist/packlets/runtime/iResourceManager.js +23 -0
  130. package/dist/packlets/runtime/index.js +34 -0
  131. package/dist/packlets/runtime/resource-tree/common.js +23 -0
  132. package/dist/packlets/runtime/resource-tree/index.js +26 -0
  133. package/dist/packlets/runtime/resource-tree/readOnlyResourceTree.js +216 -0
  134. package/dist/packlets/runtime/resource-tree/resourceTreeChildren.js +97 -0
  135. package/dist/packlets/runtime/resource-tree/resourceTreeChildrenValidator.js +161 -0
  136. package/dist/packlets/runtime/resourceResolver.js +481 -0
  137. package/dist/packlets/runtime/resourceTreeResolver.js +220 -0
  138. package/dist/packlets/runtime/validate.js +47 -0
  139. package/dist/packlets/zip-archive/convert.js +100 -0
  140. package/dist/packlets/zip-archive/index.browser.js +54 -0
  141. package/dist/packlets/zip-archive/index.js +47 -0
  142. package/dist/packlets/zip-archive/json.js +23 -0
  143. package/dist/packlets/zip-archive/types.js +36 -0
  144. package/dist/packlets/zip-archive/zipArchiveCreator.js +191 -0
  145. package/dist/packlets/zip-archive/zipArchiveFormat.js +140 -0
  146. package/dist/packlets/zip-archive/zipArchiveLoader.js +282 -0
  147. package/dist/test/data/sample.json +32 -0
  148. package/dist/test/unit/qualifier-types/testQualifierType.js +76 -0
  149. package/dist/test/unit/resource-types/testDerivedResourceType.js +109 -0
  150. package/dist/test/unit/resources/deltaGenerator.helpers.js +282 -0
  151. package/dist/tsdoc-metadata.json +1 -1
  152. package/lib/index.browser.d.ts +24 -0
  153. package/lib/index.browser.js +116 -0
  154. package/lib/packlets/config/index.browser.d.ts +7 -0
  155. package/lib/packlets/config/index.browser.js +74 -0
  156. package/lib/packlets/import/importers/index.browser.d.ts +4 -0
  157. package/lib/packlets/import/importers/index.browser.js +45 -0
  158. package/lib/packlets/import/index.browser.d.ts +7 -0
  159. package/lib/packlets/import/index.browser.js +74 -0
  160. package/lib/packlets/zip-archive/index.browser.d.ts +27 -0
  161. package/lib/packlets/zip-archive/index.browser.js +102 -0
  162. package/package.json +25 -7
@@ -0,0 +1,191 @@
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
+ import { zipSync } from 'fflate';
23
+ import { succeed, fail } from '@fgv/ts-utils';
24
+ import { FileTree } from '@fgv/ts-json-base';
25
+ import { normalizePath } from './zipArchiveFormat';
26
+ /**
27
+ * ZIP archive creator using fflate for universal compatibility
28
+ * @public
29
+ */
30
+ export class ZipArchiveCreator {
31
+ /**
32
+ * Create a ZIP archive buffer from a supplied buffer
33
+ * @param options - Input paths and configuration
34
+ * @param onProgress - Optional progress callback
35
+ * @returns Result containing ZIP buffer and manifest
36
+ */
37
+ async createFromBuffer(options, onProgress) {
38
+ try {
39
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress('creating-zip', 0, 'Starting ZIP archive creation');
40
+ const files = {};
41
+ const manifest = {
42
+ timestamp: new Date().toISOString()
43
+ };
44
+ const { value: inputItem, message: inputItemError } = this._getInputFileTreeItem(options);
45
+ if (inputItemError !== undefined) {
46
+ return fail(inputItemError);
47
+ }
48
+ if (inputItem !== undefined) {
49
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress('reading-file', 10, `Processing input: ${inputItem.absolutePath}`);
50
+ if (inputItem.type === 'directory') {
51
+ // Add entire directory recursively, preserving structure
52
+ const archivePath = `input/${inputItem.name}`;
53
+ const addDirResult = await this._addDirectoryTreeToZip(files, inputItem, archivePath, onProgress);
54
+ /* c8 ignore next 3 - defense in depth against internal error */
55
+ if (addDirResult.isFailure()) {
56
+ return fail(addDirResult.message);
57
+ }
58
+ manifest.input = {
59
+ type: 'directory',
60
+ originalPath: inputItem.absolutePath,
61
+ archivePath
62
+ };
63
+ }
64
+ else if (inputItem.type === 'file') {
65
+ // Add single file
66
+ const archivePath = `input/${inputItem.name}`;
67
+ const addFileResult = await this._addFileTreeItemToZip(files, inputItem, archivePath);
68
+ /* c8 ignore next 3 - defense in depth against internal error */
69
+ if (addFileResult.isFailure()) {
70
+ return fail(addFileResult.message);
71
+ }
72
+ manifest.input = {
73
+ type: 'file',
74
+ originalPath: inputItem.absolutePath,
75
+ archivePath
76
+ };
77
+ }
78
+ }
79
+ const { value: configItem, message: configItemError } = this._getConfigFileTreeItem(options);
80
+ if (configItemError !== undefined) {
81
+ return fail(configItemError);
82
+ }
83
+ if (configItem !== undefined) {
84
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress('reading-file', 40, `Processing config: ${configItem.absolutePath}`);
85
+ const archivePath = `config/${configItem.name}`;
86
+ const addConfigResult = await this._addFileTreeItemToZip(files, configItem, archivePath);
87
+ /* c8 ignore next 3 - defense in depth against internal error */
88
+ if (addConfigResult.isFailure()) {
89
+ return fail(addConfigResult.message);
90
+ }
91
+ // Update manifest with config info
92
+ manifest.config = {
93
+ type: 'file',
94
+ originalPath: configItem.absolutePath,
95
+ archivePath
96
+ };
97
+ }
98
+ // Add manifest to ZIP
99
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress('creating-zip', 70, 'Adding manifest');
100
+ const manifestJson = JSON.stringify(manifest, null, 2);
101
+ files['manifest.json'] = new TextEncoder().encode(manifestJson);
102
+ // Create ZIP buffer using fflate
103
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress('creating-zip', 80, 'Compressing files');
104
+ const zipBuffer = zipSync(files, { level: 6 });
105
+ const result = {
106
+ zipBuffer,
107
+ manifest,
108
+ size: zipBuffer.length
109
+ };
110
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress('creating-zip', 100, 'ZIP archive buffer created');
111
+ return succeed(result);
112
+ /* c8 ignore next 3 - defense in depth against internal error */
113
+ }
114
+ catch (error) {
115
+ return fail(`Failed to create ZIP archive: ${error instanceof Error ? error.message : String(error)}`);
116
+ }
117
+ }
118
+ /**
119
+ * Add a single FileTree item to the ZIP archive
120
+ * @param files - ZIP files collection
121
+ * @param fileItem - FileTree file item to add
122
+ * @param archivePath - Path within the archive
123
+ * @returns Result indicating success or failure
124
+ */
125
+ async _addFileTreeItemToZip(files, fileItem, archivePath) {
126
+ return fileItem.getRawContents().onSuccess((content) => {
127
+ const contentBuffer = new TextEncoder().encode(content);
128
+ files[normalizePath(archivePath)] = contentBuffer;
129
+ return succeed(undefined);
130
+ });
131
+ }
132
+ /**
133
+ * Add a directory recursively to the ZIP archive using FileTree
134
+ * @param files - ZIP files collection
135
+ * @param directoryItem - FileTree directory item to add
136
+ * @param archivePrefix - Prefix path within the archive
137
+ * @param onProgress - Optional progress callback
138
+ * @returns Result indicating success or failure
139
+ */
140
+ async _addDirectoryTreeToZip(files, directoryItem, archivePrefix, onProgress) {
141
+ const childrenResult = directoryItem.getChildren();
142
+ /* c8 ignore next 3 - defense in depth against internal error */
143
+ if (childrenResult.isFailure()) {
144
+ return fail(`Failed to read directory ${directoryItem.absolutePath}: ${childrenResult.message}`);
145
+ }
146
+ for (const child of childrenResult.value) {
147
+ const itemArchivePath = normalizePath(`${archivePrefix}/${child.name}`);
148
+ if (child.type === 'directory') {
149
+ // Recursively add subdirectory
150
+ const addDirResult = await this._addDirectoryTreeToZip(files, child, itemArchivePath, onProgress);
151
+ /* c8 ignore next 3 - defense in depth against internal error */
152
+ if (addDirResult.isFailure()) {
153
+ return fail(addDirResult.message);
154
+ }
155
+ }
156
+ else if (child.type === 'file') {
157
+ // Add file
158
+ const addFileResult = await this._addFileTreeItemToZip(files, child, itemArchivePath);
159
+ /* c8 ignore next 3 - defense in depth against internal error */
160
+ if (addFileResult.isFailure()) {
161
+ return fail(addFileResult.message);
162
+ }
163
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress('reading-file', 0, `Added file: ${itemArchivePath}`);
164
+ }
165
+ }
166
+ return succeed(undefined);
167
+ }
168
+ _getInputFileTreeItem(options) {
169
+ if ('inputPath' in options && options.inputPath !== undefined) {
170
+ return FileTree.forFilesystem()
171
+ .withErrorFormat((msg) => `Failed to create file tree: ${msg}`)
172
+ .onSuccess((fileTree) => fileTree.getItem(options.inputPath).withErrorFormat((msg) => `Failed to get item: ${msg}`));
173
+ }
174
+ else if ('inputItem' in options) {
175
+ return succeed(options.inputItem);
176
+ }
177
+ return succeed(undefined);
178
+ }
179
+ _getConfigFileTreeItem(options) {
180
+ if ('configPath' in options && options.configPath !== undefined) {
181
+ return FileTree.forFilesystem()
182
+ .withErrorFormat((msg) => `Failed to create file tree: ${msg}`)
183
+ .onSuccess((fileTree) => fileTree.getFile(options.configPath).withErrorFormat((msg) => `Failed to get config file: ${msg}`));
184
+ }
185
+ else if ('configItem' in options && options.configItem !== undefined) {
186
+ return succeed(options.configItem);
187
+ }
188
+ return succeed(undefined);
189
+ }
190
+ }
191
+ //# sourceMappingURL=zipArchiveCreator.js.map
@@ -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
+ import { captureResult } from '@fgv/ts-utils';
23
+ import * as Convert from './convert';
24
+ /**
25
+ * Create a ZIP archive manifest object
26
+ * @param inputType - Type of input (file or directory)
27
+ * @param originalPath - Original file/directory path
28
+ * @param archivePath - Path within the archive
29
+ * @param configPath - Optional configuration file path
30
+ * @returns ZIP archive manifest
31
+ * @public
32
+ */
33
+ export function createZipArchiveManifest(inputType, originalPath, archivePath, configPath) {
34
+ const manifest = {
35
+ timestamp: new Date().toISOString(),
36
+ input: {
37
+ type: inputType,
38
+ originalPath,
39
+ archivePath
40
+ }
41
+ };
42
+ if (configPath) {
43
+ manifest.config = {
44
+ type: 'file',
45
+ originalPath: configPath,
46
+ archivePath: 'config.json'
47
+ };
48
+ }
49
+ return manifest;
50
+ }
51
+ /**
52
+ * Parse and validate a ZIP archive manifest
53
+ * @param manifestData - JSON string containing manifest data
54
+ * @returns Result containing validated manifest
55
+ * @public
56
+ */
57
+ export function parseZipArchiveManifest(manifestData) {
58
+ return captureResult(() => {
59
+ const parsed = JSON.parse(manifestData);
60
+ return parsed;
61
+ })
62
+ .onSuccess((parsed) => Convert.zipArchiveManifest.validate(parsed))
63
+ .withErrorFormat((e) => `Failed to parse ZIP archive manifest: ${e}`);
64
+ }
65
+ /**
66
+ * Validate a ZIP archive manifest object
67
+ * @param manifest - Object to validate as manifest
68
+ * @returns Result containing validated manifest
69
+ * @public
70
+ */
71
+ export function validateZipArchiveManifest(manifest) {
72
+ return Convert.zipArchiveManifest.validate(manifest);
73
+ }
74
+ /**
75
+ * Parse and validate configuration JSON
76
+ * @param configData - JSON string containing configuration
77
+ * @returns Result containing validated configuration
78
+ * @public
79
+ */
80
+ export function parseZipArchiveConfiguration(configData) {
81
+ return captureResult(() => {
82
+ const parsed = JSON.parse(configData);
83
+ return parsed;
84
+ })
85
+ .onSuccess((parsed) => Convert.systemConfiguration.validate(parsed))
86
+ .withErrorFormat((e) => `Failed to parse ZIP archive configuration: ${e}`);
87
+ }
88
+ /**
89
+ * Generate a timestamp-based filename for ZIP archives
90
+ * @param customName - Optional custom name prefix
91
+ * @returns Generated filename
92
+ * @public
93
+ */
94
+ export function generateZipArchiveFilename(customName) {
95
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-').replace('T', '_').slice(0, -5);
96
+ return customName ? `${customName}-${timestamp}.zip` : `ts-res-archive-${timestamp}.zip`;
97
+ }
98
+ /**
99
+ * Normalize path separators for cross-platform compatibility
100
+ * @param path - Path to normalize
101
+ * @returns Normalized path
102
+ * @public
103
+ */
104
+ export function normalizePath(path) {
105
+ return path.replace(/\\/g, '/').replace(/\/+/g, '/');
106
+ }
107
+ /**
108
+ * Extract directory name from a file path
109
+ * @param path - File path
110
+ * @returns Directory name
111
+ * @public
112
+ */
113
+ export function getDirectoryName(path) {
114
+ const normalized = normalizePath(path);
115
+ const parts = normalized.split('/');
116
+ return parts[parts.length - 1] || 'archive';
117
+ }
118
+ /**
119
+ * Create a safe filename by removing invalid characters
120
+ * @param filename - Original filename
121
+ * @returns Sanitized filename
122
+ * @public
123
+ */
124
+ export function sanitizeFilename(filename) {
125
+ return filename
126
+ .replace(/[<>:"/\\|?*]/g, '_')
127
+ .replace(/\s+/g, '_')
128
+ .replace(/_+/g, '_')
129
+ .trim();
130
+ }
131
+ /**
132
+ * Validate ZIP file extension
133
+ * @param filename - Filename to validate
134
+ * @returns True if filename has .zip extension
135
+ * @public
136
+ */
137
+ export function isZipFile(filename) {
138
+ return filename.toLowerCase().endsWith('.zip');
139
+ }
140
+ //# sourceMappingURL=zipArchiveFormat.js.map
@@ -0,0 +1,282 @@
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
+ import { succeed, fail } from '@fgv/ts-utils';
23
+ // ZipFileTree is browser-safe - doesn't depend on Node.js crypto/fs modules
24
+ import { ZipFileTree } from '@fgv/ts-extras';
25
+ import { parseZipArchiveManifest, parseZipArchiveConfiguration, isZipFile } from './zipArchiveFormat';
26
+ /**
27
+ * ZIP archive loader extending ts-extras foundation
28
+ * @public
29
+ */
30
+ export class ZipArchiveLoader {
31
+ /**
32
+ * Load ZIP archive from File object (Browser)
33
+ * @param file - File object from file input
34
+ * @param options - Loading options
35
+ * @param onProgress - Optional progress callback
36
+ * @returns Result containing loaded archive data
37
+ */
38
+ async loadFromFile(file, options = {}, onProgress) {
39
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress('reading-file', 0, `Reading file: ${file.name}`);
40
+ if (!isZipFile(file.name)) {
41
+ return fail(`File ${file.name} is not a ZIP file`);
42
+ }
43
+ try {
44
+ const buffer = await file.arrayBuffer();
45
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress('reading-file', 100, 'File read complete');
46
+ return await this.loadFromBuffer(buffer, options, onProgress);
47
+ /* c8 ignore next 3 - defense in depth against internal error */
48
+ }
49
+ catch (error) {
50
+ return fail(`Failed to read file: ${error instanceof Error ? error.message : String(error)}`);
51
+ }
52
+ }
53
+ /**
54
+ * Load ZIP archive from ArrayBuffer (Universal)
55
+ * @param buffer - ZIP data buffer
56
+ * @param options - Loading options
57
+ * @param onProgress - Optional progress callback
58
+ * @returns Result containing loaded archive data
59
+ */
60
+ async loadFromBuffer(buffer, options = {}, onProgress) {
61
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress('parsing-zip', 0, 'Parsing ZIP archive');
62
+ const zipAccessorsResult = ZipFileTree.ZipFileTreeAccessors.fromBuffer(buffer);
63
+ if (zipAccessorsResult.isFailure()) {
64
+ return fail(`Failed to parse ZIP: ${zipAccessorsResult.message}`);
65
+ }
66
+ const zipAccessors = zipAccessorsResult.value;
67
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress('parsing-zip', 100, 'ZIP archive parsed');
68
+ // Load manifest
69
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress('loading-manifest', 0, 'Loading manifest');
70
+ const manifestResult = this._loadManifestFromAccessors(zipAccessors);
71
+ if (manifestResult.isFailure()) {
72
+ return fail(manifestResult.message);
73
+ }
74
+ const manifest = manifestResult.value;
75
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress('loading-manifest', 100, 'Manifest loaded');
76
+ // Load configuration
77
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress('loading-config', 0, 'Loading configuration');
78
+ const configResult = this._loadConfigurationFromAccessors(zipAccessors, manifest, options);
79
+ if (configResult.isFailure()) {
80
+ return fail(configResult.message);
81
+ }
82
+ const config = configResult.value;
83
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress('loading-config', 100, 'Configuration loaded');
84
+ // Extract files and directory structure
85
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress('extracting-files', 0, 'Extracting files');
86
+ const filesResult = await this._extractFilesFromAccessors(zipAccessors, onProgress);
87
+ /* c8 ignore next 3 - defense in depth against internal error */
88
+ if (filesResult.isFailure()) {
89
+ return fail(filesResult.message);
90
+ }
91
+ const { files, directory } = filesResult.value;
92
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress('extracting-files', 100, `Extracted ${files.length} files`);
93
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress('extracting-files', 100, 'ZIP loading complete');
94
+ return succeed({
95
+ manifest,
96
+ config,
97
+ files,
98
+ directory
99
+ });
100
+ }
101
+ /**
102
+ * Load manifest from ZIP using ZipFileTreeAccessors
103
+ * @param zipAccessors - ZIP file tree accessors
104
+ * @returns Result containing parsed manifest
105
+ */
106
+ _loadManifestFromAccessors(zipAccessors) {
107
+ const manifestResult = zipAccessors.getFileContents('manifest.json');
108
+ if (manifestResult.isFailure()) {
109
+ // Manifest is optional - return success with undefined
110
+ return succeed(undefined);
111
+ }
112
+ const parseResult = parseZipArchiveManifest(manifestResult.value);
113
+ if (parseResult.isFailure()) {
114
+ return fail(`Failed to parse manifest.json: ${parseResult.message}`);
115
+ }
116
+ return succeed(parseResult.value);
117
+ }
118
+ /**
119
+ * Load configuration from ZIP using ZipFileTreeAccessors
120
+ * @param zipAccessors - ZIP file tree accessors
121
+ * @param manifest - Parsed manifest (may be undefined)
122
+ * @param options - Loading options
123
+ * @returns Result containing parsed configuration
124
+ */
125
+ _loadConfigurationFromAccessors(zipAccessors, manifest, options) {
126
+ // Check if manifest specifies a config file
127
+ const manifestSpecifiesConfig = (manifest === null || manifest === void 0 ? void 0 : manifest.config) !== undefined;
128
+ if (!manifestSpecifiesConfig) {
129
+ // If no config specified in manifest, config is optional
130
+ return succeed(undefined);
131
+ }
132
+ // Get the config path from the manifest
133
+ const configPath = manifest.config.archivePath;
134
+ return zipAccessors
135
+ .getFileContents(configPath)
136
+ .withErrorFormat(() => `Manifest specifies config file at '${configPath}' but it was not found in archive`)
137
+ .onSuccess((configContent) => parseZipArchiveConfiguration(configContent))
138
+ .withErrorFormat((e) => `Failed to parse config file '${configPath}': ${e}`);
139
+ }
140
+ /**
141
+ * Extract files and directory structure from ZIP
142
+ * @param zipAccessors - ZIP file tree accessors
143
+ * @param onProgress - Optional progress callback
144
+ * @returns Result containing files and directory structure
145
+ */
146
+ async _extractFilesFromAccessors(zipAccessors, onProgress) {
147
+ try {
148
+ const files = [];
149
+ const directories = new Map();
150
+ // Get all children from root
151
+ const rootChildrenResult = zipAccessors.getChildren('/');
152
+ /* c8 ignore next 3 - defense in depth against internal error */
153
+ if (rootChildrenResult.isFailure()) {
154
+ return fail(`Failed to read ZIP contents: ${rootChildrenResult.message}`);
155
+ }
156
+ // Process all items recursively
157
+ await this._processFileTreeItems(zipAccessors, '/', rootChildrenResult.value, files, directories, onProgress);
158
+ // Build directory structure
159
+ const directory = this._buildDirectoryStructure(files, directories);
160
+ return succeed({ files, directory });
161
+ /* c8 ignore next 3 - defense in depth against internal error */
162
+ }
163
+ catch (error) {
164
+ return fail(`Failed to extract files: ${error instanceof Error ? error.message : String(error)}`);
165
+ }
166
+ }
167
+ /**
168
+ * Recursively process file tree items
169
+ * @param zipAccessors - ZIP file tree accessors
170
+ * @param currentPath - Current directory path
171
+ * @param items - Items to process
172
+ * @param files - Files collection
173
+ * @param directories - Directories collection
174
+ * @param onProgress - Optional progress callback
175
+ * @param processed - Processing counter
176
+ */
177
+ async _processFileTreeItems(zipAccessors, currentPath, items, files, directories, onProgress, processed = { count: 0 }) {
178
+ for (const item of items) {
179
+ /* c8 ignore next 1 - defense in depth */
180
+ const itemPath = item.absolutePath.startsWith('/') ? item.absolutePath.substring(1) : item.absolutePath;
181
+ if (item.type === 'directory') {
182
+ // Track directory
183
+ if (!directories.has(itemPath)) {
184
+ directories.set(itemPath, {
185
+ name: item.name,
186
+ files: [],
187
+ subdirectories: []
188
+ });
189
+ }
190
+ // Recursively process children
191
+ const childrenResult = zipAccessors.getChildren(item.absolutePath);
192
+ if (childrenResult.isSuccess()) {
193
+ await this._processFileTreeItems(zipAccessors, item.absolutePath, childrenResult.value, files, directories, onProgress, processed);
194
+ }
195
+ }
196
+ else if (item.type === 'file') {
197
+ // Get file content
198
+ const contentResult = item.getRawContents();
199
+ const content = contentResult.orDefault('');
200
+ files.push({
201
+ name: item.name,
202
+ path: itemPath,
203
+ content,
204
+ type: this._getFileType(item.name)
205
+ });
206
+ }
207
+ processed.count++;
208
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress('extracting-files', 0, `Processing ${itemPath}`);
209
+ }
210
+ }
211
+ /**
212
+ * Build directory structure from files
213
+ * @param files - Extracted files
214
+ * @param directories - Directories map
215
+ * @returns Root directory structure or null
216
+ */
217
+ _buildDirectoryStructure(files, directories) {
218
+ /* c8 ignore next 3 - should never happen with fflate */
219
+ if (files.length === 0) {
220
+ return undefined;
221
+ }
222
+ const rootDir = {
223
+ name: 'root',
224
+ files: [],
225
+ subdirectories: []
226
+ };
227
+ // Process files to build directory structure
228
+ for (const file of files) {
229
+ const pathParts = file.path.split('/').filter((part) => part.length > 0);
230
+ /* c8 ignore next 1 - defense in depth should never happen */
231
+ if (pathParts.length === 0)
232
+ continue;
233
+ // Ensure all parent directories exist
234
+ let currentDir = rootDir;
235
+ for (let i = 0; i < pathParts.length - 1; i++) {
236
+ const dirName = pathParts[i];
237
+ let foundDir = currentDir.subdirectories.find((d) => d.name === dirName);
238
+ if (!foundDir) {
239
+ foundDir = {
240
+ name: dirName,
241
+ files: [],
242
+ subdirectories: []
243
+ };
244
+ currentDir.subdirectories.push(foundDir);
245
+ }
246
+ currentDir = foundDir;
247
+ }
248
+ // Add file to its parent directory
249
+ currentDir.files.push(file);
250
+ }
251
+ return rootDir;
252
+ }
253
+ /**
254
+ * Get file MIME type based on extension
255
+ * @param filename - Filename
256
+ * @returns MIME type
257
+ */
258
+ _getFileType(filename) {
259
+ const ext = filename.toLowerCase().split('.').pop();
260
+ /* c8 ignore next 20 - no need to test every one */
261
+ switch (ext) {
262
+ case 'json':
263
+ return 'application/json';
264
+ case 'yaml':
265
+ case 'yml':
266
+ return 'application/yaml';
267
+ case 'xml':
268
+ return 'application/xml';
269
+ case 'txt':
270
+ return 'text/plain';
271
+ case 'md':
272
+ return 'text/markdown';
273
+ case 'js':
274
+ return 'application/javascript';
275
+ case 'ts':
276
+ return 'application/typescript';
277
+ default:
278
+ return 'application/octet-stream';
279
+ }
280
+ }
281
+ }
282
+ //# sourceMappingURL=zipArchiveLoader.js.map
@@ -0,0 +1,32 @@
1
+ [
2
+ {
3
+ "id": "some.resource.path",
4
+ "json": { "home": "United States" },
5
+ "conditions": {
6
+ "homeTerritory": "US"
7
+ }
8
+ },
9
+ {
10
+ "id": "some.resource.path",
11
+ "json": { "speaks": "English" },
12
+ "conditions": {
13
+ "language": "en"
14
+ }
15
+ },
16
+ {
17
+ "id": "some.resource.path",
18
+ "json": { "home": "Canada", "speaks": "Canadian English" },
19
+ "conditions": {
20
+ "homeTerritory": "CA",
21
+ "language": "en-CA"
22
+ },
23
+ "mergeMethod": "replace"
24
+ },
25
+ {
26
+ "id": "some.resource.path",
27
+ "json": { "speaks": "Español" },
28
+ "conditions": {
29
+ "language": "es"
30
+ }
31
+ }
32
+ ]