lula2 0.0.5 → 0.0.6

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 (108) hide show
  1. package/README.md +291 -8
  2. package/dist/_app/env.js +1 -0
  3. package/dist/_app/immutable/assets/0.DtiRW3lO.css +1 -0
  4. package/dist/_app/immutable/assets/DynamicControlEditor.BkVTzFZ-.css +1 -0
  5. package/dist/_app/immutable/chunks/7x_q-1ab.js +1 -0
  6. package/dist/_app/immutable/chunks/B19gt6-g.js +2 -0
  7. package/dist/_app/immutable/chunks/BR-0Dorr.js +1 -0
  8. package/dist/_app/immutable/chunks/B_3ksxz5.js +2 -0
  9. package/dist/_app/immutable/chunks/Bg_R1qWi.js +3 -0
  10. package/dist/_app/immutable/chunks/D3aNP_lg.js +1 -0
  11. package/dist/_app/immutable/chunks/D4Q_ObIy.js +1 -0
  12. package/dist/_app/immutable/chunks/DsnmJJEf.js +1 -0
  13. package/dist/_app/immutable/chunks/XY2j_owG.js +66 -0
  14. package/dist/_app/immutable/chunks/rzN25oDf.js +1 -0
  15. package/dist/_app/immutable/entry/app.r0uOd9qg.js +2 -0
  16. package/dist/_app/immutable/entry/start.DvoqR0rc.js +1 -0
  17. package/dist/_app/immutable/nodes/0.Ct6FAss_.js +1 -0
  18. package/dist/_app/immutable/nodes/1.DLoKuy8Q.js +1 -0
  19. package/dist/_app/immutable/nodes/2.IRkwSmiB.js +1 -0
  20. package/dist/_app/immutable/nodes/3.BrTg-ZHv.js +1 -0
  21. package/dist/_app/immutable/nodes/4.Blq-4WQS.js +9 -0
  22. package/dist/_app/version.json +1 -0
  23. package/dist/cli/commands/crawl.js +128 -0
  24. package/dist/cli/commands/ui.js +2769 -0
  25. package/dist/cli/commands/version.js +30 -0
  26. package/dist/cli/server/index.js +2713 -0
  27. package/dist/cli/server/server.js +2702 -0
  28. package/dist/cli/server/serverState.js +1199 -0
  29. package/dist/cli/server/spreadsheetRoutes.js +788 -0
  30. package/dist/cli/server/types.js +0 -0
  31. package/dist/cli/server/websocketServer.js +2625 -0
  32. package/dist/cli/utils/debug.js +24 -0
  33. package/dist/favicon.svg +1 -0
  34. package/dist/index.html +38 -0
  35. package/dist/index.js +2924 -37
  36. package/dist/lula.png +0 -0
  37. package/dist/lula2 +2 -0
  38. package/package.json +120 -72
  39. package/src/app.css +192 -0
  40. package/src/app.d.ts +13 -0
  41. package/src/app.html +13 -0
  42. package/src/lib/actions/fadeWhenScrollable.ts +39 -0
  43. package/src/lib/actions/modal.ts +230 -0
  44. package/src/lib/actions/tooltip.ts +82 -0
  45. package/src/lib/components/control-sets/ControlSetInfo.svelte +20 -0
  46. package/src/lib/components/control-sets/ControlSetSelector.svelte +46 -0
  47. package/src/lib/components/control-sets/index.ts +5 -0
  48. package/src/lib/components/controls/ControlDetailsPanel.svelte +235 -0
  49. package/src/lib/components/controls/ControlsList.svelte +608 -0
  50. package/src/lib/components/controls/DynamicControlEditor.svelte +298 -0
  51. package/src/lib/components/controls/MappingCard.svelte +105 -0
  52. package/src/lib/components/controls/MappingForm.svelte +188 -0
  53. package/src/lib/components/controls/index.ts +9 -0
  54. package/src/lib/components/controls/renderers/EditableFieldRenderer.svelte +103 -0
  55. package/src/lib/components/controls/renderers/FieldRenderer.svelte +49 -0
  56. package/src/lib/components/controls/renderers/index.ts +5 -0
  57. package/src/lib/components/controls/tabs/CustomFieldsTab.svelte +130 -0
  58. package/src/lib/components/controls/tabs/ImplementationTab.svelte +127 -0
  59. package/src/lib/components/controls/tabs/MappingsTab.svelte +182 -0
  60. package/src/lib/components/controls/tabs/OverviewTab.svelte +151 -0
  61. package/src/lib/components/controls/tabs/TimelineTab.svelte +41 -0
  62. package/src/lib/components/controls/tabs/index.ts +8 -0
  63. package/src/lib/components/controls/utils/ProcessedTextRenderer.svelte +63 -0
  64. package/src/lib/components/controls/utils/textProcessor.ts +164 -0
  65. package/src/lib/components/forms/DynamicControlForm.svelte +340 -0
  66. package/src/lib/components/forms/DynamicField.svelte +494 -0
  67. package/src/lib/components/forms/FormField.svelte +107 -0
  68. package/src/lib/components/forms/index.ts +6 -0
  69. package/src/lib/components/setup/ExistingControlSets.svelte +284 -0
  70. package/src/lib/components/setup/SpreadsheetImport.svelte +968 -0
  71. package/src/lib/components/setup/index.ts +5 -0
  72. package/src/lib/components/ui/Dropdown.svelte +107 -0
  73. package/src/lib/components/ui/EmptyState.svelte +80 -0
  74. package/src/lib/components/ui/FeatureToggle.svelte +50 -0
  75. package/src/lib/components/ui/SearchBar.svelte +73 -0
  76. package/src/lib/components/ui/StatusBadge.svelte +79 -0
  77. package/src/lib/components/ui/TabNavigation.svelte +48 -0
  78. package/src/lib/components/ui/Tooltip.svelte +120 -0
  79. package/src/lib/components/ui/index.ts +10 -0
  80. package/src/lib/components/version-control/DiffViewer.svelte +292 -0
  81. package/src/lib/components/version-control/TimelineItem.svelte +107 -0
  82. package/src/lib/components/version-control/YamlDiffViewer.svelte +428 -0
  83. package/src/lib/components/version-control/index.ts +6 -0
  84. package/src/lib/form-types.ts +57 -0
  85. package/src/lib/formatUtils.ts +17 -0
  86. package/src/lib/index.ts +5 -0
  87. package/src/lib/types.ts +180 -0
  88. package/src/lib/websocket.ts +359 -0
  89. package/src/routes/+layout.svelte +236 -0
  90. package/src/routes/+page.svelte +38 -0
  91. package/src/routes/control/[id]/+page.svelte +112 -0
  92. package/src/routes/setup/+page.svelte +241 -0
  93. package/src/stores/compliance.ts +95 -0
  94. package/src/styles/highlightjs.css +20 -0
  95. package/src/styles/modal.css +58 -0
  96. package/src/styles/tables.css +111 -0
  97. package/src/styles/tooltip.css +65 -0
  98. package/dist/controls/index.d.ts +0 -18
  99. package/dist/controls/index.d.ts.map +0 -1
  100. package/dist/controls/index.js +0 -18
  101. package/dist/crawl.d.ts +0 -62
  102. package/dist/crawl.d.ts.map +0 -1
  103. package/dist/crawl.js +0 -172
  104. package/dist/index.d.ts +0 -8
  105. package/dist/index.d.ts.map +0 -1
  106. package/src/controls/index.ts +0 -19
  107. package/src/crawl.ts +0 -227
  108. package/src/index.ts +0 -46
package/dist/index.js CHANGED
@@ -1,40 +1,2927 @@
1
1
  #!/usr/bin/env node
