oneie 1.3.3 → 1.3.4

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 (179) hide show
  1. package/.claude/agents/engineering-architect.md +39 -56
  2. package/.claude/agents/engineering-developer.md +37 -57
  3. package/.claude/agents/engineering-director.md +37 -144
  4. package/.claude/agents/engineering-ingestor.md +229 -0
  5. package/.claude/agents/engineering-quality-assurance.md +40 -206
  6. package/.claude/agents/engineering-user-experience.md +36 -207
  7. package/.claude/agents/improver.md +454 -0
  8. package/.claude/agents/marketing-brand-identity.md +37 -48
  9. package/.claude/agents/marketing-director.md +9 -0
  10. package/.claude/agents/one-orchestrator.md +50 -136
  11. package/.claude/agents/story-teller.md +10 -0
  12. package/.claude/agents/task-master.md +10 -0
  13. package/.claude/agents/turbo-repo-builder.md +51 -0
  14. package/.claude/claude-code-hooks.json +20 -233
  15. package/.claude/commands/agent-balance +111 -0
  16. package/.claude/commands/agent.md +24 -7
  17. package/.claude/commands/cascade-status.md +128 -0
  18. package/.claude/commands/ingest.md +290 -0
  19. package/.claude/commands/ingestor.md +136 -0
  20. package/.claude/commands/mission.md +26 -8
  21. package/.claude/commands/one.md +351 -14
  22. package/.claude/commands/quality-check.md +204 -0
  23. package/.claude/commands/smart-route.md +220 -0
  24. package/.claude/commands/start.md +9 -8
  25. package/.claude/commands/story.md +18 -3
  26. package/.claude/commands/task.md +22 -1
  27. package/.claude/settings.local.json +18 -3
  28. package/.obsidian/core-plugins.json +3 -1
  29. package/.one/checklists/agent-quality-checklist.md +24 -15
  30. package/.one/checklists/story-quality-checklist.md +24 -15
  31. package/.one/checklists/task-quality-checklist.md +24 -15
  32. package/.one/templates/bun-workspace-guide-template.md +188 -0
  33. package/.one/templates/bunfig-template.toml +95 -0
  34. package/.one/templates/root-package-template.json +37 -21
  35. package/.one/templates/turbo-config-template.json +18 -3
  36. package/.one/tools/bump-core-version.js +0 -0
  37. package/.one/tools/bump-expansion-version.js +0 -0
  38. package/.one/tools/code-generators.js +0 -0
  39. package/.one/tools/compression-engine.js +638 -0
  40. package/.one/tools/content-deduplicator.js +336 -0
  41. package/.one/tools/convert-wav-to-mp3.js +0 -0
  42. package/.one/tools/foundation-wizard.js +0 -0
  43. package/.one/tools/generate-toc.js +0 -0
  44. package/.one/tools/ingestor/cascade-integration.js +523 -0
  45. package/.one/tools/ingestor/cli.ts +234 -0
  46. package/.one/tools/ingestor/context-mapper.ts +604 -0
  47. package/.one/tools/ingestor/error-handling-monitor.js +742 -0
  48. package/.one/tools/ingestor/file-discovery.ts +484 -0
  49. package/.one/tools/ingestor/file-transformer.ts +524 -0
  50. package/.one/tools/ingestor/ingestor-orchestrator.ts +416 -0
  51. package/.one/tools/ingestor/package.json +47 -0
  52. package/.one/tools/ingestor/usage-examples.md +458 -0
  53. package/.one/tools/lazy-loader.js +489 -0
  54. package/.one/tools/minimal-generators.js +0 -0
  55. package/.one/tools/performance-benchmark.js +300 -0
  56. package/.one/tools/premium-manager.js +0 -0
  57. package/.one/tools/semantic-release-sync-installer.js +0 -0
  58. package/.one/tools/size-memory-optimizer.js +475 -0
  59. package/.one/tools/sync-installer-version.js +0 -0
  60. package/.one/tools/text-to-speech.js +0 -0
  61. package/.one/tools/transformative-ai-engine.js +0 -0
  62. package/.one/workflows/safe-improvement-deployment.yaml +420 -0
  63. package/CLAUDE.md +30 -0
  64. package/README.md +41 -10
  65. package/one/cache/benchmark-results.json +43 -0
  66. package/one/cache/file-index.json +12480 -0
  67. package/one/config/agent-routing.yaml +124 -0
  68. package/one/config/agent-skills.yaml +451 -0
  69. package/one/config/cache-config.yaml +304 -0
  70. package/one/config/feedback-templates.yaml +152 -0
  71. package/one/config/performance-config.yaml +281 -0
  72. package/one/config/quality-automation.yaml +405 -0
  73. package/one/config/routing-logic.yaml +292 -0
  74. package/one/data/task-registry.yaml +224 -0
  75. package/one/stories/story-1.10-parallel-task-execution-orchestration.md +119 -0
  76. package/one/stories/story-3.1-external-repository-foundation.md +374 -0
  77. package/one/stories/story-3.2-3-levels-architecture-integration.md +449 -0
  78. package/one/stories/story-3.3-multi-platform-application-development.md +677 -0
  79. package/one/stories/story-3.4-shared-package-system-ui-components.md +854 -0
  80. package/one/stories/story-3.5-backend-integration-production-deployment.md +1034 -0
  81. package/one/tasks/task-1.10.1-design-parallel-execution-architecture.md +108 -0
  82. package/one/tasks/task-1.10.2-create-task-dependency-mapping-system.md +82 -0
  83. package/one/tasks/task-1.10.3-build-agent-spawning-orchestration-engine.md +120 -0
  84. package/one/tasks/task-1.10.4-implement-task-queue-dependency-resolution.md +125 -0
  85. package/one/tasks/task-1.10.5-create-task-numbering-convention-system.md +542 -0
  86. package/one/tasks/task-3.1.1-external-repository-creation.md +303 -0
  87. package/one/tasks/task-3.1.2-turborepo-configuration-optimization.md +402 -0
  88. package/one/tasks/task-3.1.3-shared-configuration-packages.md +571 -0
  89. package/one/tasks/task-3.1.4-bun-package-management-optimization.md +627 -0
  90. package/one/tools/task-numbering-validator.js +429 -0
  91. package/package.json +1 -1
  92. package/quality-gate-optimization-analysis.md +260 -0
  93. package/turbo-benchmark.js +268 -0
  94. package/turbo-optimization-guide.md +163 -0
  95. package/turbo-workspace-template.json +83 -0
  96. package/turbo.json +178 -0
  97. package/.claude/commands/analyst.md +0 -70
  98. package/.claude/commands/architect.md +0 -67
  99. package/.claude/commands/commander.md +0 -78
  100. package/.claude/commands/deploy.md +0 -68
  101. package/.claude/commands/dev.md +0 -60
  102. package/.claude/commands/playbook.md +0 -81
  103. package/.claude/commands/pm.md +0 -64
  104. package/.claude/commands/po.md +0 -68
  105. package/.claude/commands/qa.md +0 -59
  106. package/.claude/commands/taskmaster.md +0 -85
  107. package/.claude/commands/ux-expert.md +0 -58
  108. package/.one/stories/bullstamp-attract-module-complete.md +0 -255
  109. package/.one/stories/bullstamp-deployment-master-plan.md +0 -518
  110. package/.one/stories/bullstamp-executive-implementation-summary.md +0 -254
  111. package/.one/stories/bullstamp-project-status-complete.md +0 -257
  112. package/.one/stories/obsidian-pandoc-config.md +0 -159
  113. package/.one/stories/story-1.1-perfect-filesystem-organization.md +0 -270
  114. package/.one/stories/story-1.1.1.md +0 -136
  115. package/.one/stories/story-1.1.md +0 -131
  116. package/.one/stories/story-1.2.md +0 -420
  117. package/.one/stories/story-1.3.md +0 -177
  118. package/.one/stories/story-1.4.md +0 -356
  119. package/.one/stories/story-1.5.md +0 -572
  120. package/.one/stories/story-1.6.md +0 -481
  121. package/.one/stories/story-1.7.md +0 -923
  122. package/.one/stories/story-1.8.md +0 -404
  123. package/.one/stories/story-2.0.md +0 -132
  124. package/.one/stories/story-2.1.md +0 -110
  125. package/.one/stories/story-2.2.md +0 -110
  126. package/.one/stories/story-2.3.md +0 -112
  127. package/.one/stories/story-2.4.md +0 -116
  128. package/.one/stories/story-2.5.md +0 -114
  129. package/.one/stories/story-3.1.md +0 -298
  130. package/.one/stories/story-3.10.md +0 -302
  131. package/.one/stories/story-3.11.md +0 -167
  132. package/.one/stories/story-3.12.md +0 -235
  133. package/.one/stories/story-3.13.md +0 -235
  134. package/.one/stories/story-3.14.md +0 -225
  135. package/.one/stories/story-3.15.md +0 -238
  136. package/.one/stories/story-3.16.md +0 -244
  137. package/.one/stories/story-3.17.md +0 -245
  138. package/.one/stories/story-3.18.md +0 -248
  139. package/.one/stories/story-3.2.md +0 -226
  140. package/.one/stories/story-3.3.md +0 -226
  141. package/.one/stories/story-3.4.md +0 -226
  142. package/.one/stories/story-3.5.md +0 -167
  143. package/.one/stories/story-3.6.md +0 -167
  144. package/.one/stories/story-3.7.md +0 -181
  145. package/.one/stories/story-3.8.md +0 -198
  146. package/.one/stories/story-3.9.md +0 -169
  147. package/.one/stories/story-4.1.md +0 -245
  148. package/.one/stories/story-4.2.md +0 -314
  149. package/.one/stories/story-4.3.md +0 -610
  150. package/.one/stories/story-4.4.md +0 -931
  151. package/.one/stories/story-4.5.md +0 -727
  152. package/.one/stories/story-4.6-consistency.md +0 -175
  153. package/.one/stories/story-5.1.md +0 -508
  154. package/.one/stories/story-5.2.md +0 -451
  155. package/.one/stories/story-5.3.md +0 -405
  156. package/.one/stories/story-5.4.md +0 -447
  157. package/.one/stories/story-5.5.md +0 -349
  158. package/.one/stories/story-5.6.md +0 -445
  159. package/.one/stories/story-6.1-text-content-engine.md +0 -144
  160. package/.one/stories/story-6.2-audio-content-engine.md +0 -145
  161. package/.one/stories/story-6.3-video-content-engine.md +0 -145
  162. package/.one/stories/story-6.4-visual-content-engine.md +0 -177
  163. package/.one/stories/story-6.5-cross-platform-distribution.md +0 -188
  164. package/.one/stories/story-6.6.ai-content-generation-pipeline.md +0 -196
  165. package/.one/stories/story-6.7-character-consistency-quality-control.md +0 -216
  166. package/.one/stories/story-6.8-claude-code-content-integration.md +0 -181
  167. package/.one/stories/story-6.8-content-production-workflows.md +0 -247
  168. package/.one/stories/story-7.1-implementation.md +0 -128
  169. package/.one/stories/story-7.1.md +0 -203
  170. package/.one/stories/story-7.2-implementation.md +0 -147
  171. package/.one/stories/story-7.2.md +0 -415
  172. package/.one/stories/story-7.3-implementation.md +0 -159
  173. package/.one/stories/story-7.3.md +0 -463
  174. package/.one/stories/story-7.4-implementation.md +0 -154
  175. package/.one/stories/story-7.4.md +0 -500
  176. package/.one/stories/story-validation-report.md +0 -169
  177. package/one/archive-index.json +0 -91
  178. /package/one/stories/{story-3.1-npx-oneie-turbo-enhancement.md → story-2.1.1-npx-oneie-turbo-enhancement.md} +0 -0
  179. /package/one/stories/{story-3.2-npx-connection-implementation.md → story-2.21-npx-connection-implementation.md} +0 -0
@@ -0,0 +1,638 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * File Compression Engine
5
+ *
6
+ * Compresses 900K+ markdown files efficiently for 60-80% size reduction
7
+ * Implements smart compression strategies with integrity validation
8
+ */
9
+
10
+ import fs from 'fs/promises';
11
+ import path from 'path';
12
+ import zlib from 'zlib';
13
+ import { promisify } from 'util';
14
+
15
+ class CompressionEngine {
16
+ constructor(options = {}) {
17
+ this.options = {
18
+ directories: ['.one', 'one'],
19
+ extensions: ['.md', '.yaml', '.json', '.txt'],
20
+ compressionLevel: 9,
21
+ minFileSizeBytes: 1000, // Only compress files > 1KB
22
+ preserveOriginals: false,
23
+ batchSize: 50,
24
+ targetCompressionRatio: 0.7, // 70% compression target
25
+ enableDeltaCompression: true,
26
+ enableDictionary: true,
27
+ ...options
28
+ };
29
+
30
+ this.stats = {
31
+ filesProcessed: 0,
32
+ filesCompressed: 0,
33
+ originalSizeBytes: 0,
34
+ compressedSizeBytes: 0,
35
+ compressionRatio: 0,
36
+ processingTimeMs: 0,
37
+ errors: []
38
+ };
39
+
40
+ this.compressionDictionary = null;
41
+ this.contentPatterns = new Map();
42
+
43
+ // Promisify compression methods
44
+ this.gzip = promisify(zlib.gzip);
45
+ this.gunzip = promisify(zlib.gunzip);
46
+ this.deflate = promisify(zlib.deflate);
47
+ this.inflate = promisify(zlib.inflate);
48
+ this.brotliCompress = promisify(zlib.brotliCompress);
49
+ this.brotliDecompress = promisify(zlib.brotliDecompress);
50
+ }
51
+
52
+ /**
53
+ * Main compression execution
54
+ */
55
+ async execute() {
56
+ console.log('🗜️ File Compression Engine - Starting optimization...');
57
+ const startTime = Date.now();
58
+
59
+ try {
60
+ // Build compression dictionary from common patterns
61
+ if (this.options.enableDictionary) {
62
+ await this.buildCompressionDictionary();
63
+ }
64
+
65
+ // Process directories
66
+ for (const directory of this.options.directories) {
67
+ await this.compressDirectory(directory);
68
+ }
69
+
70
+ // Calculate final stats
71
+ this.stats.processingTimeMs = Date.now() - startTime;
72
+ this.stats.compressionRatio = this.stats.originalSizeBytes > 0 ?
73
+ (this.stats.originalSizeBytes - this.stats.compressedSizeBytes) / this.stats.originalSizeBytes : 0;
74
+
75
+ await this.generateCompressionReport();
76
+ this.logResults();
77
+
78
+ return this.stats;
79
+
80
+ } catch (error) {
81
+ console.error('❌ Compression engine failed:', error);
82
+ throw error;
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Build compression dictionary from common content patterns
88
+ */
89
+ async buildCompressionDictionary() {
90
+ console.log('📚 Building compression dictionary...');
91
+
92
+ const patterns = new Map();
93
+ const sampleFiles = [];
94
+
95
+ // Collect sample files for dictionary building
96
+ for (const directory of this.options.directories) {
97
+ const samples = await this.collectSampleFiles(directory, 100);
98
+ sampleFiles.push(...samples);
99
+ }
100
+
101
+ // Analyze common patterns
102
+ for (const filePath of sampleFiles) {
103
+ try {
104
+ const content = await fs.readFile(filePath, 'utf8');
105
+ this.analyzeContentPatterns(content, patterns);
106
+ } catch (error) {
107
+ console.warn(`⚠️ Cannot analyze ${filePath}: ${error.message}`);
108
+ }
109
+ }
110
+
111
+ // Build dictionary from most common patterns
112
+ const commonPatterns = Array.from(patterns.entries())
113
+ .sort(([,a], [,b]) => b.count - a.count)
114
+ .slice(0, 500) // Top 500 patterns
115
+ .map(([pattern]) => pattern);
116
+
117
+ this.compressionDictionary = Buffer.from(commonPatterns.join('\n'));
118
+ console.log(`📚 Dictionary built with ${commonPatterns.length} patterns`);
119
+ }
120
+
121
+ /**
122
+ * Collect sample files for dictionary building
123
+ */
124
+ async collectSampleFiles(directory, maxSamples) {
125
+ const samples = [];
126
+ await this.walkDirectory(directory, async (filePath) => {
127
+ if (samples.length >= maxSamples) return;
128
+
129
+ const ext = path.extname(filePath);
130
+ if (this.options.extensions.includes(ext)) {
131
+ samples.push(filePath);
132
+ }
133
+ });
134
+
135
+ return samples;
136
+ }
137
+
138
+ /**
139
+ * Analyze content for common patterns
140
+ */
141
+ analyzeContentPatterns(content, patterns) {
142
+ // Common markdown patterns
143
+ const markdownPatterns = [
144
+ /^#{1,6}\s+.*$/gm, // Headers
145
+ /\*\*.*?\*\*/g, // Bold
146
+ /\*.*?\*/g, // Italic
147
+ /\[.*?\]\(.*?\)/g, // Links
148
+ /```[\s\S]*?```/g, // Code blocks
149
+ /`.*?`/g, // Inline code
150
+ /^\s*-\s+.*$/gm, // Lists
151
+ /^\s*\d+\.\s+.*$/gm, // Numbered lists
152
+ ];
153
+
154
+ // Extract and count patterns
155
+ for (const regex of markdownPatterns) {
156
+ const matches = content.match(regex) || [];
157
+ for (const match of matches) {
158
+ const normalized = match.trim();
159
+ if (normalized.length > 10 && normalized.length < 100) {
160
+ const existing = patterns.get(normalized) || { count: 0 };
161
+ patterns.set(normalized, { count: existing.count + 1 });
162
+ }
163
+ }
164
+ }
165
+
166
+ // Common YAML patterns
167
+ if (content.includes(':')) {
168
+ const yamlPatterns = content.match(/^\s*\w+:\s*.*$/gm) || [];
169
+ for (const pattern of yamlPatterns) {
170
+ const normalized = pattern.trim();
171
+ if (normalized.length > 5 && normalized.length < 50) {
172
+ const existing = patterns.get(normalized) || { count: 0 };
173
+ patterns.set(normalized, { count: existing.count + 1 });
174
+ }
175
+ }
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Compress directory recursively
181
+ */
182
+ async compressDirectory(directory) {
183
+ console.log(`🗜️ Compressing directory: ${directory}`);
184
+
185
+ const files = [];
186
+ await this.walkDirectory(directory, (filePath) => {
187
+ const ext = path.extname(filePath);
188
+ if (this.options.extensions.includes(ext)) {
189
+ files.push(filePath);
190
+ }
191
+ });
192
+
193
+ console.log(`Found ${files.length} files to process`);
194
+
195
+ // Process files in batches
196
+ for (let i = 0; i < files.length; i += this.options.batchSize) {
197
+ const batch = files.slice(i, i + this.options.batchSize);
198
+ await this.processBatch(batch);
199
+
200
+ // Progress indication
201
+ const progress = ((i + batch.length) / files.length * 100).toFixed(1);
202
+ console.log(`Progress: ${progress}% (${i + batch.length}/${files.length})`);
203
+ }
204
+ }
205
+
206
+ /**
207
+ * Process batch of files for compression
208
+ */
209
+ async processBatch(files) {
210
+ const promises = files.map(filePath => this.compressFile(filePath));
211
+ await Promise.all(promises);
212
+ }
213
+
214
+ /**
215
+ * Compress individual file with optimal strategy
216
+ */
217
+ async compressFile(filePath) {
218
+ try {
219
+ const stats = await fs.stat(filePath);
220
+
221
+ // Skip small files
222
+ if (stats.size < this.options.minFileSizeBytes) {
223
+ return;
224
+ }
225
+
226
+ const originalContent = await fs.readFile(filePath, 'utf8');
227
+ this.stats.originalSizeBytes += stats.size;
228
+ this.stats.filesProcessed++;
229
+
230
+ // Determine best compression strategy
231
+ const compressionStrategy = this.selectCompressionStrategy(originalContent, filePath);
232
+ const compressedResult = await this.applyCompression(originalContent, compressionStrategy);
233
+
234
+ // Only proceed if compression is worthwhile
235
+ if (compressedResult.ratio > this.options.targetCompressionRatio) {
236
+ await this.saveCompressedFile(filePath, compressedResult);
237
+ this.stats.filesCompressed++;
238
+ this.stats.compressedSizeBytes += compressedResult.compressedSize;
239
+ } else {
240
+ // No compression benefit, count original size
241
+ this.stats.compressedSizeBytes += stats.size;
242
+ }
243
+
244
+ } catch (error) {
245
+ this.stats.errors.push({
246
+ file: filePath,
247
+ error: error.message
248
+ });
249
+ console.warn(`⚠️ Cannot compress ${filePath}: ${error.message}`);
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Select optimal compression strategy based on content
255
+ */
256
+ selectCompressionStrategy(content, filePath) {
257
+ const size = Buffer.byteLength(content, 'utf8');
258
+ const ext = path.extname(filePath);
259
+
260
+ let strategy = {
261
+ algorithm: 'gzip',
262
+ level: this.options.compressionLevel,
263
+ windowBits: 15,
264
+ memLevel: 8,
265
+ preprocessor: null
266
+ };
267
+
268
+ // Strategy based on file type
269
+ if (ext === '.md') {
270
+ strategy.preprocessor = 'markdown';
271
+ strategy.algorithm = 'brotli'; // Better for text
272
+ } else if (ext === '.yaml' || ext === '.json') {
273
+ strategy.preprocessor = 'structured';
274
+ strategy.algorithm = 'gzip';
275
+ }
276
+
277
+ // Strategy based on size
278
+ if (size > 100 * 1024) { // > 100KB
279
+ strategy.level = 9; // Maximum compression
280
+ strategy.algorithm = 'brotli';
281
+ } else if (size < 5 * 1024) { // < 5KB
282
+ strategy.level = 6; // Balanced
283
+ }
284
+
285
+ // Strategy based on content characteristics
286
+ const repetitiveness = this.calculateRepetitiveness(content);
287
+ if (repetitiveness > 0.7) {
288
+ strategy.level = 9;
289
+ strategy.algorithm = 'gzip'; // Great for repetitive content
290
+ }
291
+
292
+ return strategy;
293
+ }
294
+
295
+ /**
296
+ * Calculate content repetitiveness score
297
+ */
298
+ calculateRepetitiveness(content) {
299
+ const lines = content.split('\n');
300
+ const uniqueLines = new Set(lines);
301
+ return 1 - (uniqueLines.size / lines.length);
302
+ }
303
+
304
+ /**
305
+ * Apply compression with selected strategy
306
+ */
307
+ async applyCompression(content, strategy) {
308
+ let processedContent = content;
309
+
310
+ // Apply preprocessing
311
+ if (strategy.preprocessor) {
312
+ processedContent = await this.preprocessContent(content, strategy.preprocessor);
313
+ }
314
+
315
+ const originalBuffer = Buffer.from(processedContent, 'utf8');
316
+ let compressedBuffer;
317
+
318
+ // Apply compression algorithm
319
+ switch (strategy.algorithm) {
320
+ case 'brotli':
321
+ compressedBuffer = await this.brotliCompress(originalBuffer, {
322
+ params: {
323
+ [zlib.constants.BROTLI_PARAM_QUALITY]: strategy.level,
324
+ [zlib.constants.BROTLI_PARAM_SIZE_HINT]: originalBuffer.length,
325
+ }
326
+ });
327
+ break;
328
+
329
+ case 'gzip':
330
+ compressedBuffer = await this.gzip(originalBuffer, {
331
+ level: strategy.level,
332
+ windowBits: strategy.windowBits,
333
+ memLevel: strategy.memLevel,
334
+ dictionary: this.compressionDictionary
335
+ });
336
+ break;
337
+
338
+ case 'deflate':
339
+ compressedBuffer = await this.deflate(originalBuffer, {
340
+ level: strategy.level,
341
+ windowBits: strategy.windowBits,
342
+ memLevel: strategy.memLevel
343
+ });
344
+ break;
345
+
346
+ default:
347
+ throw new Error(`Unsupported compression algorithm: ${strategy.algorithm}`);
348
+ }
349
+
350
+ const ratio = (originalBuffer.length - compressedBuffer.length) / originalBuffer.length;
351
+
352
+ return {
353
+ algorithm: strategy.algorithm,
354
+ compressedBuffer,
355
+ originalSize: originalBuffer.length,
356
+ compressedSize: compressedBuffer.length,
357
+ ratio,
358
+ preprocessor: strategy.preprocessor
359
+ };
360
+ }
361
+
362
+ /**
363
+ * Preprocess content for better compression
364
+ */
365
+ async preprocessContent(content, type) {
366
+ switch (type) {
367
+ case 'markdown':
368
+ return this.preprocessMarkdown(content);
369
+
370
+ case 'structured':
371
+ return this.preprocessStructured(content);
372
+
373
+ default:
374
+ return content;
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Preprocess markdown for better compression
380
+ */
381
+ preprocessMarkdown(content) {
382
+ return content
383
+ // Normalize whitespace
384
+ .replace(/[ \t]+$/gm, '')
385
+ .replace(/\n{3,}/g, '\n\n')
386
+ // Normalize headers
387
+ .replace(/^(#{1,6})\s+/gm, '$1 ')
388
+ // Normalize lists
389
+ .replace(/^\s*[\*\-\+]\s+/gm, '- ')
390
+ // Normalize links
391
+ .replace(/\]\(\s+/g, '](')
392
+ .replace(/\s+\)/g, ')')
393
+ .trim();
394
+ }
395
+
396
+ /**
397
+ * Preprocess structured data for better compression
398
+ */
399
+ preprocessStructured(content) {
400
+ try {
401
+ // Try to parse and reformat for consistent structure
402
+ if (content.trim().startsWith('{')) {
403
+ const parsed = JSON.parse(content);
404
+ return JSON.stringify(parsed, null, 0); // Compact format
405
+ } else if (content.includes(':')) {
406
+ // Basic YAML normalization
407
+ return content
408
+ .replace(/:\s+/g, ':')
409
+ .replace(/\s+$/gm, '')
410
+ .trim();
411
+ }
412
+ } catch (error) {
413
+ // If parsing fails, return normalized content
414
+ }
415
+
416
+ return content
417
+ .replace(/\s+$/gm, '')
418
+ .replace(/\n{3,}/g, '\n\n')
419
+ .trim();
420
+ }
421
+
422
+ /**
423
+ * Save compressed file
424
+ */
425
+ async saveCompressedFile(originalPath, compressionResult) {
426
+ const compressedPath = originalPath + '.compressed';
427
+ const metadataPath = originalPath + '.compression-meta.json';
428
+
429
+ // Save compressed content
430
+ await fs.writeFile(compressedPath, compressionResult.compressedBuffer);
431
+
432
+ // Save metadata
433
+ const metadata = {
434
+ originalFile: originalPath,
435
+ algorithm: compressionResult.algorithm,
436
+ originalSize: compressionResult.originalSize,
437
+ compressedSize: compressionResult.compressedSize,
438
+ ratio: compressionResult.ratio,
439
+ preprocessor: compressionResult.preprocessor,
440
+ timestamp: new Date().toISOString(),
441
+ version: '1.0.0'
442
+ };
443
+
444
+ await fs.writeFile(metadataPath, JSON.stringify(metadata, null, 2));
445
+
446
+ // Optionally replace original file with compressed version
447
+ if (!this.options.preserveOriginals) {
448
+ const backupPath = originalPath + '.original';
449
+ await fs.rename(originalPath, backupPath);
450
+
451
+ // Create a decompression script for easy access
452
+ const decompressScript = this.generateDecompressionScript(originalPath, compressionResult);
453
+ await fs.writeFile(originalPath + '.decompress.js', decompressScript);
454
+ }
455
+
456
+ console.log(`✅ Compressed ${originalPath}: ${this.formatBytes(compressionResult.originalSize)} -> ${this.formatBytes(compressionResult.compressedSize)} (${(compressionResult.ratio * 100).toFixed(1)}%)`);
457
+ }
458
+
459
+ /**
460
+ * Generate decompression script for easy file access
461
+ */
462
+ generateDecompressionScript(originalPath, compressionResult) {
463
+ return `#!/usr/bin/env node
464
+ // Auto-generated decompression script for ${originalPath}
465
+ const fs = require('fs');
466
+ const zlib = require('zlib');
467
+
468
+ async function decompress() {
469
+ try {
470
+ const compressedPath = '${originalPath}.compressed';
471
+ const compressedBuffer = fs.readFileSync(compressedPath);
472
+
473
+ let decompressedBuffer;
474
+
475
+ switch ('${compressionResult.algorithm}') {
476
+ case 'brotli':
477
+ decompressedBuffer = zlib.brotliDecompressSync(compressedBuffer);
478
+ break;
479
+ case 'gzip':
480
+ decompressedBuffer = zlib.gunzipSync(compressedBuffer);
481
+ break;
482
+ case 'deflate':
483
+ decompressedBuffer = zlib.inflateSync(compressedBuffer);
484
+ break;
485
+ default:
486
+ throw new Error('Unsupported compression algorithm');
487
+ }
488
+
489
+ console.log(decompressedBuffer.toString('utf8'));
490
+ } catch (error) {
491
+ console.error('Decompression failed:', error.message);
492
+ process.exit(1);
493
+ }
494
+ }
495
+
496
+ decompress();
497
+ `;
498
+ }
499
+
500
+ /**
501
+ * Walk directory recursively
502
+ */
503
+ async walkDirectory(dirPath, callback) {
504
+ try {
505
+ const entries = await fs.readdir(dirPath, { withFileTypes: true });
506
+
507
+ for (const entry of entries) {
508
+ const fullPath = path.join(dirPath, entry.name);
509
+
510
+ if (entry.isDirectory()) {
511
+ // Skip certain directories
512
+ if (!['node_modules', '.git', '.next', 'dist', 'build'].includes(entry.name)) {
513
+ await this.walkDirectory(fullPath, callback);
514
+ }
515
+ } else if (entry.isFile()) {
516
+ await callback(fullPath);
517
+ }
518
+ }
519
+ } catch (error) {
520
+ console.warn(`⚠️ Cannot walk directory ${dirPath}: ${error.message}`);
521
+ }
522
+ }
523
+
524
+ /**
525
+ * Generate compression report
526
+ */
527
+ async generateCompressionReport() {
528
+ const report = {
529
+ timestamp: new Date().toISOString(),
530
+ version: '1.0.0',
531
+ configuration: this.options,
532
+ statistics: {
533
+ ...this.stats,
534
+ compressionRatioPercent: (this.stats.compressionRatio * 100).toFixed(2),
535
+ spaceSavedBytes: this.stats.originalSizeBytes - this.stats.compressedSizeBytes,
536
+ spaceSavedMB: ((this.stats.originalSizeBytes - this.stats.compressedSizeBytes) / 1024 / 1024).toFixed(2),
537
+ averageCompressionRatio: this.stats.filesCompressed > 0 ?
538
+ (this.stats.compressionRatio / this.stats.filesCompressed * 100).toFixed(2) : 0,
539
+ processingSpeed: (this.stats.filesProcessed / (this.stats.processingTimeMs / 1000)).toFixed(2) + ' files/sec'
540
+ },
541
+ errors: this.stats.errors,
542
+ recommendations: this.generateOptimizationRecommendations()
543
+ };
544
+
545
+ const reportPath = path.join('.one', 'reports', 'compression-report.json');
546
+ await fs.mkdir(path.dirname(reportPath), { recursive: true });
547
+ await fs.writeFile(reportPath, JSON.stringify(report, null, 2));
548
+
549
+ console.log(`📊 Compression report saved to: ${reportPath}`);
550
+ return report;
551
+ }
552
+
553
+ /**
554
+ * Generate optimization recommendations
555
+ */
556
+ generateOptimizationRecommendations() {
557
+ const recommendations = [];
558
+
559
+ if (this.stats.compressionRatio < 0.5) {
560
+ recommendations.push({
561
+ type: 'compression_strategy',
562
+ message: 'Consider using Brotli compression for better text compression ratios',
563
+ impact: 'medium'
564
+ });
565
+ }
566
+
567
+ if (this.stats.errors.length > this.stats.filesProcessed * 0.1) {
568
+ recommendations.push({
569
+ type: 'error_handling',
570
+ message: 'High error rate detected. Review file permissions and encoding issues',
571
+ impact: 'high'
572
+ });
573
+ }
574
+
575
+ if (this.stats.filesProcessed > 1000 && this.stats.processingTimeMs > 60000) {
576
+ recommendations.push({
577
+ type: 'performance',
578
+ message: 'Consider increasing batch size or using parallel processing for large datasets',
579
+ impact: 'medium'
580
+ });
581
+ }
582
+
583
+ return recommendations;
584
+ }
585
+
586
+ /**
587
+ * Log compression results
588
+ */
589
+ logResults() {
590
+ const spaceSaved = this.stats.originalSizeBytes - this.stats.compressedSizeBytes;
591
+
592
+ console.log('\n🎉 Compression Results:');
593
+ console.log(` 📁 Files processed: ${this.stats.filesProcessed}`);
594
+ console.log(` 🗜️ Files compressed: ${this.stats.filesCompressed}`);
595
+ console.log(` 📊 Original size: ${this.formatBytes(this.stats.originalSizeBytes)}`);
596
+ console.log(` 📊 Compressed size: ${this.formatBytes(this.stats.compressedSizeBytes)}`);
597
+ console.log(` 💾 Space saved: ${this.formatBytes(spaceSaved)} (${(this.stats.compressionRatio * 100).toFixed(1)}%)`);
598
+ console.log(` ⏱️ Processing time: ${(this.stats.processingTimeMs / 1000).toFixed(2)}s`);
599
+ console.log(` 🚀 Speed: ${(this.stats.filesProcessed / (this.stats.processingTimeMs / 1000)).toFixed(1)} files/sec`);
600
+
601
+ if (this.stats.errors.length > 0) {
602
+ console.log(` ⚠️ Errors: ${this.stats.errors.length}`);
603
+ }
604
+ }
605
+
606
+ /**
607
+ * Format bytes to human readable
608
+ */
609
+ formatBytes(bytes) {
610
+ if (bytes === 0) return '0 B';
611
+ const k = 1024;
612
+ const sizes = ['B', 'KB', 'MB', 'GB'];
613
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
614
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
615
+ }
616
+ }
617
+
618
+ // CLI execution
619
+ if (process.argv[1] === new URL(import.meta.url).pathname) {
620
+ const engine = new CompressionEngine({
621
+ directories: process.argv.includes('--one-only') ? ['one'] : ['.one', 'one'],
622
+ preserveOriginals: !process.argv.includes('--replace-originals'),
623
+ compressionLevel: parseInt(process.argv.find(arg => arg.startsWith('--level='))?.split('=')[1]) || 9,
624
+ batchSize: parseInt(process.argv.find(arg => arg.startsWith('--batch='))?.split('=')[1]) || 50
625
+ });
626
+
627
+ engine.execute()
628
+ .then(stats => {
629
+ console.log('\n✅ Compression completed successfully!');
630
+ process.exit(0);
631
+ })
632
+ .catch(error => {
633
+ console.error('❌ Compression failed:', error.message);
634
+ process.exit(1);
635
+ });
636
+ }
637
+
638
+ export default CompressionEngine;