2
- import { Command } from "commander";
3
- import crawl from "./crawl.js";
4
- import fs from "fs";
5
- import path from "path";
6
- const program = new Command();
7
- import { fileURLToPath } from "url";
8
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
9
- /**
10
- * Get the current version from package.json
11
- *
12
- * @returns The current version
13
- */
14
- export function getVersion() {
15
- const pkgPath = path.resolve(__dirname, "../package.json"); // adjust path if index.ts is in src/
16
- const packageJson = fs.readFileSync(pkgPath, "utf8");
17
- const { version } = JSON.parse(packageJson);
18
- return version;
19
- }
20
- program
21
- .name("lula2")
22
- .description("Reports and exports compliance status for defined controls")
23
- .version(getVersion(), "-v, --version", "output the current version")
24
- .option("-c, --config <path>", "path to config file", "compliance.json")
25
- .addCommand(crawl())
26
- .action(options => {
27
- console.log("Checking compliance status...");
28
- if (options.config) {
29
- console.log(`Using config file: ${options.config}`);
30
- }
31
- else {
32
- console.log("Using default configuration");
33
- }
34
- console.log("Compliance check completed!");
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res) => function __init() {
5
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
+ };
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+
12
+ // cli/utils/debug.ts
13
+ var debug_exports = {};
14
+ __export(debug_exports, {
15
+ debug: () => debug,
16
+ debugError: () => debugError,
17
+ isDebugEnabled: () => isDebugEnabled,
18
+ setDebugMode: () => setDebugMode
35
19
  });
36
- program.parse(process.argv);
37
- // If no command is provided, show help
38
- if (!process.argv.slice(1).length) {
39
- program.help();
20
+ function setDebugMode(enabled) {
21
+ debugEnabled = enabled || process.env.DEBUG === "true" || process.env.DEBUG === "1";
22
+ }
23
+ function debug(...args) {
24
+ if (debugEnabled) {
25
+ console.log("[DEBUG]", ...args);
26
+ }
27
+ }
28
+ function debugError(...args) {
29
+ if (debugEnabled) {
30
+ console.error("[DEBUG ERROR]", ...args);
31
+ }
32
+ }
33
+ function isDebugEnabled() {
34
+ return debugEnabled;
35
+ }
36
+ var debugEnabled;
37
+ var init_debug = __esm({
38
+ "cli/utils/debug.ts"() {
39
+ "use strict";
40
+ debugEnabled = false;
41
+ }
42
+ });
43
+
44
+ // cli/server/infrastructure/controlHelpers.ts
45
+ import { existsSync, readFileSync } from "fs";
46
+ import { join } from "path";
47
+ import * as yaml from "js-yaml";
48
+ function loadControlSetMetadata(baseDir) {
49
+ const path2 = join(baseDir, "lula.yaml");
50
+ if (metadataPath !== path2 || !controlSetMetadata) {
51
+ if (existsSync(path2)) {
52
+ try {
53
+ const content = readFileSync(path2, "utf8");
54
+ controlSetMetadata = yaml.load(content);
55
+ metadataPath = path2;
56
+ } catch (error) {
57
+ console.error(`Failed to parse lula.yaml at ${path2}:`, error);
58
+ controlSetMetadata = {};
59
+ metadataPath = path2;
60
+ }
61
+ } else {
62
+ controlSetMetadata = {};
63
+ metadataPath = path2;
64
+ }
65
+ }
66
+ return controlSetMetadata;
67
+ }
68
+ function getControlIdField(baseDir) {
69
+ if (baseDir) {
70
+ loadControlSetMetadata(baseDir);
71
+ }
72
+ return controlSetMetadata?.control_id_field || "id";
73
+ }
74
+ function getControlId(control, baseDir) {
75
+ if (!control || typeof control !== "object") {
76
+ throw new Error("Invalid control object provided");
77
+ }
78
+ const idField = getControlIdField(baseDir);
79
+ const configuredId = control[idField];
80
+ if (configuredId && typeof configuredId === "string") {
81
+ return configuredId;
82
+ }
83
+ if (idField !== "id" && control.id) {
84
+ return control.id;
85
+ }
86
+ const possibleIdFields = [
87
+ "ap-acronym",
88
+ "control-id",
89
+ "control_id",
90
+ "controlId"
91
+ ];
92
+ for (const field of possibleIdFields) {
93
+ const value = control[field];
94
+ if (value && typeof value === "string") {
95
+ return value;
96
+ }
97
+ }
98
+ const availableFields = Object.keys(control).filter(
99
+ (key) => control[key] !== void 0
100
+ );
101
+ throw new Error(
102
+ `No control ID found in control object. Available fields: ${availableFields.join(", ")}`
103
+ );
104
+ }
105
+ var controlSetMetadata, metadataPath;
106
+ var init_controlHelpers = __esm({
107
+ "cli/server/infrastructure/controlHelpers.ts"() {
108
+ "use strict";
109
+ controlSetMetadata = null;
110
+ metadataPath = null;
111
+ }
112
+ });
113
+
114
+ // cli/server/infrastructure/fileStore.ts
115
+ var fileStore_exports = {};
116
+ __export(fileStore_exports, {
117
+ FileStore: () => FileStore
118
+ });
119
+ import {
120
+ existsSync as existsSync2,
121
+ promises as fs,
122
+ mkdirSync,
123
+ readdirSync,
124
+ readFileSync as readFileSync2,
125
+ statSync,
126
+ unlinkSync,
127
+ writeFileSync
128
+ } from "fs";
129
+ import * as yaml2 from "js-yaml";
130
+ import { join as join2 } from "path";
131
+ var FileStore;
132
+ var init_fileStore = __esm({
133
+ "cli/server/infrastructure/fileStore.ts"() {
134
+ "use strict";
135
+ init_controlHelpers();
136
+ FileStore = class {
137
+ baseDir;
138
+ controlsDir;
139
+ mappingsDir;
140
+ // Simple cache - just control ID to filename mapping
141
+ controlMetadataCache = /* @__PURE__ */ new Map();
142
+ constructor(options) {
143
+ this.baseDir = options.baseDir;
144
+ this.controlsDir = join2(this.baseDir, "controls");
145
+ this.mappingsDir = join2(this.baseDir, "mappings");
146
+ if (existsSync2(this.controlsDir)) {
147
+ this.refreshControlsCache();
148
+ }
149
+ }
150
+ /**
151
+ * Get simple filename from control ID
152
+ */
153
+ getControlFilename(controlId) {
154
+ const sanitized = controlId.replace(/[^\w\-]/g, "_");
155
+ return `${sanitized}.yaml`;
156
+ }
157
+ /**
158
+ * Get family name from control ID
159
+ */
160
+ getControlFamily(controlId) {
161
+ return controlId.split("-")[0];
162
+ }
163
+ /**
164
+ * Ensure required directories exist
165
+ */
166
+ ensureDirectories() {
167
+ if (!this.baseDir || this.baseDir === "." || this.baseDir === process.cwd()) {
168
+ return;
169
+ }
170
+ const lulaConfigPath = join2(this.baseDir, "lula.yaml");
171
+ if (!existsSync2(lulaConfigPath)) {
172
+ return;
173
+ }
174
+ if (!existsSync2(this.controlsDir)) {
175
+ mkdirSync(this.controlsDir, { recursive: true });
176
+ }
177
+ if (!existsSync2(this.mappingsDir)) {
178
+ mkdirSync(this.mappingsDir, { recursive: true });
179
+ }
180
+ }
181
+ /**
182
+ * Get control metadata by ID
183
+ */
184
+ getControlMetadata(controlId) {
185
+ return this.controlMetadataCache.get(controlId);
186
+ }
187
+ /**
188
+ * Load a control by ID
189
+ */
190
+ async loadControl(controlId) {
191
+ const sanitizedId = controlId.replace(/[^\w\-]/g, "_");
192
+ const possibleFlatPaths = [
193
+ join2(this.controlsDir, `${controlId}.yaml`),
194
+ join2(this.controlsDir, `${sanitizedId}.yaml`)
195
+ ];
196
+ for (const flatFilePath of possibleFlatPaths) {
197
+ if (existsSync2(flatFilePath)) {
198
+ try {
199
+ const content = readFileSync2(flatFilePath, "utf8");
200
+ const parsed = yaml2.load(content);
201
+ if (!parsed.id) {
202
+ parsed.id = controlId.replace(/_(\d)/g, ".$1");
203
+ }
204
+ return parsed;
205
+ } catch (error) {
206
+ console.error(`Failed to load control ${controlId} from flat structure:`, error);
207
+ throw new Error(
208
+ `Failed to load control ${controlId}: ${error instanceof Error ? error.message : String(error)}`
209
+ );
210
+ }
211
+ }
212
+ }
213
+ const family = this.getControlFamily(controlId);
214
+ const familyDir = join2(this.controlsDir, family);
215
+ const possibleFamilyPaths = [
216
+ join2(familyDir, `${controlId}.yaml`),
217
+ join2(familyDir, `${sanitizedId}.yaml`)
218
+ ];
219
+ for (const filePath of possibleFamilyPaths) {
220
+ if (existsSync2(filePath)) {
221
+ try {
222
+ const content = readFileSync2(filePath, "utf8");
223
+ const parsed = yaml2.load(content);
224
+ if (!parsed.id) {
225
+ parsed.id = controlId.replace(/_(\d)/g, ".$1");
226
+ }
227
+ return parsed;
228
+ } catch (error) {
229
+ console.error(`Failed to load control ${controlId}:`, error);
230
+ throw new Error(
231
+ `Failed to load control ${controlId}: ${error instanceof Error ? error.message : String(error)}`
232
+ );
233
+ }
234
+ }
235
+ }
236
+ return null;
237
+ }
238
+ /**
239
+ * Save a control
240
+ */
241
+ async saveControl(control) {
242
+ this.ensureDirectories();
243
+ const controlId = getControlId(control, this.baseDir);
244
+ const family = this.getControlFamily(controlId);
245
+ const filename = this.getControlFilename(controlId);
246
+ const familyDir = join2(this.controlsDir, family);
247
+ const filePath = join2(familyDir, filename);
248
+ if (!existsSync2(familyDir)) {
249
+ mkdirSync(familyDir, { recursive: true });
250
+ }
251
+ try {
252
+ let yamlContent;
253
+ if (existsSync2(filePath)) {
254
+ const existingContent = readFileSync2(filePath, "utf8");
255
+ const existingControl = yaml2.load(existingContent);
256
+ const fieldsToUpdate = {};
257
+ for (const key in control) {
258
+ if (key === "timeline" || key === "unifiedHistory" || key === "_metadata" || key === "id") {
259
+ continue;
260
+ }
261
+ if (JSON.stringify(control[key]) !== JSON.stringify(existingControl[key])) {
262
+ fieldsToUpdate[key] = control[key];
263
+ }
264
+ }
265
+ if (Object.keys(fieldsToUpdate).length > 0) {
266
+ const updatedControl = { ...existingControl, ...fieldsToUpdate };
267
+ yamlContent = yaml2.dump(updatedControl, {
268
+ indent: 2,
269
+ lineWidth: 80,
270
+ noRefs: true,
271
+ sortKeys: false
272
+ });
273
+ } else {
274
+ yamlContent = existingContent;
275
+ }
276
+ } else {
277
+ const controlToSave = { ...control };
278
+ delete controlToSave.timeline;
279
+ delete controlToSave.unifiedHistory;
280
+ delete controlToSave._metadata;
281
+ delete controlToSave.id;
282
+ yamlContent = yaml2.dump(controlToSave, {
283
+ indent: 2,
284
+ lineWidth: 80,
285
+ noRefs: true,
286
+ sortKeys: false
287
+ });
288
+ }
289
+ writeFileSync(filePath, yamlContent, "utf8");
290
+ this.controlMetadataCache.set(controlId, {
291
+ controlId,
292
+ filename,
293
+ family
294
+ });
295
+ } catch (error) {
296
+ throw new Error(
297
+ `Failed to save control ${controlId}: ${error instanceof Error ? error.message : String(error)}`
298
+ );
299
+ }
300
+ }
301
+ /**
302
+ * Delete a control
303
+ */
304
+ async deleteControl(controlId) {
305
+ const family = this.getControlFamily(controlId);
306
+ const filename = this.getControlFilename(controlId);
307
+ const familyDir = join2(this.controlsDir, family);
308
+ const filePath = join2(familyDir, filename);
309
+ if (existsSync2(filePath)) {
310
+ unlinkSync(filePath);
311
+ this.controlMetadataCache.delete(controlId);
312
+ }
313
+ }
314
+ /**
315
+ * Load all controls
316
+ */
317
+ async loadAllControls() {
318
+ if (!existsSync2(this.controlsDir)) {
319
+ return [];
320
+ }
321
+ const entries = readdirSync(this.controlsDir);
322
+ const yamlFiles = entries.filter((file) => file.endsWith(".yaml"));
323
+ if (yamlFiles.length > 0) {
324
+ const promises = yamlFiles.map(async (file) => {
325
+ try {
326
+ const filePath = join2(this.controlsDir, file);
327
+ const content = await fs.readFile(filePath, "utf8");
328
+ const parsed = yaml2.load(content);
329
+ if (!parsed.id) {
330
+ parsed.id = getControlId(parsed, this.baseDir);
331
+ }
332
+ return parsed;
333
+ } catch (error) {
334
+ console.error(`Failed to load control from file ${file}:`, error);
335
+ return null;
336
+ }
337
+ });
338
+ const results2 = await Promise.all(promises);
339
+ return results2.filter((c) => c !== null);
340
+ }
341
+ const families = entries.filter((name) => {
342
+ const familyPath = join2(this.controlsDir, name);
343
+ return statSync(familyPath).isDirectory();
344
+ });
345
+ const allPromises = [];
346
+ for (const family of families) {
347
+ const familyPath = join2(this.controlsDir, family);
348
+ const files = readdirSync(familyPath).filter((file) => file.endsWith(".yaml"));
349
+ const familyPromises = files.map(async (file) => {
350
+ try {
351
+ const controlId = file.replace(".yaml", "");
352
+ const control = await this.loadControl(controlId);
353
+ return control;
354
+ } catch (error) {
355
+ console.error(`Failed to load control from file ${file}:`, error);
356
+ return null;
357
+ }
358
+ });
359
+ allPromises.push(...familyPromises);
360
+ }
361
+ const results = await Promise.all(allPromises);
362
+ return results.filter((c) => c !== null);
363
+ }
364
+ /**
365
+ * Load mappings from mappings directory
366
+ */
367
+ async loadMappings() {
368
+ const mappings = [];
369
+ if (!existsSync2(this.mappingsDir)) {
370
+ return mappings;
371
+ }
372
+ const families = readdirSync(this.mappingsDir).filter((name) => {
373
+ const familyPath = join2(this.mappingsDir, name);
374
+ return statSync(familyPath).isDirectory();
375
+ });
376
+ for (const family of families) {
377
+ const familyPath = join2(this.mappingsDir, family);
378
+ const files = readdirSync(familyPath).filter((file) => file.endsWith("-mappings.yaml"));
379
+ for (const file of files) {
380
+ const mappingFile = join2(familyPath, file);
381
+ try {
382
+ const content = readFileSync2(mappingFile, "utf8");
383
+ const parsed = yaml2.load(content);
384
+ if (Array.isArray(parsed)) {
385
+ mappings.push(...parsed);
386
+ }
387
+ } catch (error) {
388
+ console.error(`Failed to load mappings from ${family}/${file}:`, error);
389
+ }
390
+ }
391
+ }
392
+ return mappings;
393
+ }
394
+ /**
395
+ * Save a single mapping
396
+ */
397
+ async saveMapping(mapping) {
398
+ this.ensureDirectories();
399
+ const controlId = mapping.control_id;
400
+ const family = this.getControlFamily(controlId);
401
+ const familyDir = join2(this.mappingsDir, family);
402
+ const mappingFile = join2(familyDir, `${controlId}-mappings.yaml`);
403
+ if (!existsSync2(familyDir)) {
404
+ mkdirSync(familyDir, { recursive: true });
405
+ }
406
+ let existingMappings = [];
407
+ if (existsSync2(mappingFile)) {
408
+ try {
409
+ const content = readFileSync2(mappingFile, "utf8");
410
+ existingMappings = yaml2.load(content) || [];
411
+ } catch (error) {
412
+ console.error(`Failed to parse existing mappings file: ${mappingFile}`, error);
413
+ existingMappings = [];
414
+ }
415
+ }
416
+ const existingIndex = existingMappings.findIndex((m) => m.uuid === mapping.uuid);
417
+ if (existingIndex >= 0) {
418
+ existingMappings[existingIndex] = mapping;
419
+ } else {
420
+ existingMappings.push(mapping);
421
+ }
422
+ try {
423
+ const yamlContent = yaml2.dump(existingMappings, {
424
+ indent: 2,
425
+ lineWidth: -1,
426
+ noRefs: true
427
+ });
428
+ writeFileSync(mappingFile, yamlContent, "utf8");
429
+ } catch (error) {
430
+ throw new Error(
431
+ `Failed to save mapping for control ${controlId}: ${error instanceof Error ? error.message : String(error)}`
432
+ );
433
+ }
434
+ }
435
+ /**
436
+ * Delete a single mapping
437
+ */
438
+ async deleteMapping(uuid) {
439
+ const mappingFiles = this.getAllMappingFiles();
440
+ for (const file of mappingFiles) {
441
+ try {
442
+ const content = readFileSync2(file, "utf8");
443
+ let mappings = yaml2.load(content) || [];
444
+ const originalLength = mappings.length;
445
+ mappings = mappings.filter((m) => m.uuid !== uuid);
446
+ if (mappings.length < originalLength) {
447
+ if (mappings.length === 0) {
448
+ unlinkSync(file);
449
+ } else {
450
+ const yamlContent = yaml2.dump(mappings, {
451
+ indent: 2,
452
+ lineWidth: -1,
453
+ noRefs: true
454
+ });
455
+ writeFileSync(file, yamlContent, "utf8");
456
+ }
457
+ return;
458
+ }
459
+ } catch (error) {
460
+ console.error(`Error processing mapping file ${file}:`, error);
461
+ }
462
+ }
463
+ }
464
+ /**
465
+ * Get all mapping files
466
+ */
467
+ getAllMappingFiles() {
468
+ const files = [];
469
+ if (!existsSync2(this.mappingsDir)) {
470
+ return files;
471
+ }
472
+ const flatFiles = readdirSync(this.mappingsDir).filter((file) => file.endsWith("-mappings.yaml")).map((file) => join2(this.mappingsDir, file));
473
+ files.push(...flatFiles);
474
+ const entries = readdirSync(this.mappingsDir, { withFileTypes: true });
475
+ for (const entry of entries) {
476
+ if (entry.isDirectory()) {
477
+ const familyDir = join2(this.mappingsDir, entry.name);
478
+ const familyFiles = readdirSync(familyDir).filter((file) => file.endsWith("-mappings.yaml")).map((file) => join2(familyDir, file));
479
+ files.push(...familyFiles);
480
+ }
481
+ }
482
+ return files;
483
+ }
484
+ /**
485
+ * Save mappings to per-control files
486
+ */
487
+ async saveMappings(mappings) {
488
+ this.ensureDirectories();
489
+ const mappingsByControl = /* @__PURE__ */ new Map();
490
+ for (const mapping of mappings) {
491
+ const controlId = mapping.control_id;
492
+ if (!mappingsByControl.has(controlId)) {
493
+ mappingsByControl.set(controlId, []);
494
+ }
495
+ mappingsByControl.get(controlId).push(mapping);
496
+ }
497
+ for (const [controlId, controlMappings] of mappingsByControl) {
498
+ const family = this.getControlFamily(controlId);
499
+ const familyDir = join2(this.mappingsDir, family);
500
+ const mappingFile = join2(familyDir, `${controlId}-mappings.yaml`);
501
+ if (!existsSync2(familyDir)) {
502
+ mkdirSync(familyDir, { recursive: true });
503
+ }
504
+ try {
505
+ const yamlContent = yaml2.dump(controlMappings, {
506
+ indent: 2,
507
+ lineWidth: -1,
508
+ noRefs: true
509
+ });
510
+ writeFileSync(mappingFile, yamlContent, "utf8");
511
+ } catch (error) {
512
+ throw new Error(
513
+ `Failed to save mappings for control ${controlId}: ${error instanceof Error ? error.message : String(error)}`
514
+ );
515
+ }
516
+ }
517
+ }
518
+ /**
519
+ * Refresh controls cache
520
+ */
521
+ refreshControlsCache() {
522
+ this.controlMetadataCache.clear();
523
+ if (!existsSync2(this.controlsDir)) {
524
+ return;
525
+ }
526
+ const entries = readdirSync(this.controlsDir);
527
+ const yamlFiles = entries.filter((file) => file.endsWith(".yaml"));
528
+ if (yamlFiles.length > 0) {
529
+ for (const filename of yamlFiles) {
530
+ const controlId = filename.replace(".yaml", "");
531
+ const family = this.getControlFamily(controlId);
532
+ this.controlMetadataCache.set(controlId, {
533
+ controlId,
534
+ filename,
535
+ family
536
+ });
537
+ }
538
+ return;
539
+ }
540
+ const families = entries.filter((name) => {
541
+ const familyPath = join2(this.controlsDir, name);
542
+ return statSync(familyPath).isDirectory();
543
+ });
544
+ for (const family of families) {
545
+ const familyPath = join2(this.controlsDir, family);
546
+ const files = readdirSync(familyPath).filter((file) => file.endsWith(".yaml"));
547
+ for (const filename of files) {
548
+ try {
549
+ const filePath = join2(familyPath, filename);
550
+ const content = readFileSync2(filePath, "utf8");
551
+ const parsed = yaml2.load(content);
552
+ const controlId = getControlId(parsed, this.baseDir);
553
+ this.controlMetadataCache.set(controlId, {
554
+ controlId,
555
+ filename,
556
+ family
557
+ });
558
+ } catch (error) {
559
+ console.error(`Failed to read control metadata from ${family}/${filename}:`, error);
560
+ const controlId = filename.replace(".yaml", "").replace(/_/g, "/");
561
+ this.controlMetadataCache.set(controlId, {
562
+ controlId,
563
+ filename,
564
+ family
565
+ });
566
+ }
567
+ }
568
+ }
569
+ }
570
+ /**
571
+ * Get file store statistics
572
+ */
573
+ getStats() {
574
+ const controlCount = this.controlMetadataCache.size;
575
+ let mappingCount = 0;
576
+ if (existsSync2(this.mappingsDir)) {
577
+ const families = readdirSync(this.mappingsDir).filter((name) => {
578
+ const familyPath = join2(this.mappingsDir, name);
579
+ return statSync(familyPath).isDirectory();
580
+ });
581
+ mappingCount = families.length;
582
+ }
583
+ const familyCount = new Set(
584
+ Array.from(this.controlMetadataCache.values()).map((meta) => meta.family)
585
+ ).size;
586
+ return {
587
+ controlCount,
588
+ mappingCount,
589
+ familyCount
590
+ };
591
+ }
592
+ /**
593
+ * Clear all caches
594
+ */
595
+ clearCache() {
596
+ this.controlMetadataCache.clear();
597
+ this.refreshControlsCache();
598
+ }
599
+ };
600
+ }
601
+ });
602
+
603
+ // cli/server/infrastructure/yamlDiff.ts
604
+ import * as yaml3 from "js-yaml";
605
+ function createYamlDiff(oldYaml, newYaml, isArrayFile = false) {
606
+ try {
607
+ const emptyDefault = isArrayFile ? "[]" : "{}";
608
+ const oldData = yaml3.load(oldYaml || emptyDefault);
609
+ const newData = yaml3.load(newYaml || emptyDefault);
610
+ const changes = compareValues(oldData, newData, "");
611
+ return {
612
+ hasChanges: changes.length > 0,
613
+ changes,
614
+ summary: generateSummary(changes)
615
+ };
616
+ } catch (error) {
617
+ console.error("Error parsing YAML for diff:", error);
618
+ return {
619
+ hasChanges: false,
620
+ changes: [],
621
+ summary: "Error parsing YAML content"
622
+ };
623
+ }
624
+ }
625
+ function compareValues(oldValue, newValue, basePath) {
626
+ const changes = [];
627
+ if (oldValue === null || oldValue === void 0) {
628
+ if (newValue !== null && newValue !== void 0) {
629
+ changes.push({
630
+ type: "added",
631
+ path: basePath || "root",
632
+ newValue,
633
+ description: `Added ${basePath || "content"}`
634
+ });
635
+ }
636
+ return changes;
637
+ }
638
+ if (newValue === null || newValue === void 0) {
639
+ changes.push({
640
+ type: "removed",
641
+ path: basePath || "root",
642
+ oldValue,
643
+ description: `Removed ${basePath || "content"}`
644
+ });
645
+ return changes;
646
+ }
647
+ if (Array.isArray(oldValue) || Array.isArray(newValue)) {
648
+ return compareArrays(oldValue, newValue, basePath);
649
+ }
650
+ if (typeof oldValue === "object" && typeof newValue === "object") {
651
+ return compareObjects(oldValue, newValue, basePath);
652
+ }
653
+ if (oldValue !== newValue) {
654
+ changes.push({
655
+ type: "modified",
656
+ path: basePath || "root",
657
+ oldValue,
658
+ newValue,
659
+ description: `Changed ${basePath || "value"}`
660
+ });
661
+ }
662
+ return changes;
663
+ }
664
+ function compareObjects(oldObj, newObj, basePath) {
665
+ const changes = [];
666
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(oldObj), ...Object.keys(newObj)]);
667
+ for (const key of allKeys) {
668
+ const currentPath = basePath ? `${basePath}.${key}` : key;
669
+ const oldValue = oldObj[key];
670
+ const newValue = newObj[key];
671
+ if (!(key in oldObj)) {
672
+ changes.push({
673
+ type: "added",
674
+ path: currentPath,
675
+ newValue,
676
+ description: `Added ${key}`
677
+ });
678
+ } else if (!(key in newObj)) {
679
+ changes.push({
680
+ type: "removed",
681
+ path: currentPath,
682
+ oldValue,
683
+ description: `Removed ${key}`
684
+ });
685
+ } else if (!deepEqual(oldValue, newValue)) {
686
+ if (typeof oldValue === "object" && typeof newValue === "object") {
687
+ changes.push(...compareValues(oldValue, newValue, currentPath));
688
+ } else {
689
+ changes.push({
690
+ type: "modified",
691
+ path: currentPath,
692
+ oldValue,
693
+ newValue,
694
+ description: `Changed ${key}`
695
+ });
696
+ }
697
+ }
698
+ }
699
+ return changes;
700
+ }
701
+ function compareArrays(oldArr, newArr, basePath) {
702
+ const changes = [];
703
+ if (!Array.isArray(oldArr) && Array.isArray(newArr)) {
704
+ changes.push({
705
+ type: "modified",
706
+ path: basePath || "root",
707
+ oldValue: oldArr,
708
+ newValue: newArr,
709
+ description: `Changed ${basePath || "value"} from non-array to array`
710
+ });
711
+ return changes;
712
+ }
713
+ if (Array.isArray(oldArr) && !Array.isArray(newArr)) {
714
+ changes.push({
715
+ type: "modified",
716
+ path: basePath || "root",
717
+ oldValue: oldArr,
718
+ newValue: newArr,
719
+ description: `Changed ${basePath || "value"} from array to non-array`
720
+ });
721
+ return changes;
722
+ }
723
+ const oldArray = oldArr;
724
+ const newArray = newArr;
725
+ if (isMappingArray(oldArray) || isMappingArray(newArray)) {
726
+ return compareMappingArrays(oldArray, newArray, basePath);
727
+ }
728
+ if (oldArray.length !== newArray.length) {
729
+ changes.push({
730
+ type: "modified",
731
+ path: basePath || "root",
732
+ oldValue: oldArray,
733
+ newValue: newArray,
734
+ description: `Array ${basePath || "items"} changed from ${oldArray.length} to ${newArray.length} items`
735
+ });
736
+ } else {
737
+ for (let i = 0; i < oldArray.length; i++) {
738
+ const elementPath = `${basePath}[${i}]`;
739
+ if (!deepEqual(oldArray[i], newArray[i])) {
740
+ changes.push(...compareValues(oldArray[i], newArray[i], elementPath));
741
+ }
742
+ }
743
+ }
744
+ return changes;
745
+ }
746
+ function isMappingArray(arr) {
747
+ if (!Array.isArray(arr) || arr.length === 0) return false;
748
+ const firstItem = arr[0];
749
+ return typeof firstItem === "object" && firstItem !== null && "control_id" in firstItem && "uuid" in firstItem;
750
+ }
751
+ function compareMappingArrays(oldArr, newArr, basePath) {
752
+ const changes = [];
753
+ const oldMappings = /* @__PURE__ */ new Map();
754
+ const newMappings = /* @__PURE__ */ new Map();
755
+ for (const item of oldArr) {
756
+ if (typeof item === "object" && item !== null && "uuid" in item) {
757
+ oldMappings.set(item.uuid, item);
758
+ }
759
+ }
760
+ for (const item of newArr) {
761
+ if (typeof item === "object" && item !== null && "uuid" in item) {
762
+ newMappings.set(item.uuid, item);
763
+ }
764
+ }
765
+ for (const [uuid, mapping] of newMappings) {
766
+ if (!oldMappings.has(uuid)) {
767
+ changes.push({
768
+ type: "added",
769
+ path: `mapping`,
770
+ newValue: mapping,
771
+ description: `Added mapping`
772
+ });
773
+ }
774
+ }
775
+ for (const [uuid, mapping] of oldMappings) {
776
+ if (!newMappings.has(uuid)) {
777
+ changes.push({
778
+ type: "removed",
779
+ path: `mapping`,
780
+ oldValue: mapping,
781
+ description: `Removed mapping`
782
+ });
783
+ }
784
+ }
785
+ for (const [uuid, oldMapping] of oldMappings) {
786
+ if (newMappings.has(uuid)) {
787
+ const newMapping = newMappings.get(uuid);
788
+ if (!deepEqual(oldMapping, newMapping)) {
789
+ changes.push({
790
+ type: "modified",
791
+ path: `mapping`,
792
+ oldValue: oldMapping,
793
+ newValue: newMapping,
794
+ description: `Modified mapping`
795
+ });
796
+ }
797
+ }
798
+ }
799
+ if (changes.length === 0 && oldArr.length !== newArr.length) {
800
+ changes.push({
801
+ type: "modified",
802
+ path: basePath || "mappings",
803
+ oldValue: oldArr,
804
+ newValue: newArr,
805
+ description: `Mappings changed from ${oldArr.length} to ${newArr.length} items`
806
+ });
807
+ }
808
+ return changes;
809
+ }
810
+ function deepEqual(a, b) {
811
+ if (a === b) return true;
812
+ if (a === null || b === null) return false;
813
+ if (typeof a !== typeof b) return false;
814
+ if (Array.isArray(a) && Array.isArray(b)) {
815
+ if (a.length !== b.length) return false;
816
+ for (let i = 0; i < a.length; i++) {
817
+ if (!deepEqual(a[i], b[i])) return false;
818
+ }
819
+ return true;
820
+ }
821
+ if (typeof a === "object" && typeof b === "object") {
822
+ const aObj = a;
823
+ const bObj = b;
824
+ const aKeys = Object.keys(aObj);
825
+ const bKeys = Object.keys(bObj);
826
+ if (aKeys.length !== bKeys.length) return false;
827
+ for (const key of aKeys) {
828
+ if (!bKeys.includes(key)) return false;
829
+ if (!deepEqual(aObj[key], bObj[key])) return false;
830
+ }
831
+ return true;
832
+ }
833
+ return false;
834
+ }
835
+ function generateSummary(changes) {
836
+ if (changes.length === 0) {
837
+ return "No changes detected";
838
+ }
839
+ const added = changes.filter((c) => c.type === "added").length;
840
+ const removed = changes.filter((c) => c.type === "removed").length;
841
+ const modified = changes.filter((c) => c.type === "modified").length;
842
+ const parts = [];
843
+ if (added > 0) parts.push(`${added} added`);
844
+ if (removed > 0) parts.push(`${removed} removed`);
845
+ if (modified > 0) parts.push(`${modified} modified`);
846
+ return parts.join(", ");
847
+ }
848
+ var init_yamlDiff = __esm({
849
+ "cli/server/infrastructure/yamlDiff.ts"() {
850
+ "use strict";
851
+ }
852
+ });
853
+
854
+ // cli/server/infrastructure/gitHistory.ts
855
+ var gitHistory_exports = {};
856
+ __export(gitHistory_exports, {
857
+ GitHistoryUtil: () => GitHistoryUtil
858
+ });
859
+ import * as fs2 from "fs";
860
+ import * as git from "isomorphic-git";
861
+ import { relative } from "path";
862
+ var GitHistoryUtil;
863
+ var init_gitHistory = __esm({
864
+ "cli/server/infrastructure/gitHistory.ts"() {
865
+ "use strict";
866
+ init_yamlDiff();
867
+ GitHistoryUtil = class {
868
+ baseDir;
869
+ constructor(baseDir) {
870
+ this.baseDir = baseDir;
871
+ }
872
+ /**
873
+ * Check if the directory is a git repository
874
+ */
875
+ async isGitRepository() {
876
+ try {
877
+ const gitDir = await git.findRoot({ fs: fs2, filepath: process.cwd() });
878
+ return !!gitDir;
879
+ } catch {
880
+ return false;
881
+ }
882
+ }
883
+ /**
884
+ * Get git history for a specific file
885
+ */
886
+ async getFileHistory(filePath, limit = 50) {
887
+ const isGitRepo = await this.isGitRepository();
888
+ if (!isGitRepo) {
889
+ return {
890
+ filePath,
891
+ commits: [],
892
+ totalCommits: 0,
893
+ firstCommit: null,
894
+ lastCommit: null
895
+ };
896
+ }
897
+ try {
898
+ const gitRoot = await git.findRoot({ fs: fs2, filepath: process.cwd() });
899
+ const relativePath = relative(gitRoot, filePath);
900
+ const commits = await git.log({
901
+ fs: fs2,
902
+ dir: gitRoot,
903
+ filepath: relativePath,
904
+ depth: limit
905
+ });
906
+ if (!commits || commits.length === 0) {
907
+ return {
908
+ filePath,
909
+ commits: [],
910
+ totalCommits: 0,
911
+ firstCommit: null,
912
+ lastCommit: null
913
+ };
914
+ }
915
+ const gitCommits = await this.convertIsomorphicCommits(commits, relativePath, gitRoot);
916
+ return {
917
+ filePath,
918
+ commits: gitCommits,
919
+ totalCommits: gitCommits.length,
920
+ firstCommit: gitCommits[gitCommits.length - 1] || null,
921
+ lastCommit: gitCommits[0] || null
922
+ };
923
+ } catch (error) {
924
+ const err = error;
925
+ if (err?.code === "NotFoundError" || err?.message?.includes("Could not find file")) {
926
+ return {
927
+ filePath,
928
+ commits: [],
929
+ totalCommits: 0,
930
+ firstCommit: null,
931
+ lastCommit: null
932
+ };
933
+ }
934
+ console.error(`Unexpected error getting git history for ${filePath}:`, error);
935
+ return {
936
+ filePath,
937
+ commits: [],
938
+ totalCommits: 0,
939
+ firstCommit: null,
940
+ lastCommit: null
941
+ };
942
+ }
943
+ }
944
+ /**
945
+ * Get the total number of commits for a file
946
+ */
947
+ async getFileCommitCount(filePath) {
948
+ const isGitRepo = await this.isGitRepository();
949
+ if (!isGitRepo) {
950
+ return 0;
951
+ }
952
+ try {
953
+ const gitRoot = await git.findRoot({ fs: fs2, filepath: process.cwd() });
954
+ const relativePath = relative(gitRoot, filePath);
955
+ const commits = await git.log({
956
+ fs: fs2,
957
+ dir: gitRoot,
958
+ filepath: relativePath
959
+ });
960
+ return commits.length;
961
+ } catch {
962
+ return 0;
963
+ }
964
+ }
965
+ /**
966
+ * Get the latest commit info for a file
967
+ */
968
+ async getLatestCommit(filePath) {
969
+ const history = await this.getFileHistory(filePath, 1);
970
+ return history.lastCommit;
971
+ }
972
+ /**
973
+ * Get file content at a specific commit (public method)
974
+ */
975
+ async getFileContentAtCommit(filePath, commitHash) {
976
+ const isGitRepo = await this.isGitRepository();
977
+ if (!isGitRepo) {
978
+ return null;
979
+ }
980
+ try {
981
+ const gitRoot = await git.findRoot({ fs: fs2, filepath: process.cwd() });
982
+ const relativePath = relative(gitRoot, filePath);
983
+ return await this.getFileAtCommit(commitHash, relativePath, gitRoot);
984
+ } catch (error) {
985
+ console.error(`Error getting file content at commit ${commitHash}:`, error);
986
+ return null;
987
+ }
988
+ }
989
+ /**
990
+ * Convert isomorphic-git commits to our GitCommit format
991
+ */
992
+ async convertIsomorphicCommits(commits, relativePath, gitRoot) {
993
+ const gitCommits = [];
994
+ for (let i = 0; i < commits.length; i++) {
995
+ const commit = commits[i];
996
+ const includeDiff = i < 5;
997
+ let changes = { insertions: 0, deletions: 0, files: 1 };
998
+ let diff;
999
+ let yamlDiff;
1000
+ if (includeDiff) {
1001
+ try {
1002
+ const diffResult = await this.getCommitDiff(commit.oid, relativePath, gitRoot);
1003
+ changes = diffResult.changes;
1004
+ diff = diffResult.diff;
1005
+ yamlDiff = diffResult.yamlDiff;
1006
+ } catch (error) {
1007
+ }
1008
+ }
1009
+ gitCommits.push({
1010
+ hash: commit.oid,
1011
+ shortHash: commit.oid.substring(0, 7),
1012
+ author: commit.commit.author.name,
1013
+ authorEmail: commit.commit.author.email,
1014
+ date: new Date(commit.commit.author.timestamp * 1e3).toISOString(),
1015
+ message: commit.commit.message,
1016
+ changes,
1017
+ ...diff && { diff },
1018
+ ...yamlDiff && { yamlDiff }
1019
+ });
1020
+ }
1021
+ return gitCommits;
1022
+ }
1023
+ /**
1024
+ * Get diff for a specific commit and file
1025
+ */
1026
+ async getCommitDiff(commitOid, relativePath, gitRoot) {
1027
+ try {
1028
+ const commit = await git.readCommit({ fs: fs2, dir: gitRoot, oid: commitOid });
1029
+ const parentOid = commit.commit.parent.length > 0 ? commit.commit.parent[0] : null;
1030
+ if (!parentOid) {
1031
+ const currentContent2 = await this.getFileAtCommit(commitOid, relativePath, gitRoot);
1032
+ if (currentContent2) {
1033
+ const lines = currentContent2.split("\n");
1034
+ const isMappingFile2 = relativePath.includes("-mappings.yaml");
1035
+ const yamlDiff2 = createYamlDiff("", currentContent2, isMappingFile2);
1036
+ return {
1037
+ changes: { insertions: lines.length, deletions: 0, files: 1 },
1038
+ diff: `--- /dev/null
1039
+ +++ b/${relativePath}
1040
+ @@ -0,0 +1,${lines.length} @@
1041
+ ` + lines.map((line) => "+" + line).join("\n"),
1042
+ yamlDiff: yamlDiff2
1043
+ };
1044
+ }
1045
+ return { changes: { insertions: 0, deletions: 0, files: 1 } };
1046
+ }
1047
+ const currentContent = await this.getFileAtCommit(commitOid, relativePath, gitRoot);
1048
+ const parentContent = await this.getFileAtCommit(parentOid, relativePath, gitRoot);
1049
+ if (!currentContent && !parentContent) {
1050
+ return { changes: { insertions: 0, deletions: 0, files: 1 } };
1051
+ }
1052
+ const currentLines = currentContent ? currentContent.split("\n") : [];
1053
+ const parentLines = parentContent ? parentContent.split("\n") : [];
1054
+ const diff = this.createSimpleDiff(parentLines, currentLines, relativePath);
1055
+ const { insertions, deletions } = this.countChanges(parentLines, currentLines);
1056
+ const isMappingFile = relativePath.includes("-mappings.yaml");
1057
+ const yamlDiff = createYamlDiff(parentContent || "", currentContent || "", isMappingFile);
1058
+ return {
1059
+ changes: { insertions, deletions, files: 1 },
1060
+ diff,
1061
+ yamlDiff
1062
+ };
1063
+ } catch (error) {
1064
+ return { changes: { insertions: 0, deletions: 0, files: 1 } };
1065
+ }
1066
+ }
1067
+ /**
1068
+ * Get file content at a specific commit
1069
+ */
1070
+ async getFileAtCommit(commitOid, filepath, gitRoot) {
1071
+ try {
1072
+ const { blob } = await git.readBlob({
1073
+ fs: fs2,
1074
+ dir: gitRoot,
1075
+ oid: commitOid,
1076
+ filepath
1077
+ });
1078
+ return new TextDecoder().decode(blob);
1079
+ } catch (_error) {
1080
+ return null;
1081
+ }
1082
+ }
1083
+ /**
1084
+ * Create a simple unified diff between two file versions
1085
+ */
1086
+ createSimpleDiff(oldLines, newLines, filepath) {
1087
+ const diffLines = [];
1088
+ diffLines.push(`--- a/${filepath}`);
1089
+ diffLines.push(`+++ b/${filepath}`);
1090
+ const oldCount = oldLines.length;
1091
+ const newCount = newLines.length;
1092
+ diffLines.push(`@@ -1,${oldCount} +1,${newCount} @@`);
1093
+ let i = 0, j = 0;
1094
+ while (i < oldLines.length || j < newLines.length) {
1095
+ if (i < oldLines.length && j < newLines.length && oldLines[i] === newLines[j]) {
1096
+ diffLines.push(` ${oldLines[i]}`);
1097
+ i++;
1098
+ j++;
1099
+ } else if (i < oldLines.length && (j >= newLines.length || oldLines[i] !== newLines[j])) {
1100
+ diffLines.push(`-${oldLines[i]}`);
1101
+ i++;
1102
+ } else if (j < newLines.length) {
1103
+ diffLines.push(`+${newLines[j]}`);
1104
+ j++;
1105
+ }
1106
+ }
1107
+ return diffLines.join("\n");
1108
+ }
1109
+ /**
1110
+ * Count insertions and deletions between two file versions
1111
+ */
1112
+ countChanges(oldLines, newLines) {
1113
+ let insertions = 0;
1114
+ let deletions = 0;
1115
+ const maxLines = Math.max(oldLines.length, newLines.length);
1116
+ for (let i = 0; i < maxLines; i++) {
1117
+ const oldLine = i < oldLines.length ? oldLines[i] : null;
1118
+ const newLine = i < newLines.length ? newLines[i] : null;
1119
+ if (oldLine === null) {
1120
+ insertions++;
1121
+ } else if (newLine === null) {
1122
+ deletions++;
1123
+ } else if (oldLine !== newLine) {
1124
+ insertions++;
1125
+ deletions++;
1126
+ }
1127
+ }
1128
+ return { insertions, deletions };
1129
+ }
1130
+ /**
1131
+ * Get git stats for the entire repository
1132
+ */
1133
+ async getRepositoryStats() {
1134
+ const isGitRepo = await this.isGitRepository();
1135
+ if (!isGitRepo) {
1136
+ return {
1137
+ totalCommits: 0,
1138
+ contributors: 0,
1139
+ lastCommitDate: null,
1140
+ firstCommitDate: null
1141
+ };
1142
+ }
1143
+ try {
1144
+ const gitRoot = await git.findRoot({ fs: fs2, filepath: process.cwd() });
1145
+ const commits = await git.log({ fs: fs2, dir: gitRoot });
1146
+ const contributorEmails = /* @__PURE__ */ new Set();
1147
+ commits.forEach((commit) => {
1148
+ contributorEmails.add(commit.commit.author.email);
1149
+ });
1150
+ const firstCommit = commits[commits.length - 1];
1151
+ const lastCommit = commits[0];
1152
+ return {
1153
+ totalCommits: commits.length,
1154
+ contributors: contributorEmails.size,
1155
+ lastCommitDate: lastCommit ? new Date(lastCommit.commit.author.timestamp * 1e3).toISOString() : null,
1156
+ firstCommitDate: firstCommit ? new Date(firstCommit.commit.author.timestamp * 1e3).toISOString() : null
1157
+ };
1158
+ } catch (error) {
1159
+ console.error("Error getting repository stats:", error);
1160
+ return {
1161
+ totalCommits: 0,
1162
+ contributors: 0,
1163
+ lastCommitDate: null,
1164
+ firstCommitDate: null
1165
+ };
1166
+ }
1167
+ }
1168
+ };
1169
+ }
1170
+ });
1171
+
1172
+ // cli/server/serverState.ts
1173
+ var serverState_exports = {};
1174
+ __export(serverState_exports, {
1175
+ addControlToIndexes: () => addControlToIndexes,
1176
+ addMappingToIndexes: () => addMappingToIndexes,
1177
+ getCurrentControlSetPath: () => getCurrentControlSetPath,
1178
+ getServerState: () => getServerState,
1179
+ initializeServerState: () => initializeServerState,
1180
+ loadAllData: () => loadAllData,
1181
+ saveMappingsToFile: () => saveMappingsToFile
1182
+ });
1183
+ import { join as join3 } from "path";
1184
+ function initializeServerState(controlSetDir, subdir = ".") {
1185
+ const fullPath = subdir === "." ? controlSetDir : join3(controlSetDir, subdir);
1186
+ serverState = {
1187
+ CONTROL_SET_DIR: controlSetDir,
1188
+ currentSubdir: subdir,
1189
+ fileStore: new FileStore({ baseDir: fullPath }),
1190
+ gitHistory: new GitHistoryUtil(fullPath),
1191
+ controlsCache: /* @__PURE__ */ new Map(),
1192
+ mappingsCache: /* @__PURE__ */ new Map(),
1193
+ controlsByFamily: /* @__PURE__ */ new Map(),
1194
+ mappingsByFamily: /* @__PURE__ */ new Map(),
1195
+ mappingsByControl: /* @__PURE__ */ new Map()
1196
+ };
1197
+ return serverState;
1198
+ }
1199
+ function getServerState() {
1200
+ if (!serverState) {
1201
+ throw new Error("Server state not initialized. Call initializeServerState() first.");
1202
+ }
1203
+ return serverState;
1204
+ }
1205
+ function getCurrentControlSetPath() {
1206
+ const state = getServerState();
1207
+ return state.currentSubdir === "." ? state.CONTROL_SET_DIR : join3(state.CONTROL_SET_DIR, state.currentSubdir);
1208
+ }
1209
+ function addControlToIndexes(control) {
1210
+ const state = getServerState();
1211
+ const family = control.family;
1212
+ if (!family) {
1213
+ return;
1214
+ }
1215
+ if (!state.controlsByFamily.has(family)) {
1216
+ state.controlsByFamily.set(family, /* @__PURE__ */ new Set());
1217
+ }
1218
+ state.controlsByFamily.get(family).add(control.id);
1219
+ }
1220
+ function addMappingToIndexes(mapping) {
1221
+ const state = getServerState();
1222
+ const family = mapping.control_id.split("-")[0];
1223
+ if (!state.mappingsByFamily.has(family)) {
1224
+ state.mappingsByFamily.set(family, /* @__PURE__ */ new Set());
1225
+ }
1226
+ state.mappingsByFamily.get(family).add(mapping.uuid);
1227
+ if (!state.mappingsByControl.has(mapping.control_id)) {
1228
+ state.mappingsByControl.set(mapping.control_id, /* @__PURE__ */ new Set());
1229
+ }
1230
+ state.mappingsByControl.get(mapping.control_id).add(mapping.uuid);
1231
+ }
1232
+ async function loadAllData() {
1233
+ const state = getServerState();
1234
+ debug("Loading data into memory...");
1235
+ try {
1236
+ const controls = await state.fileStore.loadAllControls();
1237
+ for (const control of controls) {
1238
+ state.controlsCache.set(control.id, control);
1239
+ addControlToIndexes(control);
1240
+ }
1241
+ debug(`Loaded ${controls.length} controls from individual files`);
1242
+ const mappings = await state.fileStore.loadMappings();
1243
+ for (const mapping of mappings) {
1244
+ state.mappingsCache.set(mapping.uuid, mapping);
1245
+ addMappingToIndexes(mapping);
1246
+ }
1247
+ debug(`Loaded ${mappings.length} mappings`);
1248
+ } catch (error) {
1249
+ console.error("Error loading data:", error);
1250
+ }
40
1251
  }
1252
+ async function saveMappingsToFile() {
1253
+ const state = getServerState();
1254
+ try {
1255
+ const allMappings = Array.from(state.mappingsCache.values());
1256
+ await state.fileStore.saveMappings(allMappings);
1257
+ debug(`Saved ${allMappings.length} mappings`);
1258
+ } catch (error) {
1259
+ console.error("Error saving mappings:", error);
1260
+ }
1261
+ }
1262
+ var serverState;
1263
+ var init_serverState = __esm({
1264
+ "cli/server/serverState.ts"() {
1265
+ "use strict";
1266
+ init_debug();
1267
+ init_fileStore();
1268
+ init_gitHistory();
1269
+ serverState = void 0;
1270
+ }
1271
+ });
1272
+
1273
+ // cli/server/spreadsheetRoutes.ts
1274
+ var spreadsheetRoutes_exports = {};
1275
+ __export(spreadsheetRoutes_exports, {
1276
+ default: () => spreadsheetRoutes_default,
1277
+ scanControlSets: () => scanControlSets
1278
+ });
1279
+ import { parse as parseCSVSync } from "csv-parse/sync";
1280
+ import ExcelJS from "exceljs";
1281
+ import express from "express";
1282
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
1283
+ import { glob } from "glob";
1284
+ import * as yaml4 from "js-yaml";
1285
+ import multer from "multer";
1286
+ import { dirname, join as join4, relative as relative2 } from "path";
1287
+ async function scanControlSets() {
1288
+ const state = getServerState();
1289
+ const baseDir = state.CONTROL_SET_DIR;
1290
+ const pattern = "**/lula.yaml";
1291
+ const files = await glob(pattern, {
1292
+ cwd: baseDir,
1293
+ ignore: ["node_modules/**", "dist/**", "build/**"],
1294
+ maxDepth: 5
1295
+ });
1296
+ const controlSets = files.map((file) => {
1297
+ const fullPath = join4(baseDir, file);
1298
+ const dirPath = dirname(fullPath);
1299
+ const relativePath = relative2(baseDir, dirPath) || ".";
1300
+ try {
1301
+ const content = readFileSync3(fullPath, "utf8");
1302
+ const data = yaml4.load(content);
1303
+ if (data.id === "default") {
1304
+ return null;
1305
+ }
1306
+ return {
1307
+ path: relativePath,
1308
+ name: data.name || "Unnamed Control Set",
1309
+ description: data.description || "",
1310
+ controlCount: data.controlCount || 0,
1311
+ file
1312
+ };
1313
+ } catch (_err) {
1314
+ return {
1315
+ path: relativePath,
1316
+ name: "Invalid lula.yaml",
1317
+ description: "Could not parse file",
1318
+ controlCount: 0,
1319
+ file
1320
+ };
1321
+ }
1322
+ }).filter((cs) => cs !== null);
1323
+ return { controlSets };
1324
+ }
1325
+ function applyNamingConvention(fieldName, convention) {
1326
+ if (!fieldName) return fieldName;
1327
+ const cleanedName = fieldName.trim();
1328
+ switch (convention) {
1329
+ case "camelCase":
1330
+ return toCamelCase(cleanedName);
1331
+ case "snake_case":
1332
+ return toSnakeCase(cleanedName);
1333
+ case "kebab-case":
1334
+ return toKebabCase(cleanedName);
1335
+ case "lowercase":
1336
+ return cleanedName.replace(/\W+/g, "").toLowerCase();
1337
+ case "original":
1338
+ return cleanedName;
1339
+ default:
1340
+ return toCamelCase(cleanedName);
1341
+ }
1342
+ }
1343
+ function toCamelCase(str) {
1344
+ return str.replace(/(?:^\w|[A-Z]|\b\w)/g, (word, index) => {
1345
+ return index === 0 ? word.toLowerCase() : word.toUpperCase();
1346
+ }).replace(/\s+/g, "");
1347
+ }
1348
+ function toSnakeCase(str) {
1349
+ return str.replace(/\W+/g, " ").split(/ |\s/).map((word) => word.toLowerCase()).join("_");
1350
+ }
1351
+ function toKebabCase(str) {
1352
+ return str.replace(/\W+/g, " ").split(/ |\s/).map((word) => word.toLowerCase()).join("-");
1353
+ }
1354
+ function detectValueType(value) {
1355
+ if (typeof value === "boolean") return "boolean";
1356
+ if (typeof value === "number") return "number";
1357
+ if (typeof value === "string") {
1358
+ const lowerValue = value.toLowerCase().trim();
1359
+ if (lowerValue === "true" || lowerValue === "false" || lowerValue === "yes" || lowerValue === "no" || lowerValue === "y" || lowerValue === "n") {
1360
+ return "boolean";
1361
+ }
1362
+ if (!isNaN(Number(value)) && value.trim() !== "") {
1363
+ return "number";
1364
+ }
1365
+ const datePatterns = [
1366
+ /^\d{4}-\d{2}-\d{2}$/,
1367
+ // YYYY-MM-DD
1368
+ /^\d{2}\/\d{2}\/\d{4}$/,
1369
+ // MM/DD/YYYY
1370
+ /^\d{1,2}\/\d{1,2}\/\d{2,4}$/
1371
+ // M/D/YY or MM/DD/YYYY
1372
+ ];
1373
+ if (datePatterns.some((pattern) => pattern.test(value))) {
1374
+ return "date";
1375
+ }
1376
+ }
1377
+ return "string";
1378
+ }
1379
+ function parseCSV(content) {
1380
+ try {
1381
+ const records = parseCSVSync(content, {
1382
+ // Don't treat first row as headers - we'll handle that ourselves
1383
+ columns: false,
1384
+ // Skip empty lines
1385
+ skip_empty_lines: true,
1386
+ // Handle different line endings
1387
+ relax_column_count: true,
1388
+ // Trim whitespace from fields
1389
+ trim: true,
1390
+ // Handle quoted fields properly
1391
+ quote: '"',
1392
+ // Standard escape character
1393
+ escape: '"',
1394
+ // Auto-detect delimiter (usually comma)
1395
+ delimiter: ","
1396
+ });
1397
+ return records;
1398
+ } catch (error) {
1399
+ console.error("CSV parsing error:", error);
1400
+ return content.split(/\r?\n/).map((line) => line.split(","));
1401
+ }
1402
+ }
1403
+ function extractFamilyFromControlId(controlId) {
1404
+ if (!controlId) return "UNKNOWN";
1405
+ controlId = controlId.trim();
1406
+ const match = controlId.match(/^([A-Za-z]+)[-._ ]?\d/);
1407
+ if (match) {
1408
+ return match[1].toUpperCase();
1409
+ }
1410
+ const letterMatch = controlId.match(/^([A-Za-z]+)/);
1411
+ if (letterMatch) {
1412
+ return letterMatch[1].toUpperCase();
1413
+ }
1414
+ return controlId.substring(0, 2).toUpperCase();
1415
+ }
1416
+ function exportAsCSV(controls, metadata, res) {
1417
+ const fieldSchema = metadata?.fieldSchema?.fields || {};
1418
+ const controlIdField = metadata?.control_id_field || "id";
1419
+ const allFields = /* @__PURE__ */ new Set();
1420
+ controls.forEach((control) => {
1421
+ Object.keys(control).forEach((key) => allFields.add(key));
1422
+ });
1423
+ const fieldMapping = [];
1424
+ if (allFields.has(controlIdField)) {
1425
+ const idSchema = fieldSchema[controlIdField];
1426
+ fieldMapping.push({
1427
+ fieldName: controlIdField,
1428
+ displayName: idSchema?.original_name || "Control ID"
1429
+ });
1430
+ allFields.delete(controlIdField);
1431
+ } else if (allFields.has("id")) {
1432
+ fieldMapping.push({
1433
+ fieldName: "id",
1434
+ displayName: "Control ID"
1435
+ });
1436
+ allFields.delete("id");
1437
+ }
1438
+ if (allFields.has("family")) {
1439
+ const familySchema = fieldSchema["family"];
1440
+ fieldMapping.push({
1441
+ fieldName: "family",
1442
+ displayName: familySchema?.original_name || "Family"
1443
+ });
1444
+ allFields.delete("family");
1445
+ }
1446
+ Array.from(allFields).filter((field) => field !== "mappings" && field !== "mappings_count").sort().forEach((field) => {
1447
+ const schema = fieldSchema[field];
1448
+ const displayName = schema?.original_name || field.replace(/-/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
1449
+ fieldMapping.push({ fieldName: field, displayName });
1450
+ });
1451
+ if (allFields.has("mappings_count")) {
1452
+ fieldMapping.push({ fieldName: "mappings_count", displayName: "Mappings Count" });
1453
+ }
1454
+ if (allFields.has("mappings")) {
1455
+ fieldMapping.push({ fieldName: "mappings", displayName: "Mappings" });
1456
+ }
1457
+ const csvRows = [];
1458
+ csvRows.push(fieldMapping.map((field) => `"${field.displayName}"`).join(","));
1459
+ controls.forEach((control) => {
1460
+ const row = fieldMapping.map(({ fieldName }) => {
1461
+ const value = control[fieldName];
1462
+ if (value === void 0 || value === null) return '""';
1463
+ if (fieldName === "mappings" && Array.isArray(value)) {
1464
+ const mappingsStr = value.map(
1465
+ (m) => `${m.status}: ${m.description.substring(0, 50)}${m.description.length > 50 ? "..." : ""}`
1466
+ ).join("; ");
1467
+ return `"${mappingsStr.replace(/"/g, '""')}"`;
1468
+ }
1469
+ if (Array.isArray(value)) return `"${value.join("; ").replace(/"/g, '""')}"`;
1470
+ if (typeof value === "object") return `"${JSON.stringify(value).replace(/"/g, '""')}"`;
1471
+ return `"${String(value).replace(/"/g, '""')}"`;
1472
+ });
1473
+ csvRows.push(row.join(","));
1474
+ });
1475
+ const csvContent = csvRows.join("\n");
1476
+ const fileName = `${metadata?.name || "controls"}_export_${Date.now()}.csv`;
1477
+ res.setHeader("Content-Type", "text/csv");
1478
+ res.setHeader("Content-Disposition", `attachment; filename="${fileName}"`);
1479
+ res.send(csvContent);
1480
+ }
1481
+ async function exportAsExcel(controls, metadata, res) {
1482
+ const fieldSchema = metadata?.fieldSchema?.fields || {};
1483
+ const controlIdField = metadata?.control_id_field || "id";
1484
+ const worksheetData = controls.map((control) => {
1485
+ const exportControl = {};
1486
+ if (control[controlIdField]) {
1487
+ const idSchema = fieldSchema[controlIdField];
1488
+ const idDisplayName = idSchema?.original_name || "Control ID";
1489
+ exportControl[idDisplayName] = control[controlIdField];
1490
+ } else if (control.id) {
1491
+ exportControl["Control ID"] = control.id;
1492
+ }
1493
+ if (control.family) {
1494
+ const familySchema = fieldSchema["family"];
1495
+ const familyDisplayName = familySchema?.original_name || "Family";
1496
+ exportControl[familyDisplayName] = control.family;
1497
+ }
1498
+ Object.keys(control).forEach((key) => {
1499
+ if (key === controlIdField || key === "id" || key === "family") return;
1500
+ const schema = fieldSchema[key];
1501
+ const displayName = schema?.original_name || (key === "mappings_count" ? "Mappings Count" : key === "mappings" ? "Mappings" : key.replace(/-/g, " ").replace(/\b\w/g, (l) => l.toUpperCase()));
1502
+ const value = control[key];
1503
+ if (key === "mappings" && Array.isArray(value)) {
1504
+ exportControl[displayName] = value.map(
1505
+ (m) => `${m.status}: ${m.description.substring(0, 100)}${m.description.length > 100 ? "..." : ""}`
1506
+ ).join("\n");
1507
+ } else if (Array.isArray(value)) {
1508
+ exportControl[displayName] = value.join("; ");
1509
+ } else if (typeof value === "object" && value !== null) {
1510
+ exportControl[displayName] = JSON.stringify(value);
1511
+ } else {
1512
+ exportControl[displayName] = value;
1513
+ }
1514
+ });
1515
+ return exportControl;
1516
+ });
1517
+ const wb = new ExcelJS.Workbook();
1518
+ const ws = wb.addWorksheet("Controls");
1519
+ const headers = Object.keys(worksheetData[0] || {});
1520
+ ws.columns = headers.map((header) => ({
1521
+ header,
1522
+ key: header,
1523
+ width: Math.min(
1524
+ Math.max(
1525
+ header.length,
1526
+ ...worksheetData.map((row) => String(row[header] || "").length)
1527
+ ) + 2,
1528
+ 50
1529
+ )
1530
+ // Auto-size with max width of 50
1531
+ }));
1532
+ worksheetData.forEach((row) => {
1533
+ ws.addRow(row);
1534
+ });
1535
+ ws.getRow(1).font = { bold: true };
1536
+ ws.getRow(1).fill = {
1537
+ type: "pattern",
1538
+ pattern: "solid",
1539
+ fgColor: { argb: "FFE0E0E0" }
1540
+ };
1541
+ if (metadata) {
1542
+ const metaSheet = wb.addWorksheet("Metadata");
1543
+ const cleanMetadata = { ...metadata };
1544
+ delete cleanMetadata.fieldSchema;
1545
+ metaSheet.columns = [
1546
+ { header: "Property", key: "property", width: 30 },
1547
+ { header: "Value", key: "value", width: 50 }
1548
+ ];
1549
+ Object.entries(cleanMetadata).forEach(([key, value]) => {
1550
+ metaSheet.addRow({ property: key, value: String(value) });
1551
+ });
1552
+ }
1553
+ const buffer = await wb.xlsx.writeBuffer();
1554
+ const fileName = `${metadata?.name || "controls"}_export_${Date.now()}.xlsx`;
1555
+ res.setHeader(
1556
+ "Content-Type",
1557
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
1558
+ );
1559
+ res.setHeader("Content-Disposition", `attachment; filename="${fileName}"`);
1560
+ res.send(buffer);
1561
+ }
1562
+ function exportAsJSON(controls, metadata, res) {
1563
+ const exportData = {
1564
+ metadata: metadata || {},
1565
+ controlCount: controls.length,
1566
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
1567
+ controls
1568
+ };
1569
+ const fileName = `${metadata?.name || "controls"}_export_${Date.now()}.json`;
1570
+ res.setHeader("Content-Type", "application/json");
1571
+ res.setHeader("Content-Disposition", `attachment; filename="${fileName}"`);
1572
+ res.json(exportData);
1573
+ }
1574
+ var router, upload, spreadsheetRoutes_default;
1575
+ var init_spreadsheetRoutes = __esm({
1576
+ "cli/server/spreadsheetRoutes.ts"() {
1577
+ "use strict";
1578
+ init_debug();
1579
+ init_serverState();
1580
+ router = express.Router();
1581
+ upload = multer({
1582
+ storage: multer.memoryStorage(),
1583
+ limits: { fileSize: 50 * 1024 * 1024 }
1584
+ // 50MB limit
1585
+ });
1586
+ router.post("/import-spreadsheet", upload.single("file"), async (req, res) => {
1587
+ try {
1588
+ if (!req.file) {
1589
+ return res.status(400).json({ error: "No file uploaded" });
1590
+ }
1591
+ const {
1592
+ controlIdField = "Control ID",
1593
+ startRow = "1",
1594
+ controlSetName = "Imported Control Set",
1595
+ controlSetDescription = "Imported from spreadsheet"
1596
+ } = req.body;
1597
+ debug("Import parameters received:", {
1598
+ controlIdField,
1599
+ startRow,
1600
+ controlSetName,
1601
+ controlSetDescription
1602
+ });
1603
+ const namingConvention = "kebab-case";
1604
+ const skipEmpty = true;
1605
+ const skipEmptyRows = true;
1606
+ const fileName = req.file.originalname || "";
1607
+ const isCSV = fileName.toLowerCase().endsWith(".csv");
1608
+ let rawData = [];
1609
+ if (isCSV) {
1610
+ const csvContent = req.file.buffer.toString("utf-8");
1611
+ rawData = parseCSV(csvContent);
1612
+ } else {
1613
+ const workbook = new ExcelJS.Workbook();
1614
+ const buffer = Buffer.from(req.file.buffer);
1615
+ await workbook.xlsx.load(buffer);
1616
+ const worksheet = workbook.worksheets[0];
1617
+ if (!worksheet) {
1618
+ return res.status(400).json({ error: "No worksheet found in file" });
1619
+ }
1620
+ worksheet.eachRow({ includeEmpty: true }, (row, rowNumber) => {
1621
+ const rowData = [];
1622
+ row.eachCell({ includeEmpty: true }, (cell, colNumber) => {
1623
+ rowData[colNumber - 1] = cell.value;
1624
+ });
1625
+ rawData[rowNumber - 1] = rowData;
1626
+ });
1627
+ }
1628
+ const startRowIndex = parseInt(startRow) - 1;
1629
+ if (rawData.length <= startRowIndex) {
1630
+ return res.status(400).json({ error: "Start row exceeds sheet data" });
1631
+ }
1632
+ const headers = rawData[startRowIndex];
1633
+ if (!headers || headers.length === 0) {
1634
+ return res.status(400).json({ error: "No headers found at specified row" });
1635
+ }
1636
+ debug("Headers found:", headers);
1637
+ debug(
1638
+ "After conversion, looking for control ID field:",
1639
+ applyNamingConvention(controlIdField, namingConvention)
1640
+ );
1641
+ const controls = [];
1642
+ const families = /* @__PURE__ */ new Map();
1643
+ const fieldMetadata = /* @__PURE__ */ new Map();
1644
+ headers.forEach((header) => {
1645
+ if (header) {
1646
+ const cleanName = applyNamingConvention(header, namingConvention);
1647
+ fieldMetadata.set(cleanName, {
1648
+ originalName: header,
1649
+ cleanName,
1650
+ type: "string",
1651
+ maxLength: 0,
1652
+ hasMultipleLines: false,
1653
+ uniqueValues: /* @__PURE__ */ new Set(),
1654
+ emptyCount: 0,
1655
+ totalCount: 0,
1656
+ examples: []
1657
+ });
1658
+ }
1659
+ });
1660
+ for (let i = startRowIndex + 1; i < rawData.length; i++) {
1661
+ const row = rawData[i];
1662
+ if (!row || row.length === 0) continue;
1663
+ const control = {};
1664
+ let hasData = false;
1665
+ headers.forEach((header, index) => {
1666
+ if (header && row[index] !== void 0 && row[index] !== null) {
1667
+ const value = typeof row[index] === "string" ? row[index].trim() : row[index];
1668
+ const fieldName = applyNamingConvention(header, namingConvention);
1669
+ const metadata = fieldMetadata.get(fieldName);
1670
+ metadata.totalCount++;
1671
+ if (value === "" || value === null || value === void 0) {
1672
+ metadata.emptyCount++;
1673
+ if (skipEmpty) return;
1674
+ } else {
1675
+ const normalizedValue = typeof value === "string" ? value.trim() : value;
1676
+ if (normalizedValue !== "") {
1677
+ metadata.uniqueValues.add(normalizedValue);
1678
+ }
1679
+ const valueType = detectValueType(value);
1680
+ if (metadata.type === "string" || metadata.totalCount === 1) {
1681
+ metadata.type = valueType;
1682
+ } else if (metadata.type !== valueType) {
1683
+ metadata.type = "mixed";
1684
+ }
1685
+ if (typeof value === "string") {
1686
+ const length = value.length;
1687
+ if (length > metadata.maxLength) {
1688
+ metadata.maxLength = length;
1689
+ }
1690
+ if (value.includes("\n") || length > 100) {
1691
+ metadata.hasMultipleLines = true;
1692
+ }
1693
+ }
1694
+ if (metadata.examples.length < 3 && normalizedValue !== "") {
1695
+ metadata.examples.push(normalizedValue);
1696
+ }
1697
+ }
1698
+ control[fieldName] = value;
1699
+ hasData = true;
1700
+ }
1701
+ });
1702
+ if (hasData && (!skipEmptyRows || Object.keys(control).length > 0)) {
1703
+ const controlIdFieldName = applyNamingConvention(controlIdField, namingConvention);
1704
+ const controlId = control[controlIdFieldName];
1705
+ if (!controlId) {
1706
+ continue;
1707
+ }
1708
+ const family = extractFamilyFromControlId(controlId);
1709
+ control.family = family;
1710
+ controls.push(control);
1711
+ if (!families.has(family)) {
1712
+ families.set(family, []);
1713
+ }
1714
+ families.get(family).push(control);
1715
+ }
1716
+ }
1717
+ const state = getServerState();
1718
+ const folderName = toKebabCase(controlSetName || "imported-controls");
1719
+ const baseDir = join4(state.CONTROL_SET_DIR || process.cwd(), folderName);
1720
+ if (!existsSync3(baseDir)) {
1721
+ mkdirSync2(baseDir, { recursive: true });
1722
+ }
1723
+ const uniqueFamilies = Array.from(families.keys()).filter((f) => f && f !== "UNKNOWN");
1724
+ let frontendFieldSchema = null;
1725
+ if (req.body.fieldSchema) {
1726
+ try {
1727
+ frontendFieldSchema = JSON.parse(req.body.fieldSchema);
1728
+ } catch (e) {
1729
+ }
1730
+ }
1731
+ const fields = {};
1732
+ let displayOrder = 1;
1733
+ const controlIdFieldNameClean = applyNamingConvention(controlIdField, namingConvention);
1734
+ const familyOptions = Array.from(families.keys()).filter((f) => f && f !== "UNKNOWN").sort();
1735
+ fields["family"] = {
1736
+ type: "string",
1737
+ ui_type: familyOptions.length <= 50 ? "select" : "short_text",
1738
+ // Make select if reasonable number of families
1739
+ is_array: false,
1740
+ max_length: 10,
1741
+ usage_count: controls.length,
1742
+ usage_percentage: 100,
1743
+ required: true,
1744
+ visible: true,
1745
+ show_in_table: true,
1746
+ editable: false,
1747
+ display_order: displayOrder++,
1748
+ category: "core",
1749
+ tab: "overview"
1750
+ };
1751
+ if (familyOptions.length <= 50) {
1752
+ fields["family"].options = familyOptions;
1753
+ }
1754
+ fieldMetadata.forEach((metadata, fieldName) => {
1755
+ if (fieldName === "family" || fieldName === "id" && controlIdFieldNameClean !== "id") {
1756
+ return;
1757
+ }
1758
+ const frontendConfig = frontendFieldSchema?.find((f) => f.fieldName === fieldName);
1759
+ if (frontendFieldSchema && !frontendConfig) {
1760
+ return;
1761
+ }
1762
+ const usageCount = metadata.totalCount - metadata.emptyCount;
1763
+ const usagePercentage = metadata.totalCount > 0 ? Math.round(usageCount / metadata.totalCount * 100) : 0;
1764
+ let uiType = "short_text";
1765
+ const nonEmptyCount = metadata.totalCount - metadata.emptyCount;
1766
+ const isDropdownCandidate = metadata.uniqueValues.size > 0 && metadata.uniqueValues.size <= 20 && // Max 20 unique values for dropdown
1767
+ nonEmptyCount >= 10 && // At least 10 non-empty values to be meaningful
1768
+ metadata.maxLength <= 100 && // Reasonably short values only
1769
+ metadata.uniqueValues.size / nonEmptyCount <= 0.3;
1770
+ if (metadata.hasMultipleLines || metadata.maxLength > 500) {
1771
+ uiType = "textarea";
1772
+ } else if (isDropdownCandidate) {
1773
+ uiType = "select";
1774
+ } else if (metadata.type === "boolean") {
1775
+ uiType = "checkbox";
1776
+ } else if (metadata.type === "number") {
1777
+ uiType = "number";
1778
+ } else if (metadata.type === "date") {
1779
+ uiType = "date";
1780
+ } else if (metadata.maxLength <= 50) {
1781
+ uiType = "short_text";
1782
+ } else if (metadata.maxLength <= 200) {
1783
+ uiType = "medium_text";
1784
+ } else {
1785
+ uiType = "long_text";
1786
+ }
1787
+ let category = frontendConfig?.category || "custom";
1788
+ if (!frontendConfig) {
1789
+ if (fieldName.includes("status") || fieldName.includes("state")) {
1790
+ category = "compliance";
1791
+ } else if (fieldName.includes("title") || fieldName.includes("name") || fieldName.includes("description")) {
1792
+ category = "core";
1793
+ } else if (fieldName.includes("note") || fieldName.includes("comment")) {
1794
+ category = "notes";
1795
+ }
1796
+ }
1797
+ const isControlIdField = fieldName === controlIdFieldNameClean;
1798
+ const fieldDef = {
1799
+ type: metadata.type,
1800
+ ui_type: uiType,
1801
+ is_array: false,
1802
+ max_length: metadata.maxLength,
1803
+ usage_count: usageCount,
1804
+ usage_percentage: usagePercentage,
1805
+ required: isControlIdField ? true : frontendConfig?.required ?? usagePercentage > 95,
1806
+ // Control ID is always required
1807
+ visible: frontendConfig?.tab !== "hidden",
1808
+ show_in_table: isControlIdField ? true : metadata.maxLength <= 100 && usagePercentage > 30,
1809
+ // Always show control ID in table
1810
+ editable: isControlIdField ? false : true,
1811
+ // Control ID is not editable
1812
+ display_order: isControlIdField ? 1 : frontendConfig?.displayOrder ?? displayOrder++,
1813
+ // Control ID is always first
1814
+ category: isControlIdField ? "core" : category,
1815
+ // Control ID is always core
1816
+ tab: isControlIdField ? "overview" : frontendConfig?.tab || void 0
1817
+ // Control ID is always in overview
1818
+ };
1819
+ if (uiType === "select") {
1820
+ fieldDef.options = Array.from(metadata.uniqueValues).sort();
1821
+ }
1822
+ if (frontendConfig?.originalName || metadata.originalName) {
1823
+ fieldDef.original_name = frontendConfig?.originalName || metadata.originalName;
1824
+ }
1825
+ fields[fieldName] = fieldDef;
1826
+ });
1827
+ const fieldSchema = {
1828
+ fields,
1829
+ total_controls: controls.length,
1830
+ analyzed_at: (/* @__PURE__ */ new Date()).toISOString()
1831
+ };
1832
+ const controlSetData = {
1833
+ name: controlSetName,
1834
+ description: controlSetDescription,
1835
+ version: "1.0.0",
1836
+ control_id_field: controlIdFieldNameClean,
1837
+ // Add this to indicate which field is the control ID
1838
+ controlCount: controls.length,
1839
+ families: uniqueFamilies,
1840
+ fieldSchema
1841
+ };
1842
+ writeFileSync2(join4(baseDir, "lula.yaml"), yaml4.dump(controlSetData));
1843
+ const controlsDir = join4(baseDir, "controls");
1844
+ families.forEach((familyControls, family) => {
1845
+ const familyDir = join4(controlsDir, family);
1846
+ if (!existsSync3(familyDir)) {
1847
+ mkdirSync2(familyDir, { recursive: true });
1848
+ }
1849
+ familyControls.forEach((control) => {
1850
+ const controlId = control[controlIdFieldNameClean];
1851
+ if (!controlId) {
1852
+ console.error("Missing control ID for control:", control);
1853
+ return;
1854
+ }
1855
+ const controlIdStr = String(controlId).slice(0, 50);
1856
+ const fileName2 = `${controlIdStr.replace(/[^a-zA-Z0-9-]/g, "_")}.yaml`;
1857
+ const filePath = join4(familyDir, fileName2);
1858
+ const filteredControl = {};
1859
+ if (control.family !== void 0) {
1860
+ filteredControl.family = control.family;
1861
+ }
1862
+ Object.keys(control).forEach((fieldName) => {
1863
+ if (fieldName === "family") return;
1864
+ const isInFrontendSchema = frontendFieldSchema?.some((f) => f.fieldName === fieldName);
1865
+ const isInFieldsMetadata = fields.hasOwnProperty(fieldName);
1866
+ if (isInFrontendSchema || isInFieldsMetadata) {
1867
+ filteredControl[fieldName] = control[fieldName];
1868
+ }
1869
+ });
1870
+ writeFileSync2(filePath, yaml4.dump(filteredControl));
1871
+ });
1872
+ });
1873
+ res.json({
1874
+ success: true,
1875
+ controlCount: controls.length,
1876
+ families: Array.from(families.keys()),
1877
+ outputDir: folderName
1878
+ // Return just the folder name, not full path
1879
+ });
1880
+ } catch (error) {
1881
+ console.error("Error processing spreadsheet:", error);
1882
+ res.status(500).json({ error: "Failed to process spreadsheet" });
1883
+ }
1884
+ });
1885
+ router.get("/export-controls", async (req, res) => {
1886
+ try {
1887
+ const format = req.query.format || "csv";
1888
+ const state = getServerState();
1889
+ const fileStore = state.fileStore;
1890
+ if (!fileStore) {
1891
+ return res.status(500).json({ error: "No control set loaded" });
1892
+ }
1893
+ const controls = await fileStore.loadAllControls();
1894
+ const mappings = await fileStore.loadMappings();
1895
+ let metadata = {};
1896
+ try {
1897
+ const metadataPath2 = join4(state.CONTROL_SET_DIR, "lula.yaml");
1898
+ if (existsSync3(metadataPath2)) {
1899
+ const metadataContent = readFileSync3(metadataPath2, "utf8");
1900
+ metadata = yaml4.load(metadataContent);
1901
+ }
1902
+ } catch (err) {
1903
+ debug("Could not load metadata:", err);
1904
+ }
1905
+ if (!controls || controls.length === 0) {
1906
+ return res.status(404).json({ error: "No controls found" });
1907
+ }
1908
+ const controlsWithMappings = controls.map((control) => {
1909
+ const controlIdField = metadata?.control_id_field || "id";
1910
+ const controlId = control[controlIdField] || control.id;
1911
+ const controlMappings = mappings.filter((m) => m.control_id === controlId);
1912
+ return {
1913
+ ...control,
1914
+ mappings_count: controlMappings.length,
1915
+ mappings: controlMappings.map((m) => ({
1916
+ uuid: m.uuid,
1917
+ status: m.status,
1918
+ description: m.justification || ""
1919
+ }))
1920
+ };
1921
+ });
1922
+ debug(`Exporting ${controlsWithMappings.length} controls as ${format}`);
1923
+ switch (format.toLowerCase()) {
1924
+ case "csv":
1925
+ return exportAsCSV(controlsWithMappings, metadata, res);
1926
+ case "excel":
1927
+ case "xlsx":
1928
+ return await exportAsExcel(controlsWithMappings, metadata, res);
1929
+ case "json":
1930
+ return exportAsJSON(controlsWithMappings, metadata, res);
1931
+ default:
1932
+ return res.status(400).json({ error: `Unsupported format: ${format}` });
1933
+ }
1934
+ } catch (error) {
1935
+ console.error("Export error:", error);
1936
+ res.status(500).json({ error: error.message });
1937
+ }
1938
+ });
1939
+ router.post("/parse-excel", upload.single("file"), async (req, res) => {
1940
+ try {
1941
+ if (!req.file) {
1942
+ return res.status(400).json({ error: "No file uploaded" });
1943
+ }
1944
+ const fileName = req.file.originalname || "";
1945
+ const isCSV = fileName.toLowerCase().endsWith(".csv");
1946
+ let sheets = [];
1947
+ let rows = [];
1948
+ if (isCSV) {
1949
+ const csvContent = req.file.buffer.toString("utf-8");
1950
+ rows = parseCSV(csvContent);
1951
+ sheets = ["Sheet1"];
1952
+ } else {
1953
+ const workbook = new ExcelJS.Workbook();
1954
+ const buffer = Buffer.from(req.file.buffer);
1955
+ await workbook.xlsx.load(buffer);
1956
+ sheets = workbook.worksheets.map((ws) => ws.name);
1957
+ const worksheet = workbook.worksheets[0];
1958
+ if (!worksheet) {
1959
+ return res.status(400).json({ error: "No worksheet found in file" });
1960
+ }
1961
+ worksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
1962
+ const rowData = [];
1963
+ row.eachCell({ includeEmpty: true }, (cell, colNumber) => {
1964
+ rowData[colNumber - 1] = cell.value;
1965
+ });
1966
+ rows.push(rowData);
1967
+ });
1968
+ }
1969
+ const headerCandidates = rows.slice(0, 5).map((row, index) => ({
1970
+ row: index + 1,
1971
+ preview: row.slice(0, 4).filter((v) => v != null).join(", ") + (row.length > 4 ? ", ..." : "")
1972
+ }));
1973
+ res.json({
1974
+ sheets,
1975
+ selectedSheet: sheets[0],
1976
+ rowPreviews: headerCandidates,
1977
+ totalRows: rows.length,
1978
+ sampleData: rows.slice(0, 10)
1979
+ // First 10 rows for preview
1980
+ });
1981
+ } catch (error) {
1982
+ console.error("Error parsing Excel file:", error);
1983
+ res.status(500).json({ error: "Failed to parse Excel file" });
1984
+ }
1985
+ });
1986
+ router.post("/parse-excel-sheet", upload.single("file"), async (req, res) => {
1987
+ try {
1988
+ const { sheetName, headerRow } = req.body;
1989
+ if (!req.file) {
1990
+ return res.status(400).json({ error: "No file uploaded" });
1991
+ }
1992
+ const fileName = req.file.originalname || "";
1993
+ const isCSV = fileName.toLowerCase().endsWith(".csv");
1994
+ let rows = [];
1995
+ if (isCSV) {
1996
+ const csvContent = req.file.buffer.toString("utf-8");
1997
+ rows = parseCSV(csvContent);
1998
+ } else {
1999
+ const workbook = new ExcelJS.Workbook();
2000
+ const buffer = Buffer.from(req.file.buffer);
2001
+ await workbook.xlsx.load(buffer);
2002
+ const worksheet = workbook.getWorksheet(sheetName);
2003
+ if (!worksheet) {
2004
+ return res.status(400).json({ error: `Sheet "${sheetName}" not found` });
2005
+ }
2006
+ worksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
2007
+ const rowData = [];
2008
+ row.eachCell({ includeEmpty: true }, (cell, colNumber) => {
2009
+ rowData[colNumber - 1] = cell.value;
2010
+ });
2011
+ rows.push(rowData);
2012
+ });
2013
+ }
2014
+ const headerRowIndex = parseInt(headerRow) - 1;
2015
+ const headers = rows[headerRowIndex] || [];
2016
+ const fields = headers.filter((h) => h && typeof h === "string");
2017
+ const sampleData = rows.slice(headerRowIndex + 1, headerRowIndex + 4).map((row) => {
2018
+ const obj = {};
2019
+ headers.forEach((header, index) => {
2020
+ if (header) {
2021
+ obj[header] = row[index];
2022
+ }
2023
+ });
2024
+ return obj;
2025
+ });
2026
+ res.json({
2027
+ fields,
2028
+ sampleData,
2029
+ controlCount: rows.length - headerRowIndex - 1
2030
+ });
2031
+ } catch (error) {
2032
+ console.error("Error parsing Excel sheet:", error);
2033
+ res.status(500).json({ error: "Failed to parse Excel sheet" });
2034
+ }
2035
+ });
2036
+ spreadsheetRoutes_default = router;
2037
+ }
2038
+ });
2039
+
2040
+ // index.ts
2041
+ import { Command as Command2 } from "commander";
2042
+
2043
+ // cli/commands/ui.ts
2044
+ import { existsSync as existsSync5 } from "fs";
2045
+ import open from "open";
2046
+ import { join as join7 } from "path";
2047
+
2048
+ // cli/server/server.ts
2049
+ init_serverState();
2050
+ init_spreadsheetRoutes();
2051
+ import cors from "cors";
2052
+ import express2 from "express";
2053
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3 } from "fs";
2054
+ import { createServer as createHttpServer } from "http";
2055
+ import { dirname as dirname2, join as join6 } from "path";
2056
+ import { fileURLToPath } from "url";
2057
+
2058
+ // cli/server/websocketServer.ts
2059
+ import { readFileSync as readFileSync4 } from "fs";
2060
+ init_debug();
2061
+ init_controlHelpers();
2062
+ init_serverState();
2063
+ import * as yaml5 from "js-yaml";
2064
+ import { join as join5 } from "path";
2065
+ import { WebSocket, WebSocketServer } from "ws";
2066
+ var WebSocketManager = class {
2067
+ wss = null;
2068
+ clients = /* @__PURE__ */ new Set();
2069
+ /**
2070
+ * Handle incoming commands from WebSocket clients
2071
+ * @param message - The command message from the client
2072
+ * @param ws - The WebSocket connection that sent the message
2073
+ */
2074
+ async handleCommand(message, ws) {
2075
+ const { type, payload } = message;
2076
+ try {
2077
+ switch (type) {
2078
+ case "update-control": {
2079
+ const state = getServerState();
2080
+ if (payload && payload.id) {
2081
+ const existingControl = state.controlsCache.get(payload.id);
2082
+ if (!existingControl) {
2083
+ console.error("Control not found:", payload.id);
2084
+ return;
2085
+ }
2086
+ const updatedControl = { ...existingControl, ...payload };
2087
+ await state.fileStore.saveControl(updatedControl);
2088
+ state.controlsCache.set(updatedControl.id, updatedControl);
2089
+ const family = updatedControl.family || updatedControl.id.split("-")[0];
2090
+ if (!state.controlsByFamily.has(family)) {
2091
+ state.controlsByFamily.set(family, /* @__PURE__ */ new Set());
2092
+ }
2093
+ const familyControlIds = state.controlsByFamily.get(family);
2094
+ if (familyControlIds) {
2095
+ familyControlIds.add(updatedControl.id);
2096
+ }
2097
+ ws.send(
2098
+ JSON.stringify({
2099
+ type: "control-updated",
2100
+ payload: { id: payload.id, success: true }
2101
+ })
2102
+ );
2103
+ }
2104
+ break;
2105
+ }
2106
+ case "refresh-controls": {
2107
+ const state = getServerState();
2108
+ state.controlsCache.clear();
2109
+ state.controlsByFamily.clear();
2110
+ const { loadAllData: loadAllData2 } = await Promise.resolve().then(() => (init_serverState(), serverState_exports));
2111
+ await loadAllData2();
2112
+ this.broadcastState();
2113
+ break;
2114
+ }
2115
+ case "switch-control-set": {
2116
+ if (payload && payload.path) {
2117
+ const { initializeServerState: initializeServerState2, loadAllData: loadAllData2 } = await Promise.resolve().then(() => (init_serverState(), serverState_exports));
2118
+ const currentState = getServerState();
2119
+ initializeServerState2(currentState.CONTROL_SET_DIR, payload.path);
2120
+ await loadAllData2();
2121
+ this.broadcastState();
2122
+ }
2123
+ break;
2124
+ }
2125
+ case "create-mapping": {
2126
+ const state = getServerState();
2127
+ if (payload && payload.control_id) {
2128
+ const mapping = payload;
2129
+ if (!mapping.uuid) {
2130
+ const crypto = await import("crypto");
2131
+ mapping.uuid = crypto.randomUUID();
2132
+ }
2133
+ await state.fileStore.saveMapping(mapping);
2134
+ state.mappingsCache.set(mapping.uuid, mapping);
2135
+ const family = mapping.control_id.split("-")[0];
2136
+ if (!state.mappingsByFamily.has(family)) {
2137
+ state.mappingsByFamily.set(family, /* @__PURE__ */ new Set());
2138
+ }
2139
+ state.mappingsByFamily.get(family)?.add(mapping.uuid);
2140
+ if (!state.mappingsByControl.has(mapping.control_id)) {
2141
+ state.mappingsByControl.set(mapping.control_id, /* @__PURE__ */ new Set());
2142
+ }
2143
+ state.mappingsByControl.get(mapping.control_id)?.add(mapping.uuid);
2144
+ ws.send(
2145
+ JSON.stringify({
2146
+ type: "mapping-created",
2147
+ payload: { uuid: mapping.uuid, success: true }
2148
+ })
2149
+ );
2150
+ this.broadcastState();
2151
+ }
2152
+ break;
2153
+ }
2154
+ case "update-mapping": {
2155
+ const state = getServerState();
2156
+ if (payload && payload.uuid) {
2157
+ const mapping = payload;
2158
+ await state.fileStore.saveMapping(mapping);
2159
+ state.mappingsCache.set(mapping.uuid, mapping);
2160
+ ws.send(
2161
+ JSON.stringify({
2162
+ type: "mapping-updated",
2163
+ payload: { uuid: mapping.uuid, success: true }
2164
+ })
2165
+ );
2166
+ this.broadcastState();
2167
+ }
2168
+ break;
2169
+ }
2170
+ case "delete-mapping": {
2171
+ const state = getServerState();
2172
+ if (payload && payload.uuid) {
2173
+ const uuid = payload.uuid;
2174
+ const mapping = state.mappingsCache.get(uuid);
2175
+ if (mapping) {
2176
+ await state.fileStore.deleteMapping(uuid);
2177
+ state.mappingsCache.delete(uuid);
2178
+ const family = mapping.control_id.split("-")[0];
2179
+ state.mappingsByFamily.get(family)?.delete(uuid);
2180
+ state.mappingsByControl.get(mapping.control_id)?.delete(uuid);
2181
+ ws.send(
2182
+ JSON.stringify({
2183
+ type: "mapping-deleted",
2184
+ payload: { uuid, success: true }
2185
+ })
2186
+ );
2187
+ this.broadcastState();
2188
+ }
2189
+ }
2190
+ break;
2191
+ }
2192
+ case "scan-control-sets": {
2193
+ const { scanControlSets: scanControlSets2 } = await Promise.resolve().then(() => (init_spreadsheetRoutes(), spreadsheetRoutes_exports));
2194
+ try {
2195
+ const controlSets = await scanControlSets2();
2196
+ ws.send(
2197
+ JSON.stringify({
2198
+ type: "control-sets-list",
2199
+ payload: controlSets
2200
+ })
2201
+ );
2202
+ } catch (error) {
2203
+ console.error("Error scanning control sets:", error);
2204
+ ws.send(
2205
+ JSON.stringify({
2206
+ type: "error",
2207
+ payload: { message: `Failed to scan control sets: ${error.message}` }
2208
+ })
2209
+ );
2210
+ }
2211
+ break;
2212
+ }
2213
+ case "get-control": {
2214
+ if (payload && payload.id) {
2215
+ const { FileStore: FileStore2 } = await Promise.resolve().then(() => (init_fileStore(), fileStore_exports));
2216
+ const currentPath = getCurrentControlSetPath();
2217
+ const fileStore = new FileStore2({ baseDir: currentPath });
2218
+ const controlId = payload.id;
2219
+ const control = await fileStore.loadControl(controlId);
2220
+ if (control) {
2221
+ if (!control.id) {
2222
+ control.id = controlId;
2223
+ }
2224
+ const { GitHistoryUtil: GitHistoryUtil2 } = await Promise.resolve().then(() => (init_gitHistory(), gitHistory_exports));
2225
+ const { execSync } = await import("child_process");
2226
+ let timeline = null;
2227
+ try {
2228
+ const currentPath2 = getCurrentControlSetPath();
2229
+ const { existsSync: existsSync6 } = await import("fs");
2230
+ const family = control.family || control.id.split("-")[0];
2231
+ const familyDir = join5(currentPath2, "controls", family);
2232
+ const possibleFilenames = [
2233
+ `${control.id}.yaml`,
2234
+ `${control.id.replace(/\./g, "_")}.yaml`,
2235
+ // AC-1.1 -> AC-1_1.yaml
2236
+ `${control.id.replace(/[^\w\-]/g, "_")}.yaml`
2237
+ // General sanitization
2238
+ ];
2239
+ let controlPath = "";
2240
+ for (const filename of possibleFilenames) {
2241
+ const testPath = join5(familyDir, filename);
2242
+ if (existsSync6(testPath)) {
2243
+ controlPath = testPath;
2244
+ break;
2245
+ }
2246
+ }
2247
+ if (!controlPath) {
2248
+ for (const filename of possibleFilenames) {
2249
+ const testPath = join5(currentPath2, "controls", filename);
2250
+ if (existsSync6(testPath)) {
2251
+ controlPath = testPath;
2252
+ break;
2253
+ }
2254
+ }
2255
+ }
2256
+ debug(`Getting timeline for control ${control.id}:`);
2257
+ debug(` Current path: ${currentPath2}`);
2258
+ debug(` Control path found: ${controlPath}`);
2259
+ debug(` File exists: ${existsSync6(controlPath)}`);
2260
+ if (!controlPath) {
2261
+ console.error(`Could not find file for control ${control.id}`);
2262
+ timeline = null;
2263
+ } else {
2264
+ const gitUtil = new GitHistoryUtil2(currentPath2);
2265
+ const controlHistory = await gitUtil.getFileHistory(controlPath);
2266
+ debug(`Git history for ${control.id}:`, {
2267
+ path: controlPath,
2268
+ totalCommits: controlHistory.totalCommits,
2269
+ commits: controlHistory.commits?.length || 0
2270
+ });
2271
+ const mappingFilename = `${control.id}-mappings.yaml`;
2272
+ const mappingPath = join5(currentPath2, "mappings", family, mappingFilename);
2273
+ let mappingHistory = { commits: [], totalCommits: 0 };
2274
+ if (existsSync6(mappingPath)) {
2275
+ mappingHistory = await gitUtil.getFileHistory(mappingPath);
2276
+ debug(`Mapping history for ${control.id}:`, {
2277
+ path: mappingPath,
2278
+ totalCommits: mappingHistory.totalCommits,
2279
+ commits: mappingHistory.commits?.length || 0
2280
+ });
2281
+ }
2282
+ let hasPendingChanges = false;
2283
+ try {
2284
+ try {
2285
+ execSync(`git ls-files --error-unmatch "${controlPath}"`, {
2286
+ encoding: "utf8",
2287
+ cwd: process.cwd(),
2288
+ stdio: "pipe"
2289
+ });
2290
+ const gitStatus = execSync(`git status --porcelain "${controlPath}"`, {
2291
+ encoding: "utf8",
2292
+ cwd: process.cwd()
2293
+ }).trim();
2294
+ hasPendingChanges = gitStatus.length > 0;
2295
+ if (hasPendingChanges) {
2296
+ debug(
2297
+ `Control ${payload.id} has pending changes: ${gitStatus.substring(0, 2)}`
2298
+ );
2299
+ }
2300
+ } catch {
2301
+ hasPendingChanges = true;
2302
+ debug(`Control ${payload.id} is untracked (new file)`);
2303
+ }
2304
+ } catch {
2305
+ }
2306
+ if (existsSync6(mappingPath)) {
2307
+ try {
2308
+ try {
2309
+ execSync(`git ls-files --error-unmatch "${mappingPath}"`, {
2310
+ encoding: "utf8",
2311
+ cwd: process.cwd(),
2312
+ stdio: "pipe"
2313
+ });
2314
+ const gitStatus = execSync(`git status --porcelain "${mappingPath}"`, {
2315
+ encoding: "utf8",
2316
+ cwd: process.cwd()
2317
+ }).trim();
2318
+ if (gitStatus.length > 0) {
2319
+ hasPendingChanges = true;
2320
+ debug(`Mapping file has pending changes: ${gitStatus.substring(0, 2)}`);
2321
+ }
2322
+ } catch {
2323
+ hasPendingChanges = true;
2324
+ debug(`Mapping file is untracked`);
2325
+ }
2326
+ } catch {
2327
+ }
2328
+ }
2329
+ const allCommits = [
2330
+ ...(controlHistory.commits || []).map((c) => ({
2331
+ ...c,
2332
+ source: "control"
2333
+ })),
2334
+ ...(mappingHistory.commits || []).map((c) => ({ ...c, source: "mapping" }))
2335
+ ];
2336
+ allCommits.sort(
2337
+ (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
2338
+ );
2339
+ timeline = {
2340
+ commits: allCommits,
2341
+ totalCommits: controlHistory.totalCommits + mappingHistory.totalCommits,
2342
+ controlCommits: controlHistory.totalCommits || 0,
2343
+ mappingCommits: mappingHistory.totalCommits || 0,
2344
+ hasPendingChanges
2345
+ };
2346
+ if (timeline.totalCommits === 0 && hasPendingChanges) {
2347
+ debug(`No git history for control ${payload.id} - showing as pending`);
2348
+ timeline.commits = [
2349
+ {
2350
+ hash: "pending",
2351
+ shortHash: "pending",
2352
+ author: "Current User",
2353
+ authorEmail: "",
2354
+ date: (/* @__PURE__ */ new Date()).toISOString(),
2355
+ message: "Pending changes (uncommitted)",
2356
+ isPending: true,
2357
+ changes: {
2358
+ insertions: 0,
2359
+ deletions: 0,
2360
+ files: 1
2361
+ },
2362
+ source: "control"
2363
+ }
2364
+ ];
2365
+ timeline.totalCommits = 1;
2366
+ } else if (hasPendingChanges && timeline.totalCommits > 0) {
2367
+ timeline.commits.unshift({
2368
+ hash: "pending",
2369
+ shortHash: "pending",
2370
+ author: "Current User",
2371
+ authorEmail: "",
2372
+ date: (/* @__PURE__ */ new Date()).toISOString(),
2373
+ message: "Pending changes (uncommitted)",
2374
+ isPending: true,
2375
+ changes: {
2376
+ insertions: 0,
2377
+ deletions: 0,
2378
+ files: 1
2379
+ },
2380
+ source: "control"
2381
+ });
2382
+ timeline.totalCommits += 1;
2383
+ }
2384
+ debug(`Final timeline for ${control.id}:`, {
2385
+ totalCommits: timeline.totalCommits,
2386
+ commits: timeline.commits?.length || 0,
2387
+ hasPending: timeline.hasPendingChanges
2388
+ });
2389
+ }
2390
+ } catch (error) {
2391
+ console.error("Error fetching timeline:", error);
2392
+ timeline = null;
2393
+ }
2394
+ ws.send(
2395
+ JSON.stringify({
2396
+ type: "control-details",
2397
+ payload: { ...control, timeline }
2398
+ })
2399
+ );
2400
+ } else {
2401
+ ws.send(
2402
+ JSON.stringify({
2403
+ type: "error",
2404
+ payload: { message: `Control not found: ${payload.id}` }
2405
+ })
2406
+ );
2407
+ }
2408
+ }
2409
+ break;
2410
+ }
2411
+ default:
2412
+ console.warn("Unknown command type:", type);
2413
+ ws.send(
2414
+ JSON.stringify({
2415
+ type: "error",
2416
+ payload: { message: `Unknown command: ${type}` }
2417
+ })
2418
+ );
2419
+ }
2420
+ } catch (error) {
2421
+ console.error("Error handling command:", error);
2422
+ ws.send(
2423
+ JSON.stringify({
2424
+ type: "error",
2425
+ payload: { message: error.message }
2426
+ })
2427
+ );
2428
+ }
2429
+ }
2430
+ /**
2431
+ * Get the complete application state for broadcasting
2432
+ * @returns The complete state object or null if error
2433
+ */
2434
+ getCompleteState() {
2435
+ try {
2436
+ const state = getServerState();
2437
+ const currentPath = getCurrentControlSetPath();
2438
+ let controlSetData = {};
2439
+ try {
2440
+ const controlSetFile = join5(currentPath, "lula.yaml");
2441
+ const content = readFileSync4(controlSetFile, "utf8");
2442
+ controlSetData = yaml5.load(content);
2443
+ } catch {
2444
+ controlSetData = {
2445
+ id: "unknown",
2446
+ name: "Unknown Control Set"
2447
+ };
2448
+ }
2449
+ const controlsMetadata = Array.from(state.controlsCache.values()).map((control) => {
2450
+ if (!control.id) {
2451
+ control.id = getControlId(control, currentPath);
2452
+ }
2453
+ const metadata = {
2454
+ id: control.id,
2455
+ family: control.family
2456
+ };
2457
+ const fieldSchema = controlSetData.fieldSchema?.fields || {};
2458
+ for (const [fieldName, fieldConfig] of Object.entries(fieldSchema)) {
2459
+ if (fieldConfig.tab === "overview" && control[fieldName] !== void 0) {
2460
+ metadata[fieldName] = control[fieldName];
2461
+ }
2462
+ }
2463
+ if (control.title !== void 0) metadata.title = control.title;
2464
+ if (control.implementation_status !== void 0)
2465
+ metadata.implementation_status = control.implementation_status;
2466
+ if (control.compliance_status !== void 0)
2467
+ metadata.compliance_status = control.compliance_status;
2468
+ return metadata;
2469
+ });
2470
+ return {
2471
+ ...controlSetData,
2472
+ // Spread control set properties at root level
2473
+ currentPath,
2474
+ controls: controlsMetadata,
2475
+ // Send lightweight metadata instead of full controls
2476
+ mappings: Array.from(state.mappingsCache.values()),
2477
+ families: Array.from(state.controlsByFamily.keys()).sort(),
2478
+ totalControls: state.controlsCache.size,
2479
+ totalMappings: state.mappingsCache.size
2480
+ };
2481
+ } catch (error) {
2482
+ console.error("Error getting complete state:", error);
2483
+ return null;
2484
+ }
2485
+ }
2486
+ /**
2487
+ * Send state updates to client in chunks for better performance
2488
+ * @param ws - The WebSocket connection to send to
2489
+ * @param fullData - Whether to send full data or summaries
2490
+ */
2491
+ sendStateInChunks(ws, fullData = false) {
2492
+ try {
2493
+ const state = getServerState();
2494
+ const currentPath = getCurrentControlSetPath();
2495
+ let controlSetData = {};
2496
+ try {
2497
+ const controlSetFile = join5(currentPath, "lula.yaml");
2498
+ const content = readFileSync4(controlSetFile, "utf8");
2499
+ controlSetData = yaml5.load(content);
2500
+ } catch {
2501
+ controlSetData = {
2502
+ id: "unknown",
2503
+ name: "Unknown Control Set"
2504
+ };
2505
+ }
2506
+ ws.send(
2507
+ JSON.stringify({
2508
+ type: "metadata-update",
2509
+ payload: {
2510
+ ...controlSetData,
2511
+ currentPath,
2512
+ families: Array.from(state.controlsByFamily.keys()).sort(),
2513
+ totalControls: state.controlsCache.size,
2514
+ totalMappings: state.mappingsCache.size
2515
+ }
2516
+ })
2517
+ );
2518
+ const controlSummaries = Array.from(state.controlsCache.values()).map((control) => {
2519
+ const controlId = control.id || getControlId(control, currentPath);
2520
+ const summary = {
2521
+ id: controlId,
2522
+ family: control.family || control["control-acronym"]?.toString().split("-")[0] || ""
2523
+ };
2524
+ if (controlSetData.field_schema?.fields) {
2525
+ for (const [fieldName] of Object.entries(controlSetData.field_schema.fields)) {
2526
+ if (control[fieldName] !== void 0) {
2527
+ summary[fieldName] = control[fieldName];
2528
+ }
2529
+ }
2530
+ } else {
2531
+ Object.assign(summary, control);
2532
+ }
2533
+ return summary;
2534
+ });
2535
+ setTimeout(() => {
2536
+ ws.send(
2537
+ JSON.stringify({
2538
+ type: "controls-update",
2539
+ payload: fullData ? Array.from(state.controlsCache.values()) : controlSummaries
2540
+ })
2541
+ );
2542
+ }, 10);
2543
+ setTimeout(() => {
2544
+ ws.send(
2545
+ JSON.stringify({
2546
+ type: "mappings-update",
2547
+ payload: Array.from(state.mappingsCache.values())
2548
+ })
2549
+ );
2550
+ }, 20);
2551
+ } catch (error) {
2552
+ console.error("Error sending state in chunks:", error);
2553
+ }
2554
+ }
2555
+ /**
2556
+ * Initialize the WebSocket server
2557
+ * @param server - The HTTP server to attach to
2558
+ */
2559
+ initialize(server) {
2560
+ this.wss = new WebSocketServer({ server, path: "/ws" });
2561
+ this.wss.on("connection", (ws) => {
2562
+ debug("New WebSocket client connected");
2563
+ this.clients.add(ws);
2564
+ const initialState = this.getCompleteState();
2565
+ if (initialState) {
2566
+ ws.send(
2567
+ JSON.stringify({
2568
+ type: "state-update",
2569
+ payload: initialState
2570
+ })
2571
+ );
2572
+ }
2573
+ ws.on("message", async (message) => {
2574
+ try {
2575
+ const data = JSON.parse(message.toString());
2576
+ debug("Received WebSocket message:", data);
2577
+ await this.handleCommand(data, ws);
2578
+ } catch (error) {
2579
+ console.error("Invalid WebSocket message:", error);
2580
+ ws.send(
2581
+ JSON.stringify({
2582
+ type: "error",
2583
+ payload: { message: "Invalid message format" }
2584
+ })
2585
+ );
2586
+ }
2587
+ });
2588
+ ws.on("close", () => {
2589
+ debug("WebSocket client disconnected");
2590
+ this.clients.delete(ws);
2591
+ });
2592
+ ws.on("error", (error) => {
2593
+ console.error("WebSocket error:", error);
2594
+ this.clients.delete(ws);
2595
+ });
2596
+ ws.send(JSON.stringify({ type: "connected" }));
2597
+ this.sendStateInChunks(ws);
2598
+ });
2599
+ }
2600
+ /**
2601
+ * Broadcast a message to all connected clients
2602
+ * @param message - The message to broadcast
2603
+ */
2604
+ broadcast(message) {
2605
+ const data = JSON.stringify(message);
2606
+ this.clients.forEach((client) => {
2607
+ if (client.readyState === WebSocket.OPEN) {
2608
+ client.send(data);
2609
+ }
2610
+ });
2611
+ }
2612
+ /**
2613
+ * Broadcast the complete state to all connected clients
2614
+ */
2615
+ broadcastState() {
2616
+ const completeState = this.getCompleteState();
2617
+ if (completeState) {
2618
+ this.broadcast({
2619
+ type: "state-update",
2620
+ payload: completeState
2621
+ });
2622
+ }
2623
+ }
2624
+ /**
2625
+ * Notify all clients that a control was updated
2626
+ * @param _controlId - The ID of the updated control (unused but kept for API compatibility)
2627
+ */
2628
+ notifyControlUpdate(_controlId) {
2629
+ this.broadcastState();
2630
+ }
2631
+ /**
2632
+ * Notify all clients that a mapping was created
2633
+ * @param _mapping - The created mapping (unused but kept for API compatibility)
2634
+ */
2635
+ notifyMappingCreated(_mapping) {
2636
+ this.broadcastState();
2637
+ }
2638
+ /**
2639
+ * Notify all clients that a mapping was updated
2640
+ * @param _mapping - The updated mapping (unused but kept for API compatibility)
2641
+ */
2642
+ notifyMappingUpdated(_mapping) {
2643
+ this.broadcastState();
2644
+ }
2645
+ /**
2646
+ * Notify all clients that a mapping was deleted
2647
+ * @param _uuid - The UUID of the deleted mapping (unused but kept for API compatibility)
2648
+ */
2649
+ notifyMappingDeleted(_uuid) {
2650
+ this.broadcastState();
2651
+ }
2652
+ /**
2653
+ * Notify all clients to refresh their data
2654
+ */
2655
+ notifyDataRefresh() {
2656
+ this.broadcastState();
2657
+ }
2658
+ };
2659
+ var wsManager = new WebSocketManager();
2660
+
2661
+ // cli/server/server.ts
2662
+ var __filename = fileURLToPath(import.meta.url);
2663
+ var __dirname = dirname2(__filename);
2664
+ async function createServer(options) {
2665
+ const { controlSetDir, port } = options;
2666
+ if (!existsSync4(controlSetDir)) {
2667
+ mkdirSync3(controlSetDir, { recursive: true });
2668
+ }
2669
+ initializeServerState(controlSetDir);
2670
+ await loadAllData();
2671
+ const app = express2();
2672
+ app.use(cors());
2673
+ app.use(express2.json({ limit: "50mb" }));
2674
+ const distPath = join6(__dirname, "../dist");
2675
+ app.use(express2.static(distPath));
2676
+ app.use("/api", spreadsheetRoutes_default);
2677
+ app.get("*", (req, res) => {
2678
+ res.sendFile(join6(distPath, "index.html"));
2679
+ });
2680
+ const httpServer = createHttpServer(app);
2681
+ wsManager.initialize(httpServer);
2682
+ return {
2683
+ app,
2684
+ start: () => {
2685
+ return new Promise((resolve) => {
2686
+ httpServer.listen(port, () => {
2687
+ console.log(`
2688
+ \u2728 Lula is running at http://localhost:${port}`);
2689
+ resolve();
2690
+ });
2691
+ });
2692
+ }
2693
+ };
2694
+ }
2695
+ async function startServer(options) {
2696
+ const server = await createServer(options);
2697
+ await server.start();
2698
+ if (process.stdin.isTTY) {
2699
+ process.stdin.setRawMode(true);
2700
+ process.stdin.resume();
2701
+ process.stdin.setEncoding("utf8");
2702
+ console.log("\nPress ESC to close the app\n");
2703
+ process.stdin.on("data", async (key) => {
2704
+ const keyStr = key.toString();
2705
+ if (keyStr === "\x1B" || keyStr === "") {
2706
+ console.log("\n\nShutting down server...");
2707
+ try {
2708
+ await saveMappingsToFile();
2709
+ console.log("Changes saved successfully");
2710
+ } catch (error) {
2711
+ console.error("Error saving changes:", error);
2712
+ }
2713
+ process.exit(0);
2714
+ }
2715
+ });
2716
+ }
2717
+ process.on("SIGINT", async () => {
2718
+ try {
2719
+ await saveMappingsToFile();
2720
+ } catch (error) {
2721
+ console.error("Error saving changes:", error);
2722
+ }
2723
+ process.exit(0);
2724
+ });
2725
+ }
2726
+
2727
+ // cli/server/index.ts
2728
+ init_serverState();
2729
+ init_fileStore();
2730
+ init_gitHistory();
2731
+
2732
+ // cli/commands/ui.ts
2733
+ var UICommand = class _UICommand {
2734
+ /**
2735
+ * Register the serve command with Commander
2736
+ * @param program The Commander program instance
2737
+ * @param parentDebugGetter Function to get debug flag from parent command
2738
+ */
2739
+ static register(program2, parentDebugGetter) {
2740
+ return program2.command("ui", { isDefault: true }).description("Start the Lula web interface (default)").option("--dir <directory>", "Control set directory path").option("--port <port>", "Server port", "3000").option("--no-open-browser", "Do not open browser when starting the server").action(async (options) => {
2741
+ if (parentDebugGetter()) {
2742
+ console.log("Debug mode enabled");
2743
+ const { setDebugMode: setDebugMode2 } = await Promise.resolve().then(() => (init_debug(), debug_exports));
2744
+ setDebugMode2(true);
2745
+ }
2746
+ const uiCommand = new _UICommand();
2747
+ const controlSetDir = options.dir || process.cwd();
2748
+ await uiCommand.run({
2749
+ dir: controlSetDir,
2750
+ port: parseInt(options.port),
2751
+ openBrowser: options.openBrowser !== false
2752
+ // Default to true unless explicitly disabled
2753
+ });
2754
+ });
2755
+ }
2756
+ async run(options) {
2757
+ const { dir, port, openBrowser } = options;
2758
+ const controlSetPath = join7(dir, "lula.yaml");
2759
+ const hasControlSet = existsSync5(controlSetPath);
2760
+ await startServer({ controlSetDir: dir, port });
2761
+ if (openBrowser) {
2762
+ const url = `http://localhost:${port}`;
2763
+ if (!hasControlSet) {
2764
+ await open(`${url}/setup`);
2765
+ } else {
2766
+ await open(url);
2767
+ }
2768
+ }
2769
+ }
2770
+ };
2771
+
2772
+ // cli/commands/version.ts
2773
+ import fs3 from "fs";
2774
+ import path from "path";
2775
+ import { fileURLToPath as fileURLToPath2 } from "url";
2776
+ function getVersion() {
2777
+ const __dirname2 = path.dirname(fileURLToPath2(import.meta.url));
2778
+ const possiblePaths = [
2779
+ path.resolve(__dirname2, "../../package.json"),
2780
+ // dev: cli/commands -> root
2781
+ path.resolve(__dirname2, "../../../package.json"),
2782
+ // alt dev path
2783
+ path.resolve(__dirname2, "../package.json"),
2784
+ // dist: dist/cli/commands -> dist -> root
2785
+ path.resolve(__dirname2, "./package.json"),
2786
+ // dist bundled
2787
+ path.resolve(process.cwd(), "package.json")
2788
+ // current directory fallback
2789
+ ];
2790
+ for (const pkgPath of possiblePaths) {
2791
+ if (fs3.existsSync(pkgPath)) {
2792
+ const packageJson = fs3.readFileSync(pkgPath, "utf8");
2793
+ const { version } = JSON.parse(packageJson);
2794
+ return version;
2795
+ }
2796
+ }
2797
+ return "unknown";
2798
+ }
2799
+
2800
+ // cli/commands/crawl.ts
2801
+ import fs4 from "fs";
2802
+ import { Octokit } from "@octokit/rest";
2803
+ import { Command } from "commander";
2804
+ import { createHash } from "crypto";
2805
+ function getPRContext() {
2806
+ const fallbackOwner = process.env.OWNER;
2807
+ const fallbackRepo = process.env.REPO;
2808
+ const fallbackNumber = process.env.PULL_NUMBER;
2809
+ if (process.env.GITHUB_EVENT_PATH && process.env.GITHUB_REPOSITORY) {
2810
+ const event = JSON.parse(fs4.readFileSync(process.env.GITHUB_EVENT_PATH, "utf8"));
2811
+ const [owner, repo] = process.env.GITHUB_REPOSITORY.split("/");
2812
+ const pull_number = event.pull_request?.number;
2813
+ if (!pull_number) throw new Error("PR number not found in GitHub event payload.");
2814
+ return { owner, repo, pull_number };
2815
+ }
2816
+ if (!fallbackOwner || !fallbackRepo || !fallbackNumber) {
2817
+ throw new Error("Set OWNER, REPO, and PULL_NUMBER in the environment for local use.");
2818
+ }
2819
+ return {
2820
+ owner: fallbackOwner,
2821
+ repo: fallbackRepo,
2822
+ pull_number: parseInt(fallbackNumber, 10)
2823
+ };
2824
+ }
2825
+ async function fetchRawFileViaAPI({
2826
+ octokit,
2827
+ owner,
2828
+ repo,
2829
+ path: path2,
2830
+ ref
2831
+ }) {
2832
+ const res = await octokit.repos.getContent({
2833
+ owner,
2834
+ repo,
2835
+ path: path2,
2836
+ ref,
2837
+ headers: {
2838
+ accept: "application/vnd.github.v3.raw"
2839
+ }
2840
+ });
2841
+ if (typeof res.data === "string") {
2842
+ return res.data;
2843
+ }
2844
+ if (typeof res.data === "object" && res.data !== null && "content" in res.data && typeof res.data.content === "string") {
2845
+ const { content } = res.data;
2846
+ return Buffer.from(content, "base64").toString("utf-8");
2847
+ }
2848
+ throw new Error("Unexpected GitHub API response shape");
2849
+ }
2850
+ function extractMapBlocks(content) {
2851
+ const lines = content.split("\n");
2852
+ const blocks = [];
2853
+ const stack = [];
2854
+ lines.forEach((line, idx) => {
2855
+ const start = line.match(/@lulaStart\s+([a-f0-9-]+)/);
2856
+ const end = line.match(/@lulaEnd\s+([a-f0-9-]+)/);
2857
+ if (start) {
2858
+ stack.push({ uuid: start[1], line: idx });
2859
+ } else if (end) {
2860
+ const last = stack.find((s) => s.uuid === end[1]);
2861
+ if (last) {
2862
+ blocks.push({ uuid: last.uuid, startLine: last.line, endLine: idx + 1 });
2863
+ stack.splice(stack.indexOf(last), 1);
2864
+ }
2865
+ }
2866
+ });
2867
+ return blocks;
2868
+ }
2869
+ function getChangedBlocks(oldText, newText) {
2870
+ const oldBlocks = extractMapBlocks(oldText);
2871
+ const newBlocks = extractMapBlocks(newText);
2872
+ const changed = [];
2873
+ for (const newBlock of newBlocks) {
2874
+ const oldMatch = oldBlocks.find((b) => b.uuid === newBlock.uuid);
2875
+ if (!oldMatch) continue;
2876
+ const oldSegment = oldText.split("\n").slice(oldMatch.startLine, oldMatch.endLine).join("\n");
2877
+ const newSegment = newText.split("\n").slice(newBlock.startLine, newBlock.endLine).join("\n");
2878
+ if (oldSegment !== newSegment) {
2879
+ changed.push(newBlock);
2880
+ }
2881
+ }
2882
+ return changed;
2883
+ }
2884
+ function crawlCommand() {
2885
+ return new Command().command("crawl").description("Detect compliance-related changes between @lulaStart and @lulaEnd in PR files").action(async () => {
2886
+ const { owner, repo, pull_number } = getPRContext();
2887
+ const octokit = new Octokit({ auth: process.env.GITHUB_TOKEN });
2888
+ const pr = await octokit.pulls.get({ owner, repo, pull_number });
2889
+ const prBranch = pr.data.head.ref;
2890
+ const { data: files } = await octokit.pulls.listFiles({ owner, repo, pull_number });
2891
+ for (const file of files) {
2892
+ if (file.status === "added") continue;
2893
+ try {
2894
+ const [oldText, newText] = await Promise.all([
2895
+ fetchRawFileViaAPI({ octokit, owner, repo, path: file.filename, ref: "main" }),
2896
+ fetchRawFileViaAPI({ octokit, owner, repo, path: file.filename, ref: prBranch })
2897
+ ]);
2898
+ const changedBlocks = getChangedBlocks(oldText, newText);
2899
+ for (const block of changedBlocks) {
2900
+ const newBlockText = newText.split("\n").slice(block.startLine, block.endLine).join("\n");
2901
+ const blockSha256 = createHash("sha256").update(newBlockText).digest("hex");
2902
+ const commentBody = `**Compliance Alert**:\`${file.filename}\` changed between lines ${block.startLine + 1}\u2013${block.endLine}.
2903
+ UUID \`${block.uuid}\` may be out of compliance.
2904
+ SHA-256 of block contents: \`${blockSha256}\`.
2905
+
2906
+ Please review the changes to ensure they meet compliance standards.`;
2907
+ console.log(`Commenting on ${file.filename}: ${commentBody}`);
2908
+ await octokit.issues.createComment({
2909
+ owner,
2910
+ repo,
2911
+ issue_number: pull_number,
2912
+ body: commentBody
2913
+ });
2914
+ }
2915
+ } catch (err) {
2916
+ console.error(`Error processing ${file.filename}: ${err}`);
2917
+ }
2918
+ }
2919
+ });
2920
+ }
2921
+
2922
+ // index.ts
2923
+ var program = new Command2();
2924
+ program.name("lula2").description("Lula - Git-friendly compliance control management").version(getVersion(), "-v, --version", "output the current version").option("--debug", "Enable debug logging");
2925
+ UICommand.register(program, () => program.opts().debug || false);
2926
+ program.addCommand(crawlCommand());
2927
+ program.parse(process.argv);