@fulmenhq/tsfulmen 0.3.0 → 0.3.1

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 (37) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/appidentity/index.js +156 -4150
  3. package/dist/appidentity/index.js.map +1 -1
  4. package/dist/bin/prometheus-cli.d.ts +1 -0
  5. package/dist/bin/prometheus-cli.js +9331 -0
  6. package/dist/bin/prometheus-cli.js.map +1 -0
  7. package/dist/bin/schema-cli.d.ts +1 -0
  8. package/dist/bin/schema-cli.js +6104 -0
  9. package/dist/bin/schema-cli.js.map +1 -0
  10. package/dist/bin/signals-cli.d.ts +1 -0
  11. package/dist/bin/signals-cli.js +2104 -0
  12. package/dist/bin/signals-cli.js.map +1 -0
  13. package/dist/config/index.js +29 -4915
  14. package/dist/config/index.js.map +1 -1
  15. package/dist/crucible/index.js +120 -5336
  16. package/dist/crucible/index.js.map +1 -1
  17. package/dist/errors/index.js +52 -4434
  18. package/dist/errors/index.js.map +1 -1
  19. package/dist/foundry/index.js +197 -1874
  20. package/dist/foundry/index.js.map +1 -1
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.js +161 -4154
  23. package/dist/index.js.map +1 -1
  24. package/dist/pathfinder/index.js +47 -4378
  25. package/dist/pathfinder/index.js.map +1 -1
  26. package/dist/reports/license-inventory.csv +2 -2
  27. package/dist/schema/index.js +0 -4
  28. package/dist/schema/index.js.map +1 -1
  29. package/dist/signals/index.js +231 -3570
  30. package/dist/signals/index.js.map +1 -1
  31. package/dist/telemetry/http/index.js +94 -5280
  32. package/dist/telemetry/http/index.js.map +1 -1
  33. package/dist/telemetry/index.js +70 -4786
  34. package/dist/telemetry/index.js.map +1 -1
  35. package/dist/telemetry/prometheus/index.js +461 -4450
  36. package/dist/telemetry/prometheus/index.js.map +1 -1
  37. package/package.json +8 -2
@@ -1,29 +1,21 @@
1
1
  import addFormats from 'ajv-formats';
2
- import { spawn } from 'child_process';
3
- import { readFile, writeFile, access, mkdir } from 'fs/promises';
4
- import { parse, stringify } from 'yaml';
5
- import { dirname, join, relative, extname } from 'path';
2
+ import 'child_process';
3
+ import { readFile, access } from 'fs/promises';
4
+ import { parse } from 'yaml';
5
+ import { join, dirname, relative, extname } from 'path';
6
6
  import { fileURLToPath } from 'url';
7
7
  import glob from 'fast-glob';
8
8
  import Ajv from 'ajv';
9
9
  import Ajv2019 from 'ajv/dist/2019.js';
10
10
  import Ajv2020 from 'ajv/dist/2020.js';
11
11
  import AjvDraft04 from 'ajv-draft-04';
12
- import { Readable } from 'stream';
13
- import picomatch from 'picomatch';
14
- import { suggest as suggest$1, substringSimilarity, score as score$1, normalize as normalize$1, jaro_winkler, damerau_levenshtein, osa_distance, levenshtein } from '@3leaps/string-metrics-wasm';
12
+ import 'commander';
15
13
  import 'crypto';
16
- import { Command } from 'commander';
17
14
 
18
- var __defProp = Object.defineProperty;
19
15
  var __getOwnPropNames = Object.getOwnPropertyNames;
20
16
  var __esm = (fn, res) => function __init() {
21
17
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
22
18
  };
23
- var __export = (target, all) => {
24
- for (var name in all)
25
- __defProp(target, name, { get: all[name], enumerable: true });
26
- };
27
19
 
28
20
  // src/appidentity/constants.ts
29
21
  var APP_IDENTITY_FILENAME, APP_IDENTITY_DIR, APP_IDENTITY_ENV_VAR, APP_IDENTITY_SCHEMA_ID, MAX_ANCESTOR_SEARCH_DEPTH;
@@ -59,23 +51,9 @@ var init_ajv_formats = __esm({
59
51
  });
60
52
 
61
53
  // src/schema/errors.ts
62
- var errors_exports = {};
63
- __export(errors_exports, {
64
- ExportErrorReason: () => ExportErrorReason,
65
- SchemaExportError: () => SchemaExportError,
66
- SchemaValidationError: () => SchemaValidationError
67
- });
68
- var ExportErrorReason, SchemaValidationError, SchemaExportError;
54
+ var SchemaValidationError;
69
55
  var init_errors = __esm({
70
56
  "src/schema/errors.ts"() {
71
- ExportErrorReason = /* @__PURE__ */ ((ExportErrorReason2) => {
72
- ExportErrorReason2["FILE_EXISTS"] = "FILE_EXISTS";
73
- ExportErrorReason2["WRITE_FAILED"] = "WRITE_FAILED";
74
- ExportErrorReason2["INVALID_FORMAT"] = "INVALID_FORMAT";
75
- ExportErrorReason2["PROVENANCE_FAILED"] = "PROVENANCE_FAILED";
76
- ExportErrorReason2["UNKNOWN"] = "UNKNOWN";
77
- return ExportErrorReason2;
78
- })(ExportErrorReason || {});
79
57
  SchemaValidationError = class _SchemaValidationError extends Error {
80
58
  constructor(message, schemaId, diagnostics = [], source, cause) {
81
59
  super(message);
@@ -215,100 +193,10 @@ Source: ${this.source.type}`;
215
193
  };
216
194
  }
217
195
  };
218
- SchemaExportError = class _SchemaExportError extends SchemaValidationError {
219
- constructor(message, reason, schemaId, outPath, cause) {
220
- super(message, schemaId, [], void 0, cause);
221
- this.reason = reason;
222
- this.schemaId = schemaId;
223
- this.outPath = outPath;
224
- this.cause = cause;
225
- this.name = "SchemaExportError";
226
- if (Error.captureStackTrace) {
227
- Error.captureStackTrace(this, _SchemaExportError);
228
- }
229
- }
230
- /**
231
- * Create error for file already exists
232
- */
233
- static fileExists(outPath) {
234
- return new _SchemaExportError(
235
- `Output file already exists: ${outPath}. Use overwrite option to replace.`,
236
- "FILE_EXISTS" /* FILE_EXISTS */,
237
- void 0,
238
- outPath
239
- );
240
- }
241
- /**
242
- * Create error for invalid export format
243
- */
244
- static invalidFormat(format, outPath) {
245
- return new _SchemaExportError(
246
- `Invalid export format: ${format}. Must be 'json' or 'yaml'.`,
247
- "INVALID_FORMAT" /* INVALID_FORMAT */,
248
- void 0,
249
- outPath
250
- );
251
- }
252
- /**
253
- * Create error for write failure
254
- */
255
- static writeFailed(outPath, error) {
256
- return new _SchemaExportError(
257
- `Failed to write schema to ${outPath}: ${error.message}`,
258
- "WRITE_FAILED" /* WRITE_FAILED */,
259
- void 0,
260
- outPath,
261
- error
262
- );
263
- }
264
- /**
265
- * Create error for provenance extraction failure
266
- */
267
- static provenanceFailed(details, error) {
268
- return new _SchemaExportError(
269
- `Failed to extract provenance metadata: ${details}`,
270
- "PROVENANCE_FAILED" /* PROVENANCE_FAILED */,
271
- void 0,
272
- void 0,
273
- error
274
- );
275
- }
276
- };
277
196
  }
278
197
  });
279
198
 
280
199
  // src/schema/utils.ts
281
- function formatDiagnostics(diagnostics) {
282
- if (diagnostics.length === 0) {
283
- return "No validation issues found.";
284
- }
285
- const lines = [];
286
- const errors = diagnostics.filter((d) => d.severity === "ERROR");
287
- const warnings = diagnostics.filter((d) => d.severity === "WARN");
288
- if (errors.length > 0) {
289
- lines.push(`\u274C ${errors.length} error(s) found:`);
290
- errors.forEach((diag, index) => {
291
- lines.push(` ${index + 1}. ${diag.message}`);
292
- if (diag.pointer) {
293
- lines.push(` at ${diag.pointer}`);
294
- }
295
- if (diag.keyword) {
296
- lines.push(` keyword: ${diag.keyword}`);
297
- }
298
- });
299
- }
300
- if (warnings.length > 0) {
301
- lines.push("");
302
- lines.push(`\u26A0\uFE0F ${warnings.length} warning(s) found:`);
303
- warnings.forEach((diag, index) => {
304
- lines.push(` ${index + 1}. ${diag.message}`);
305
- if (diag.pointer) {
306
- lines.push(` at ${diag.pointer}`);
307
- }
308
- });
309
- }
310
- return lines.join("\n");
311
- }
312
200
  function createDiagnostic(pointer, message, keyword, severity = "ERROR", source = "ajv", data) {
313
201
  return {
314
202
  pointer,
@@ -324,261 +212,27 @@ var init_utils = __esm({
324
212
  init_errors();
325
213
  }
326
214
  });
327
- async function detectGoneat(customPath) {
328
- if (customPath) {
329
- try {
330
- await access(customPath);
331
- return customPath;
332
- } catch {
333
- return null;
334
- }
335
- }
336
- if (process.env.GONEAT_PATH) {
337
- try {
338
- await access(process.env.GONEAT_PATH);
339
- return process.env.GONEAT_PATH;
340
- } catch {
341
- }
342
- }
343
- try {
344
- await access("./bin/goneat");
345
- return "./bin/goneat";
346
- } catch {
347
- }
348
- return "goneat";
349
- }
350
- async function isGoneatAvailable(goneatPath) {
351
- let pathToTest;
352
- if (goneatPath) {
353
- pathToTest = goneatPath;
354
- } else {
355
- pathToTest = await detectGoneat();
356
- if (!pathToTest) return false;
357
- }
358
- return new Promise((resolve) => {
359
- const proc = spawn(pathToTest, ["version"], { stdio: "ignore" });
360
- const timeout = setTimeout(() => {
361
- proc.kill();
362
- resolve(false);
363
- }, 5e3);
364
- proc.on("close", (code) => {
365
- clearTimeout(timeout);
366
- resolve(code === 0);
367
- });
368
- proc.on("error", () => {
369
- clearTimeout(timeout);
370
- resolve(false);
371
- });
372
- });
373
- }
374
- async function runGoneatValidation(schemaPath, dataPath, goneatPath) {
375
- const detected = await detectGoneat(goneatPath);
376
- if (!detected) {
377
- return {
378
- valid: false,
379
- diagnostics: [
380
- createDiagnostic(
381
- "",
382
- "goneat binary not found. Install goneat or specify path with --goneat-path",
383
- "goneat-unavailable",
384
- "ERROR",
385
- "goneat"
386
- )
387
- ],
388
- source: "goneat"
389
- };
390
- }
391
- if (!await isGoneatAvailable(detected)) {
392
- return {
393
- valid: false,
394
- diagnostics: [
395
- createDiagnostic(
396
- "",
397
- `goneat binary found at '${detected}' but not executable or version check failed`,
398
- "goneat-not-executable",
399
- "ERROR",
400
- "goneat"
401
- )
402
- ],
403
- source: "goneat"
404
- };
405
- }
406
- return new Promise((resolve) => {
407
- const args = [
408
- "schema",
409
- "validate",
410
- "--schema",
411
- schemaPath,
412
- "--data",
413
- dataPath,
414
- "--format",
415
- "json"
416
- ];
417
- const proc = spawn(detected, args);
418
- let stdout = "";
419
- let stderr = "";
420
- proc.stdout.on("data", (data) => {
421
- stdout += data.toString();
422
- });
423
- proc.stderr.on("data", (data) => {
424
- stderr += data.toString();
425
- });
426
- proc.on("close", (code) => {
427
- let output;
428
- try {
429
- output = JSON.parse(stdout);
430
- } catch {
431
- resolve({
432
- valid: false,
433
- diagnostics: [
434
- createDiagnostic(
435
- "",
436
- `goneat validation failed: ${stderr || "unknown error"}`,
437
- "goneat-error",
438
- "ERROR",
439
- "goneat"
440
- )
441
- ],
442
- source: "goneat"
443
- });
444
- return;
445
- }
446
- const diagnostics = output.errors?.map(
447
- (error) => createDiagnostic(
448
- error.path || "",
449
- error.message,
450
- error.keyword || "validation",
451
- "ERROR",
452
- "goneat"
453
- )
454
- ) || [];
455
- resolve({
456
- valid: code === 0 && output.valid,
457
- diagnostics,
458
- source: "goneat"
459
- });
460
- });
461
- proc.on("error", (error) => {
462
- resolve({
463
- valid: false,
464
- diagnostics: [
465
- createDiagnostic(
466
- "",
467
- `Failed to execute goneat: ${error.message}`,
468
- "goneat-spawn-error",
469
- "ERROR",
470
- "goneat"
471
- )
472
- ],
473
- source: "goneat"
474
- });
475
- });
476
- });
477
- }
478
215
  var init_goneat_bridge = __esm({
479
216
  "src/schema/goneat-bridge.ts"() {
480
217
  init_utils();
481
218
  }
482
219
  });
483
- function parseSchemaInput(input) {
484
- if (!input) {
485
- throw SchemaValidationError.parseFailed(
486
- { type: "string", content: "" },
487
- new Error("schema content is empty")
488
- );
489
- }
490
- try {
491
- if (typeof input === "string") {
492
- try {
493
- return JSON.parse(input);
494
- } catch {
495
- return parse(input);
496
- }
497
- }
498
- if (Buffer.isBuffer(input)) {
499
- const content = input.toString("utf-8");
500
- try {
501
- return JSON.parse(content);
502
- } catch {
503
- return parse(content);
504
- }
505
- }
506
- return input;
507
- } catch (error) {
508
- throw SchemaValidationError.parseFailed(
509
- {
510
- type: typeof input === "string" ? "string" : "object",
511
- content: typeof input === "string" ? input : JSON.stringify(input)
512
- },
513
- error
514
- );
515
- }
516
- }
517
- function sortObjectKeys(obj) {
518
- if (obj === null || typeof obj !== "object") {
519
- return obj;
520
- }
521
- if (Array.isArray(obj)) {
522
- return obj.map(sortObjectKeys);
523
- }
524
- const sorted = {};
525
- const keys = Object.keys(obj).sort();
526
- for (const key of keys) {
527
- sorted[key] = sortObjectKeys(obj[key]);
528
- }
529
- return sorted;
530
- }
531
- function normalizeSchema(input, options = {}) {
532
- try {
533
- const parsed = parseSchemaInput(input);
534
- const sorted = sortObjectKeys(parsed);
535
- if (options.compact) {
536
- return JSON.stringify(sorted);
537
- }
538
- return JSON.stringify(sorted, null, 2);
539
- } catch (error) {
540
- if (error instanceof SchemaValidationError) {
541
- throw error;
542
- }
543
- throw SchemaValidationError.parseFailed(
544
- {
545
- type: typeof input === "string" ? "string" : "object",
546
- content: typeof input === "string" ? input : JSON.stringify(input)
547
- },
548
- error
549
- );
550
- }
551
- }
552
- function compareSchemas(schemaA, schemaB, options = {}) {
553
- const normalizedA = normalizeSchema(schemaA, options);
554
- const normalizedB = normalizeSchema(schemaB, options);
555
- return {
556
- equal: normalizedA === normalizedB,
557
- normalizedA,
558
- normalizedB
559
- };
560
- }
561
220
  var init_normalizer = __esm({
562
221
  "src/schema/normalizer.ts"() {
563
222
  init_errors();
564
223
  }
565
224
  });
566
225
  function optionsChanged(newOptions) {
567
- if (!newOptions && !globalRegistryOptions) return false;
568
- if (!newOptions || !globalRegistryOptions) return true;
569
- return newOptions.baseDir !== globalRegistryOptions.baseDir || JSON.stringify(newOptions.patterns) !== JSON.stringify(globalRegistryOptions.patterns) || newOptions.followSymlinks !== globalRegistryOptions.followSymlinks || newOptions.maxDepth !== globalRegistryOptions.maxDepth;
226
+ if (!globalRegistryOptions) return false;
227
+ return true;
570
228
  }
571
229
  function getSchemaRegistry(options) {
572
- if (!globalRegistry || optionsChanged(options)) {
230
+ if (!globalRegistry || optionsChanged()) {
573
231
  globalRegistry = new SchemaRegistry(options);
574
232
  globalRegistryOptions = options;
575
233
  }
576
234
  return globalRegistry;
577
235
  }
578
- async function listSchemas(prefix, options) {
579
- const registry = getSchemaRegistry(options);
580
- return registry.listSchemas(prefix);
581
- }
582
236
  var DEFAULT_PATTERNS, SchemaRegistry, globalRegistry, globalRegistryOptions;
583
237
  var init_registry = __esm({
584
238
  "src/schema/registry.ts"() {
@@ -599,9 +253,9 @@ var init_registry = __esm({
599
253
  * Get default schema directory using import.meta.url
600
254
  */
601
255
  getDefaultSchemaDir() {
602
- const __filename3 = fileURLToPath(import.meta.url);
603
- const __dirname4 = dirname(__filename3);
604
- return join(__dirname4, "..", "..", "schemas", "crucible-ts");
256
+ const __filename = fileURLToPath(import.meta.url);
257
+ const __dirname2 = dirname(__filename);
258
+ return join(__dirname2, "..", "..", "schemas", "crucible-ts");
605
259
  }
606
260
  /**
607
261
  * Build logical schema ID from file path
@@ -1489,25 +1143,11 @@ var init_telemetry = __esm({
1489
1143
  metrics = new MetricsRegistry();
1490
1144
  }
1491
1145
  });
1492
-
1493
- // src/schema/validator.ts
1494
- var validator_exports = {};
1495
- __export(validator_exports, {
1496
- clearCache: () => clearCache,
1497
- compileSchema: () => compileSchema,
1498
- compileSchemaById: () => compileSchemaById,
1499
- getCacheSize: () => getCacheSize,
1500
- validateData: () => validateData,
1501
- validateDataBySchemaId: () => validateDataBySchemaId,
1502
- validateFile: () => validateFile,
1503
- validateFileBySchemaId: () => validateFileBySchemaId,
1504
- validateSchema: () => validateSchema
1505
- });
1506
1146
  async function loadMetaSchema(draft) {
1507
- const __filename3 = fileURLToPath(import.meta.url);
1508
- const __dirname4 = dirname(__filename3);
1147
+ const __filename = fileURLToPath(import.meta.url);
1148
+ const __dirname2 = dirname(__filename);
1509
1149
  const metaSchemaPath = join(
1510
- __dirname4,
1150
+ __dirname2,
1511
1151
  "..",
1512
1152
  "..",
1513
1153
  "schemas",
@@ -1523,9 +1163,9 @@ async function loadVocabularySchemas(draft) {
1523
1163
  if (draft !== "draft-2019-09" && draft !== "draft-2020-12") {
1524
1164
  return [];
1525
1165
  }
1526
- const __filename3 = fileURLToPath(import.meta.url);
1527
- const __dirname4 = dirname(__filename3);
1528
- const vocabDir = join(__dirname4, "..", "..", "schemas", "crucible-ts", "meta", draft, "meta");
1166
+ const __filename = fileURLToPath(import.meta.url);
1167
+ const __dirname2 = dirname(__filename);
1168
+ const vocabDir = join(__dirname2, "..", "..", "schemas", "crucible-ts", "meta", draft, "meta");
1529
1169
  const vocabFiles = draft === "draft-2020-12" ? [
1530
1170
  "core.json",
1531
1171
  "applicator.json",
@@ -1553,9 +1193,9 @@ async function loadVocabularySchemas(draft) {
1553
1193
  return schemas;
1554
1194
  }
1555
1195
  async function loadReferencedSchema(uri) {
1556
- const __filename3 = fileURLToPath(import.meta.url);
1557
- const __dirname4 = dirname(__filename3);
1558
- const repoRoot = join(__dirname4, "..", "..");
1196
+ const __filename = fileURLToPath(import.meta.url);
1197
+ const __dirname2 = dirname(__filename);
1198
+ const repoRoot = join(__dirname2, "..", "..");
1559
1199
  let resolvedPath;
1560
1200
  if (uri.startsWith("https://schemas.fulmenhq.dev/")) {
1561
1201
  let relativePath = uri.replace("https://schemas.fulmenhq.dev/", "");
@@ -1730,104 +1370,6 @@ function validateData(data, validator) {
1730
1370
  }
1731
1371
  return result;
1732
1372
  }
1733
- async function validateFile(filePath, validator) {
1734
- try {
1735
- const content = await readFile(filePath, "utf-8");
1736
- let data;
1737
- try {
1738
- data = JSON.parse(content);
1739
- } catch {
1740
- data = parse(content);
1741
- }
1742
- return validateData(data, validator);
1743
- } catch (error) {
1744
- if (error instanceof SchemaValidationError) {
1745
- throw error;
1746
- }
1747
- throw SchemaValidationError.validationFailed(
1748
- filePath,
1749
- [
1750
- createDiagnostic(
1751
- "",
1752
- `Failed to read or parse file: ${error.message}`,
1753
- "file-read",
1754
- "ERROR",
1755
- "ajv"
1756
- )
1757
- ],
1758
- { type: "file", id: filePath }
1759
- );
1760
- }
1761
- }
1762
- async function validateSchema(schema) {
1763
- try {
1764
- let parsedSchema;
1765
- if (typeof schema === "string") {
1766
- try {
1767
- parsedSchema = JSON.parse(schema);
1768
- } catch {
1769
- parsedSchema = parse(schema);
1770
- }
1771
- } else if (Buffer.isBuffer(schema)) {
1772
- const content = schema.toString("utf-8");
1773
- try {
1774
- parsedSchema = JSON.parse(content);
1775
- } catch {
1776
- parsedSchema = parse(content);
1777
- }
1778
- } else {
1779
- parsedSchema = schema;
1780
- }
1781
- const dialect = detectDialect(parsedSchema);
1782
- const ajv = await getAjv(dialect);
1783
- const metaValid = ajv.validateSchema(parsedSchema);
1784
- if (!metaValid && ajv.errors) {
1785
- const diagnostics = ajv.errors.map(
1786
- (error) => createDiagnostic(
1787
- error.instancePath || "",
1788
- error.message || "Schema meta-validation failed",
1789
- error.keyword || "unknown",
1790
- "ERROR",
1791
- "ajv"
1792
- )
1793
- );
1794
- return { valid: false, diagnostics, source: "ajv" };
1795
- }
1796
- await compileSchema(parsedSchema);
1797
- return {
1798
- valid: true,
1799
- diagnostics: [],
1800
- source: "ajv"
1801
- };
1802
- } catch (error) {
1803
- if (error instanceof SchemaValidationError) {
1804
- return {
1805
- valid: false,
1806
- diagnostics: error.diagnostics,
1807
- source: "ajv"
1808
- };
1809
- }
1810
- return {
1811
- valid: false,
1812
- diagnostics: [
1813
- createDiagnostic(
1814
- "",
1815
- `Schema validation failed: ${error.message}`,
1816
- "schema-validation",
1817
- "ERROR",
1818
- "ajv"
1819
- )
1820
- ],
1821
- source: "ajv"
1822
- };
1823
- }
1824
- }
1825
- function clearCache() {
1826
- schemaCache.clear();
1827
- }
1828
- function getCacheSize() {
1829
- return schemaCache.size;
1830
- }
1831
1373
  async function compileSchemaById(schemaId, registryOptions) {
1832
1374
  try {
1833
1375
  const registry = getSchemaRegistry(registryOptions);
@@ -1855,15 +1397,6 @@ async function validateDataBySchemaId(data, schemaId, registryOptions) {
1855
1397
  throw error;
1856
1398
  }
1857
1399
  }
1858
- async function validateFileBySchemaId(filePath, schemaId, registryOptions) {
1859
- try {
1860
- const validator = await compileSchemaById(schemaId, registryOptions);
1861
- return validateFile(filePath, validator);
1862
- } catch (error) {
1863
- metrics.counter("schema_validation_errors").inc();
1864
- throw error;
1865
- }
1866
- }
1867
1400
  var ajvInstances, metaschemaReady, schemaCache;
1868
1401
  var init_validator = __esm({
1869
1402
  "src/schema/validator.ts"() {
@@ -1877,174 +1410,15 @@ var init_validator = __esm({
1877
1410
  schemaCache = /* @__PURE__ */ new Map();
1878
1411
  }
1879
1412
  });
1880
-
1881
- // src/schema/export.ts
1882
- var export_exports = {};
1883
- __export(export_exports, {
1884
- exportSchema: () => exportSchema,
1885
- stripProvenance: () => stripProvenance
1886
- });
1887
- async function extractProvenanceMetadata(schemaId) {
1888
- try {
1889
- const __filename3 = fileURLToPath(import.meta.url);
1890
- const __dirname4 = dirname(__filename3);
1891
- const metadataPath = join(__dirname4, "..", "..", ".crucible", "metadata", "metadata.yaml");
1892
- const metadataContent = await readFile(metadataPath, "utf-8");
1893
- const metadata = parse(metadataContent);
1894
- const crucibleSource = metadata.sources?.[0];
1895
- const crucibleVersion = crucibleSource?.version || "unknown";
1896
- const revision = crucibleSource?.commit;
1897
- const pkgPath = join(__dirname4, "..", "..", "package.json");
1898
- const pkgContent = await readFile(pkgPath, "utf-8");
1899
- const pkg = JSON.parse(pkgContent);
1900
- return {
1901
- schema_id: schemaId,
1902
- crucible_version: crucibleVersion,
1903
- library_version: pkg.version,
1904
- revision,
1905
- exported_at: (/* @__PURE__ */ new Date()).toISOString(),
1906
- export_source: "tsfulmen"
1907
- };
1908
- } catch (error) {
1909
- throw SchemaExportError.provenanceFailed(error.message, error);
1910
- }
1911
- }
1912
- function embedProvenance(schemaContent, provenance, format) {
1913
- if (format === "json") {
1914
- const withProvenance = {
1915
- ...schemaContent,
1916
- $comment: {
1917
- ...typeof schemaContent.$comment === "object" ? schemaContent.$comment : {},
1918
- "x-crucible-source": provenance
1919
- }
1920
- };
1921
- return JSON.stringify(withProvenance, null, 2);
1922
- }
1923
- const yamlContent = stringify(schemaContent, {
1924
- indent: 2,
1925
- lineWidth: 0
1926
- });
1927
- const provenanceComment = [
1928
- "# x-crucible-source:",
1929
- `# schema_id: ${provenance.schema_id}`,
1930
- `# crucible_version: ${provenance.crucible_version}`,
1931
- `# library_version: ${provenance.library_version}`,
1932
- ...provenance.revision ? [`# revision: ${provenance.revision}`] : [],
1933
- `# exported_at: ${provenance.exported_at}`,
1934
- `# export_source: ${provenance.export_source}`,
1935
- ""
1936
- ].join("\n");
1937
- return provenanceComment + yamlContent;
1938
- }
1939
- function detectFormat(outPath, formatOption) {
1940
- if (formatOption && formatOption !== "auto") {
1941
- return formatOption;
1942
- }
1943
- const ext = extname(outPath).toLowerCase();
1944
- switch (ext) {
1945
- case ".json":
1946
- return "json";
1947
- case ".yaml":
1948
- case ".yml":
1949
- return "yaml";
1950
- default:
1951
- throw SchemaExportError.invalidFormat(ext, outPath);
1952
- }
1953
- }
1954
- async function exportSchema(options) {
1955
- const {
1956
- schemaId,
1957
- outPath,
1958
- includeProvenance = true,
1959
- validate = true,
1960
- overwrite = false,
1961
- format: formatOption,
1962
- baseDir
1963
- } = options;
1964
- const format = detectFormat(outPath, formatOption);
1965
- if (!overwrite) {
1966
- try {
1967
- await access(outPath);
1968
- throw SchemaExportError.fileExists(outPath);
1969
- } catch (error) {
1970
- if (error.code !== "ENOENT") {
1971
- throw error;
1972
- }
1973
- }
1974
- }
1975
- const registry = getSchemaRegistry({ baseDir });
1976
- const schema = await registry.getSchema(schemaId);
1977
- const schemaContent = await readFile(schema.path, "utf-8");
1978
- if (validate) {
1979
- const validationResult = await validateSchema(schemaContent);
1980
- if (!validationResult.valid) {
1981
- throw SchemaValidationError.validationFailed(schemaId, validationResult.diagnostics, {
1982
- type: "file",
1983
- id: schema.path
1984
- });
1985
- }
1986
- }
1987
- let schemaObject;
1988
- try {
1989
- schemaObject = JSON.parse(schemaContent);
1990
- } catch {
1991
- schemaObject = parse(schemaContent);
1992
- }
1993
- Object.freeze(schemaObject);
1994
- let provenance;
1995
- let outputContent;
1996
- if (includeProvenance) {
1997
- provenance = await extractProvenanceMetadata(schemaId);
1998
- outputContent = embedProvenance(schemaObject, provenance, format);
1999
- } else {
2000
- if (format === "json") {
2001
- outputContent = JSON.stringify(schemaObject, null, 2);
2002
- } else {
2003
- outputContent = stringify(schemaObject, { indent: 2, lineWidth: 0 });
2004
- }
2005
- }
2006
- await mkdir(dirname(outPath), { recursive: true });
2007
- try {
2008
- await writeFile(outPath, outputContent, "utf-8");
2009
- } catch (error) {
2010
- throw SchemaExportError.writeFailed(outPath, error);
2011
- }
2012
- return {
2013
- success: true,
2014
- schemaId,
2015
- outPath,
2016
- format,
2017
- includeProvenance,
2018
- provenance
2019
- };
2020
- }
2021
- function stripProvenance(content) {
2022
- try {
2023
- const parsed = JSON.parse(content);
2024
- if (parsed.$comment && typeof parsed.$comment === "object") {
2025
- const comment = { ...parsed.$comment };
2026
- delete comment["x-crucible-source"];
2027
- if (Object.keys(comment).length === 0) {
2028
- delete parsed.$comment;
2029
- } else {
2030
- parsed.$comment = comment;
2031
- }
2032
- }
2033
- return JSON.stringify(parsed, null, 2);
2034
- } catch {
2035
- const lines = content.split("\n");
2036
- const filtered = lines.filter((line) => {
2037
- const trimmed = line.trim();
2038
- return !(trimmed.startsWith("# x-crucible-source:") || trimmed.startsWith("# ") && /^#\s+(schema_id|crucible_version|library_version|revision|exported_at|export_source):/.test(
2039
- trimmed
2040
- ));
2041
- });
2042
- while (filtered.length > 0 && filtered[0]?.trim() === "") {
2043
- filtered.shift();
2044
- }
2045
- return filtered.join("\n");
1413
+ var init_cli = __esm({
1414
+ "src/schema/cli.ts"() {
1415
+ init_goneat_bridge();
1416
+ init_normalizer();
1417
+ init_registry();
1418
+ init_utils();
1419
+ init_validator();
2046
1420
  }
2047
- }
1421
+ });
2048
1422
  var init_export = __esm({
2049
1423
  "src/schema/export.ts"() {
2050
1424
  init_errors();
@@ -2053,3112 +1427,18 @@ var init_export = __esm({
2053
1427
  }
2054
1428
  });
2055
1429
 
2056
- // src/foundry/errors.ts
2057
- var FoundryCatalogError;
2058
- var init_errors2 = __esm({
2059
- "src/foundry/errors.ts"() {
2060
- FoundryCatalogError = class _FoundryCatalogError extends Error {
2061
- constructor(message, catalog, cause) {
2062
- super(message);
2063
- this.catalog = catalog;
2064
- this.cause = cause;
2065
- this.name = "FoundryCatalogError";
2066
- if (Error.captureStackTrace) {
2067
- Error.captureStackTrace(this, _FoundryCatalogError);
2068
- }
2069
- }
2070
- static invalidSchema(catalog, details, cause) {
2071
- return new _FoundryCatalogError(
2072
- `Invalid schema in ${catalog} catalog: ${details}`,
2073
- catalog,
2074
- cause
2075
- );
2076
- }
2077
- static missingCatalog(catalog) {
2078
- return new _FoundryCatalogError(`Catalog ${catalog} not found or could not be loaded`, catalog);
2079
- }
2080
- static invalidPattern(patternId, details) {
2081
- return new _FoundryCatalogError(`Invalid pattern ${patternId}: ${details}`, "patterns");
2082
- }
2083
- static compilationError(patternId, details, cause) {
2084
- return new _FoundryCatalogError(
2085
- `Failed to compile pattern ${patternId}: ${details}`,
2086
- "patterns",
2087
- cause
2088
- );
2089
- }
2090
- };
2091
- }
2092
- });
2093
- async function loadCatalog(filePath, catalogName, schemaId) {
2094
- try {
2095
- let content;
2096
- if (typeof Bun !== "undefined") {
2097
- try {
2098
- const file = Bun.file(filePath);
2099
- if (!await file.exists()) {
2100
- throw FoundryCatalogError.missingCatalog(catalogName);
2101
- }
2102
- content = await file.text();
2103
- } catch (error) {
2104
- if (error instanceof Error && error.message.includes("No such file")) {
2105
- throw FoundryCatalogError.missingCatalog(catalogName);
2106
- }
2107
- throw error;
2108
- }
2109
- } else {
2110
- try {
2111
- content = await readFile(filePath, "utf-8");
2112
- } catch (error) {
2113
- if (error.code === "ENOENT") {
2114
- throw FoundryCatalogError.missingCatalog(catalogName);
2115
- }
2116
- throw error;
2117
- }
2118
- }
2119
- const data = parse(content);
2120
- const result = await validateDataBySchemaId(data, schemaId);
2121
- if (!result.valid) {
2122
- const errorMessages = result.diagnostics.map((d) => `${d.pointer}: ${d.message}`).join("; ");
2123
- throw FoundryCatalogError.invalidSchema(
2124
- catalogName,
2125
- `Schema validation failed: ${errorMessages}`
2126
- );
2127
- }
2128
- return data;
2129
- } catch (error) {
2130
- if (error instanceof FoundryCatalogError) {
2131
- throw error;
2132
- }
2133
- const err = error;
2134
- if (err.code === "ENOENT") {
2135
- throw FoundryCatalogError.missingCatalog(catalogName);
2136
- } else if (err.code === "EACCES") {
2137
- throw FoundryCatalogError.invalidSchema(
2138
- catalogName,
2139
- "Permission denied accessing catalog file",
2140
- err
2141
- );
2142
- } else if (err.code === "EISDIR") {
2143
- throw FoundryCatalogError.invalidSchema(
2144
- catalogName,
2145
- "Expected file but found directory",
2146
- err
2147
- );
2148
- } else if (err.code === "EMFILE" || err.code === "ENFILE") {
2149
- throw FoundryCatalogError.invalidSchema(catalogName, "Too many open files", err);
2150
- }
2151
- throw FoundryCatalogError.invalidSchema(catalogName, "Failed to load catalog", err);
2152
- }
2153
- }
2154
- async function loadPatternCatalog() {
2155
- return loadCatalog(SSOT_PATHS.patterns, "patterns", SCHEMA_IDS.patterns);
2156
- }
2157
- async function loadHttpStatusCatalog() {
2158
- return loadCatalog(
2159
- SSOT_PATHS.httpStatuses,
2160
- "httpStatuses",
2161
- SCHEMA_IDS.httpStatuses
2162
- );
2163
- }
2164
- async function loadMimeTypeCatalog() {
2165
- return loadCatalog(SSOT_PATHS.mimeTypes, "mimeTypes", SCHEMA_IDS.mimeTypes);
2166
- }
2167
- async function loadCountryCodeCatalog() {
2168
- return loadCatalog(
2169
- SSOT_PATHS.countryCodes,
2170
- "countryCodes",
2171
- SCHEMA_IDS.countryCodes
2172
- );
2173
- }
2174
- async function loadAllCatalogs() {
2175
- const [patterns, httpStatuses, mimeTypes, countryCodes] = await Promise.all([
2176
- loadPatternCatalog(),
2177
- loadHttpStatusCatalog(),
2178
- loadMimeTypeCatalog(),
2179
- loadCountryCodeCatalog()
2180
- ]);
2181
- return { patterns, httpStatuses, mimeTypes, countryCodes };
2182
- }
2183
- var __filename, __dirname2, SSOT_PATHS, SCHEMA_IDS;
2184
- var init_loader = __esm({
2185
- "src/foundry/loader.ts"() {
2186
- init_validator();
2187
- init_errors2();
2188
- __filename = fileURLToPath(import.meta.url);
2189
- __dirname2 = dirname(__filename);
2190
- SSOT_PATHS = {
2191
- patterns: join(__dirname2, "../../config/crucible-ts/library/foundry/patterns.yaml"),
2192
- httpStatuses: join(__dirname2, "../../config/crucible-ts/library/foundry/http-statuses.yaml"),
2193
- mimeTypes: join(__dirname2, "../../config/crucible-ts/library/foundry/mime-types.yaml"),
2194
- countryCodes: join(__dirname2, "../../config/crucible-ts/library/foundry/country-codes.yaml")
2195
- };
2196
- SCHEMA_IDS = {
2197
- patterns: "library/foundry/v1.0.0/patterns",
2198
- httpStatuses: "library/foundry/v1.0.0/http-status-groups",
2199
- mimeTypes: "library/foundry/v1.0.0/mime-types",
2200
- countryCodes: "library/foundry/v1.0.0/country-codes"
2201
- };
2202
- }
2203
- });
2204
-
2205
- // src/foundry/country-codes.ts
2206
- function deepClone(obj) {
2207
- if (obj === null || typeof obj !== "object") {
2208
- return obj;
2209
- }
2210
- if (Array.isArray(obj)) {
2211
- return obj.map((item) => deepClone(item));
2212
- }
2213
- const cloned = {};
2214
- for (const key in obj) {
2215
- if (Object.hasOwn(obj, key)) {
2216
- cloned[key] = deepClone(obj[key]);
2217
- }
2218
- }
2219
- return cloned;
2220
- }
2221
- function deepFreeze(obj) {
2222
- Object.freeze(obj);
2223
- for (const key in obj) {
2224
- if (Object.hasOwn(obj, key)) {
2225
- const value = obj[key];
2226
- if (value !== null && typeof value === "object") {
2227
- deepFreeze(value);
2228
- }
2229
- }
2230
- }
2231
- return obj;
2232
- }
2233
- function normalizeNumeric(code) {
2234
- const str = typeof code === "number" ? code.toString() : code;
2235
- return str.padStart(3, "0");
2236
- }
2237
- async function ensureCatalogLoaded() {
2238
- if (catalogCache !== null) {
2239
- return;
2240
- }
2241
- catalogCache = await loadCountryCodeCatalog();
2242
- for (const country of catalogCache.countries) {
2243
- alpha2Index.set(country.alpha2.toUpperCase(), country);
2244
- alpha3Index.set(country.alpha3.toUpperCase(), country);
2245
- const normalized = normalizeNumeric(country.numeric);
2246
- numericIndex.set(normalized, country);
2247
- }
2248
- }
2249
- async function getCountryByAlpha2(code) {
2250
- await ensureCatalogLoaded();
2251
- const normalized = code.toUpperCase();
2252
- const country = alpha2Index.get(normalized);
2253
- return country ? deepFreeze(deepClone(country)) : null;
2254
- }
2255
- async function getCountryByAlpha3(code) {
2256
- await ensureCatalogLoaded();
2257
- const normalized = code.toUpperCase();
2258
- const country = alpha3Index.get(normalized);
2259
- return country ? deepFreeze(deepClone(country)) : null;
2260
- }
2261
- async function getCountryByNumeric(code) {
2262
- await ensureCatalogLoaded();
2263
- const normalized = normalizeNumeric(code);
2264
- const country = numericIndex.get(normalized);
2265
- return country ? deepFreeze(deepClone(country)) : null;
2266
- }
2267
- async function listCountries() {
2268
- await ensureCatalogLoaded();
2269
- return Array.from(alpha2Index.values()).map((c) => deepFreeze(deepClone(c)));
2270
- }
2271
- function clearCountryCodeCache() {
2272
- catalogCache = null;
2273
- alpha2Index.clear();
2274
- alpha3Index.clear();
2275
- numericIndex.clear();
2276
- }
2277
- var catalogCache, alpha2Index, alpha3Index, numericIndex;
2278
- var init_country_codes = __esm({
2279
- "src/foundry/country-codes.ts"() {
2280
- init_loader();
2281
- catalogCache = null;
2282
- alpha2Index = /* @__PURE__ */ new Map();
2283
- alpha3Index = /* @__PURE__ */ new Map();
2284
- numericIndex = /* @__PURE__ */ new Map();
2285
- }
2286
- });
2287
-
2288
- // src/crucible/foundry/exitCodes.ts
2289
- function getExitCodeInfo(code) {
2290
- return exitCodeMetadata[code];
2291
- }
2292
- var exitCodes, exitCodeMetadata, EXIT_CODES_VERSION;
2293
- var init_exitCodes = __esm({
2294
- "src/crucible/foundry/exitCodes.ts"() {
2295
- exitCodes = {
2296
- // Standard Exit Codes (0-1)
2297
- // POSIX standard success and generic failure codes
2298
- EXIT_SUCCESS: 0,
2299
- EXIT_FAILURE: 1,
2300
- // Networking & Port Management (10-19)
2301
- // Network-related failures (ports, connectivity, etc.)
2302
- EXIT_PORT_IN_USE: 10,
2303
- EXIT_PORT_RANGE_EXHAUSTED: 11,
2304
- EXIT_INSTANCE_ALREADY_RUNNING: 12,
2305
- EXIT_NETWORK_UNREACHABLE: 13,
2306
- EXIT_CONNECTION_REFUSED: 14,
2307
- EXIT_CONNECTION_TIMEOUT: 15,
2308
- // Configuration & Validation (20-29)
2309
- // Configuration errors, validation failures, version mismatches
2310
- EXIT_CONFIG_INVALID: 20,
2311
- EXIT_MISSING_DEPENDENCY: 21,
2312
- EXIT_SSOT_VERSION_MISMATCH: 22,
2313
- EXIT_CONFIG_FILE_NOT_FOUND: 23,
2314
- EXIT_ENVIRONMENT_INVALID: 24,
2315
- // Runtime Errors (30-39)
2316
- // Errors during normal operation (health checks, database, etc.)
2317
- EXIT_HEALTH_CHECK_FAILED: 30,
2318
- EXIT_DATABASE_UNAVAILABLE: 31,
2319
- EXIT_EXTERNAL_SERVICE_UNAVAILABLE: 32,
2320
- EXIT_RESOURCE_EXHAUSTED: 33,
2321
- EXIT_OPERATION_TIMEOUT: 34,
2322
- // Command-Line Usage Errors (40-49)
2323
- // Invalid arguments, missing required flags, usage errors
2324
- EXIT_INVALID_ARGUMENT: 40,
2325
- EXIT_MISSING_REQUIRED_ARGUMENT: 41,
2326
- EXIT_USAGE: 64,
2327
- // Permissions & File Access (50-59)
2328
- // Permission denied, file not found, access errors
2329
- EXIT_PERMISSION_DENIED: 50,
2330
- EXIT_FILE_NOT_FOUND: 51,
2331
- EXIT_DIRECTORY_NOT_FOUND: 52,
2332
- EXIT_FILE_READ_ERROR: 53,
2333
- EXIT_FILE_WRITE_ERROR: 54,
2334
- // Data & Processing Errors (60-69)
2335
- // Data validation, parsing, transformation failures
2336
- EXIT_DATA_INVALID: 60,
2337
- EXIT_PARSE_ERROR: 61,
2338
- EXIT_TRANSFORMATION_FAILED: 62,
2339
- EXIT_DATA_CORRUPT: 63,
2340
- // Security & Authentication (70-79)
2341
- // Authentication failures, authorization errors, security violations
2342
- EXIT_AUTHENTICATION_FAILED: 70,
2343
- EXIT_AUTHORIZATION_FAILED: 71,
2344
- EXIT_SECURITY_VIOLATION: 72,
2345
- EXIT_CERTIFICATE_INVALID: 73,
2346
- // Observability & Monitoring (80-89)
2347
- // Observability infrastructure failures. Use when observability is CRITICAL to operation (e.g., monitoring agents, telemetry exporters). For workhorses where observability is auxiliary: - Log warning and continue (don't exit) - Emit degraded health status - Only exit if explicitly configured (fail_on_observability_error: true)
2348
- EXIT_METRICS_UNAVAILABLE: 80,
2349
- EXIT_TRACING_FAILED: 81,
2350
- EXIT_LOGGING_FAILED: 82,
2351
- EXIT_ALERT_SYSTEM_FAILED: 83,
2352
- EXIT_STRUCTURED_LOGGING_FAILED: 84,
2353
- // Testing & Validation (91-99)
2354
- // Test execution outcomes and validation failures. NOTE: Test harnesses MUST use EXIT_SUCCESS (0) for successful test runs per ecosystem conventions (pytest, Go testing, Jest all use 0 for success). Codes in this category are for FAILURES and exceptional conditions only.
2355
- EXIT_TEST_FAILURE: 91,
2356
- EXIT_TEST_ERROR: 92,
2357
- EXIT_TEST_INTERRUPTED: 93,
2358
- EXIT_TEST_USAGE_ERROR: 94,
2359
- EXIT_TEST_NO_TESTS_COLLECTED: 95,
2360
- EXIT_COVERAGE_THRESHOLD_NOT_MET: 96,
2361
- // Shell & Process Control (124-127)
2362
- // Exit codes from shell conventions and process control utilities (timeout, exec)
2363
- EXIT_TIMEOUT: 124,
2364
- EXIT_TIMEOUT_INTERNAL: 125,
2365
- EXIT_CANNOT_EXECUTE: 126,
2366
- EXIT_NOT_FOUND: 127,
2367
- // Signal-Induced Exits (128-165)
2368
- // Process terminated by Unix signals (128+N pattern per POSIX). Signal codes follow Linux numbering; macOS/FreeBSD differ for SIGUSR1/SIGUSR2. For full signal semantics, see config/library/foundry/signals.yaml. For signal handling patterns, see docs/standards/library/modules/signal-handling.md.
2369
- EXIT_SIGNAL_HUP: 129,
2370
- EXIT_SIGNAL_INT: 130,
2371
- EXIT_SIGNAL_QUIT: 131,
2372
- EXIT_SIGNAL_KILL: 137,
2373
- EXIT_SIGNAL_PIPE: 141,
2374
- EXIT_SIGNAL_ALRM: 142,
2375
- EXIT_SIGNAL_TERM: 143,
2376
- EXIT_SIGNAL_USR1: 138,
2377
- EXIT_SIGNAL_USR2: 140
2378
- };
2379
- exitCodeMetadata = {
2380
- 0: {
2381
- code: 0,
2382
- name: "EXIT_SUCCESS",
2383
- description: "Successful execution",
2384
- context: "Command completed without errors",
2385
- category: "standard"
2386
- },
2387
- 1: {
2388
- code: 1,
2389
- name: "EXIT_FAILURE",
2390
- description: "Generic failure (unspecified error)",
2391
- context: "Use when no more specific exit code applies",
2392
- category: "standard"
2393
- },
2394
- 10: {
2395
- code: 10,
2396
- name: "EXIT_PORT_IN_USE",
2397
- description: "Specified port is already in use",
2398
- context: "Server startup when port unavailable and fail_if_unavailable strategy",
2399
- category: "networking"
2400
- },
2401
- 11: {
2402
- code: 11,
2403
- name: "EXIT_PORT_RANGE_EXHAUSTED",
2404
- description: "No available ports in configured range",
2405
- context: "Server startup when all ports in environment range occupied",
2406
- category: "networking"
2407
- },
2408
- 12: {
2409
- code: 12,
2410
- name: "EXIT_INSTANCE_ALREADY_RUNNING",
2411
- description: "Another instance already running on target port",
2412
- context: "Server startup when PID registry shows active process on port",
2413
- category: "networking"
2414
- },
2415
- 13: {
2416
- code: 13,
2417
- name: "EXIT_NETWORK_UNREACHABLE",
2418
- description: "Network destination unreachable",
2419
- context: "Client connections, health checks, external service validation",
2420
- category: "networking"
2421
- },
2422
- 14: {
2423
- code: 14,
2424
- name: "EXIT_CONNECTION_REFUSED",
2425
- description: "Connection refused by remote host",
2426
- context: "Database connections, API endpoints, upstream services",
2427
- category: "networking"
2428
- },
2429
- 15: {
2430
- code: 15,
2431
- name: "EXIT_CONNECTION_TIMEOUT",
2432
- description: "Connection attempt timed out",
2433
- context: "Slow networks, unresponsive services, firewall blocks",
2434
- category: "networking"
2435
- },
2436
- 20: {
2437
- code: 20,
2438
- name: "EXIT_CONFIG_INVALID",
2439
- description: "Configuration file failed validation",
2440
- context: "Startup validation, schema mismatches, invalid YAML/JSON",
2441
- category: "configuration",
2442
- retryHint: "no_retry"
2443
- },
2444
- 21: {
2445
- code: 21,
2446
- name: "EXIT_MISSING_DEPENDENCY",
2447
- description: "Required dependency not found",
2448
- context: "Missing binaries, libraries, or runtime requirements",
2449
- category: "configuration",
2450
- retryHint: "investigate"
2451
- },
2452
- 22: {
2453
- code: 22,
2454
- name: "EXIT_SSOT_VERSION_MISMATCH",
2455
- description: "SSOT (Crucible) version incompatible",
2456
- context: "Helper library detects unsupported Crucible version",
2457
- category: "configuration",
2458
- retryHint: "no_retry"
2459
- },
2460
- 23: {
2461
- code: 23,
2462
- name: "EXIT_CONFIG_FILE_NOT_FOUND",
2463
- description: "Required configuration file not found",
2464
- context: "Explicitly specified config path doesn't exist",
2465
- category: "configuration"
2466
- },
2467
- 24: {
2468
- code: 24,
2469
- name: "EXIT_ENVIRONMENT_INVALID",
2470
- description: "Invalid or unsupported environment specification",
2471
- context: "Unknown environment name, missing environment config",
2472
- category: "configuration"
2473
- },
2474
- 30: {
2475
- code: 30,
2476
- name: "EXIT_HEALTH_CHECK_FAILED",
2477
- description: "Health check endpoint returned non-healthy status",
2478
- context: "Startup health validation, readiness probes",
2479
- category: "runtime",
2480
- retryHint: "retry"
2481
- },
2482
- 31: {
2483
- code: 31,
2484
- name: "EXIT_DATABASE_UNAVAILABLE",
2485
- description: "Database connection failed or unavailable",
2486
- context: "Startup connection checks, critical query failures",
2487
- category: "runtime",
2488
- retryHint: "retry"
2489
- },
2490
- 32: {
2491
- code: 32,
2492
- name: "EXIT_EXTERNAL_SERVICE_UNAVAILABLE",
2493
- description: "Required external service unavailable",
2494
- context: "API dependencies, message queues, cache servers",
2495
- category: "runtime"
2496
- },
2497
- 33: {
2498
- code: 33,
2499
- name: "EXIT_RESOURCE_EXHAUSTED",
2500
- description: "System resources exhausted (memory, disk, file descriptors)",
2501
- context: "Out-of-memory, disk full, too many open files",
2502
- category: "runtime",
2503
- retryHint: "investigate"
2504
- },
2505
- 34: {
2506
- code: 34,
2507
- name: "EXIT_OPERATION_TIMEOUT",
2508
- description: "Operation exceeded timeout threshold",
2509
- context: "Long-running tasks, async operations, batch processing",
2510
- category: "runtime",
2511
- retryHint: "retry"
2512
- },
2513
- 40: {
2514
- code: 40,
2515
- name: "EXIT_INVALID_ARGUMENT",
2516
- description: "Invalid command-line argument or flag value",
2517
- context: "Type errors, out-of-range values, malformed input",
2518
- category: "usage"
2519
- },
2520
- 41: {
2521
- code: 41,
2522
- name: "EXIT_MISSING_REQUIRED_ARGUMENT",
2523
- description: "Required command-line argument not provided",
2524
- context: "Missing --config, --port, or other required flags",
2525
- category: "usage"
2526
- },
2527
- 64: {
2528
- code: 64,
2529
- name: "EXIT_USAGE",
2530
- description: "Command-line usage error",
2531
- context: "BSD sysexits.h EX_USAGE - wrong number of arguments, bad syntax",
2532
- category: "usage",
2533
- bsdEquivalent: "EX_USAGE"
2534
- },
2535
- 50: {
2536
- code: 50,
2537
- name: "EXIT_PERMISSION_DENIED",
2538
- description: "Insufficient permissions for operation",
2539
- context: "File access, port binding (<1024), privileged operations",
2540
- category: "permissions"
2541
- },
2542
- 51: {
2543
- code: 51,
2544
- name: "EXIT_FILE_NOT_FOUND",
2545
- description: "Required file not found",
2546
- context: "Assets, templates, data files (not config - use 23)",
2547
- category: "permissions"
2548
- },
2549
- 52: {
2550
- code: 52,
2551
- name: "EXIT_DIRECTORY_NOT_FOUND",
2552
- description: "Required directory not found",
2553
- context: "State directories, log paths, data directories",
2554
- category: "permissions"
2555
- },
2556
- 53: {
2557
- code: 53,
2558
- name: "EXIT_FILE_READ_ERROR",
2559
- description: "Error reading file",
2560
- context: "Corrupt files, I/O errors, encoding issues",
2561
- category: "permissions"
2562
- },
2563
- 54: {
2564
- code: 54,
2565
- name: "EXIT_FILE_WRITE_ERROR",
2566
- description: "Error writing file",
2567
- context: "Disk full, read-only filesystem, permission errors",
2568
- category: "permissions"
2569
- },
2570
- 60: {
2571
- code: 60,
2572
- name: "EXIT_DATA_INVALID",
2573
- description: "Input data failed validation",
2574
- context: "Schema validation, business rule violations",
2575
- category: "data"
2576
- },
2577
- 61: {
2578
- code: 61,
2579
- name: "EXIT_PARSE_ERROR",
2580
- description: "Error parsing input data",
2581
- context: "Malformed JSON/YAML/XML, syntax errors",
2582
- category: "data"
2583
- },
2584
- 62: {
2585
- code: 62,
2586
- name: "EXIT_TRANSFORMATION_FAILED",
2587
- description: "Data transformation or conversion failed",
2588
- context: "Type conversions, format transformations, encoding changes",
2589
- category: "data"
2590
- },
2591
- 63: {
2592
- code: 63,
2593
- name: "EXIT_DATA_CORRUPT",
2594
- description: "Data corruption detected",
2595
- context: "Checksum failures, integrity violations",
2596
- category: "data"
2597
- },
2598
- 70: {
2599
- code: 70,
2600
- name: "EXIT_AUTHENTICATION_FAILED",
2601
- description: "Authentication failed",
2602
- context: "Invalid credentials, expired tokens, auth service unavailable",
2603
- category: "security"
2604
- },
2605
- 71: {
2606
- code: 71,
2607
- name: "EXIT_AUTHORIZATION_FAILED",
2608
- description: "Authorization failed (authenticated but insufficient permissions)",
2609
- context: "RBAC failures, scope violations, resource access denied",
2610
- category: "security"
2611
- },
2612
- 72: {
2613
- code: 72,
2614
- name: "EXIT_SECURITY_VIOLATION",
2615
- description: "Security policy violation detected",
2616
- context: "Suspicious activity, rate limit exceeded, IP blocklist",
2617
- category: "security"
2618
- },
2619
- 73: {
2620
- code: 73,
2621
- name: "EXIT_CERTIFICATE_INVALID",
2622
- description: "TLS/SSL certificate validation failed",
2623
- context: "Expired certs, untrusted CAs, hostname mismatches",
2624
- category: "security",
2625
- bsdEquivalent: "EX_PROTOCOL"
2626
- },
2627
- 80: {
2628
- code: 80,
2629
- name: "EXIT_METRICS_UNAVAILABLE",
2630
- description: "Metrics endpoint or collection system unavailable",
2631
- context: "Use for observability-focused tools (Prometheus exporters, StatsD agents).\nWorkhorses SHOULD log warning and continue unless configured to fail-fast.\n",
2632
- category: "observability"
2633
- },
2634
- 81: {
2635
- code: 81,
2636
- name: "EXIT_TRACING_FAILED",
2637
- description: "Distributed tracing system unavailable",
2638
- context: "OTLP exporter failed, Jaeger collector unreachable",
2639
- category: "observability"
2640
- },
2641
- 82: {
2642
- code: 82,
2643
- name: "EXIT_LOGGING_FAILED",
2644
- description: "Logging system unavailable or misconfigured",
2645
- context: "Log aggregator unreachable, log file unwritable",
2646
- category: "observability"
2647
- },
2648
- 83: {
2649
- code: 83,
2650
- name: "EXIT_ALERT_SYSTEM_FAILED",
2651
- description: "Alerting system unavailable",
2652
- context: "PagerDuty API failed, Slack webhook unreachable",
2653
- category: "observability"
2654
- },
2655
- 84: {
2656
- code: 84,
2657
- name: "EXIT_STRUCTURED_LOGGING_FAILED",
2658
- description: "Structured logging system unavailable",
2659
- context: "JSON log aggregator unreachable, log schema validation failed",
2660
- category: "observability"
2661
- },
2662
- 91: {
2663
- code: 91,
2664
- name: "EXIT_TEST_FAILURE",
2665
- description: "One or more tests failed",
2666
- context: "Test assertions failed, expected behavior not met.\nMaps to pytest exit code 1, Go test failure, Jest failure.\n",
2667
- category: "testing"
2668
- },
2669
- 92: {
2670
- code: 92,
2671
- name: "EXIT_TEST_ERROR",
2672
- description: "Test execution error (not test failure)",
2673
- context: "Test setup failed, fixture unavailable, test harness error.\nMaps to pytest exit code 3 (internal error).\n",
2674
- category: "testing"
2675
- },
2676
- 93: {
2677
- code: 93,
2678
- name: "EXIT_TEST_INTERRUPTED",
2679
- description: "Test run interrupted by user or system",
2680
- context: "Ctrl+C during tests, system signal, user cancellation.\nMaps to pytest exit code 2.\n",
2681
- category: "testing"
2682
- },
2683
- 94: {
2684
- code: 94,
2685
- name: "EXIT_TEST_USAGE_ERROR",
2686
- description: "Test command usage error",
2687
- context: "Invalid test arguments, bad configuration.\nMaps to pytest exit code 4.\n",
2688
- category: "testing"
2689
- },
2690
- 95: {
2691
- code: 95,
2692
- name: "EXIT_TEST_NO_TESTS_COLLECTED",
2693
- description: "No tests found or all tests skipped",
2694
- context: "Empty test suite, all tests deselected or skipped.\nMaps to pytest exit code 5.\n",
2695
- category: "testing"
2696
- },
2697
- 96: {
2698
- code: 96,
2699
- name: "EXIT_COVERAGE_THRESHOLD_NOT_MET",
2700
- description: "Test coverage below required threshold",
2701
- context: "Code coverage validation, quality gate failure",
2702
- category: "testing"
2703
- },
2704
- 124: {
2705
- code: 124,
2706
- name: "EXIT_TIMEOUT",
2707
- description: "Command timed out before completion",
2708
- context: "GNU timeout or similar utility terminated command after deadline",
2709
- category: "shell"
2710
- },
2711
- 125: {
2712
- code: 125,
2713
- name: "EXIT_TIMEOUT_INTERNAL",
2714
- description: "Timeout utility itself failed",
2715
- context: "Error in timeout tool before or during command execution (not command failure)",
2716
- category: "shell"
2717
- },
2718
- 126: {
2719
- code: 126,
2720
- name: "EXIT_CANNOT_EXECUTE",
2721
- description: "Command found but could not be executed",
2722
- context: "Permission denied, not executable, exec format error",
2723
- category: "shell",
2724
- bsdEquivalent: "EX_NOPERM (partial)"
2725
- },
2726
- 127: {
2727
- code: 127,
2728
- name: "EXIT_NOT_FOUND",
2729
- description: "Command not found",
2730
- context: "Executable not found in PATH or specified path does not exist",
2731
- category: "shell",
2732
- bsdEquivalent: "EX_UNAVAILABLE (partial)"
2733
- },
2734
- 129: {
2735
- code: 129,
2736
- name: "EXIT_SIGNAL_HUP",
2737
- description: "Hangup signal (SIGHUP) - config reload via restart",
2738
- context: "Config reload via restart-based pattern (mandatory schema validation).\nProcess exits with 129, supervisor restarts with new config.\nSee signals.yaml for reload behavior definition.",
2739
- category: "signals",
2740
- bsdEquivalent: "128 + 1"
2741
- },
2742
- 130: {
2743
- code: 130,
2744
- name: "EXIT_SIGNAL_INT",
2745
- description: "Interrupt signal (SIGINT) - user interrupt with Ctrl+C double-tap",
2746
- context: "Ctrl+C pressed. First tap initiates graceful shutdown, second within 2s forces immediate exit.\nSame exit code (130) for both graceful and force modes.\nSee signals.yaml for double-tap behavior definition.",
2747
- category: "signals",
2748
- bsdEquivalent: "128 + 2"
2749
- },
2750
- 131: {
2751
- code: 131,
2752
- name: "EXIT_SIGNAL_QUIT",
2753
- description: "Quit signal (SIGQUIT) - immediate exit",
2754
- context: "Ctrl+\\ on Unix, Ctrl+Break on Windows. Immediate termination without cleanup.\nUse for emergency shutdown or debugging (core dumps).",
2755
- category: "signals",
2756
- bsdEquivalent: "128 + 3"
2757
- },
2758
- 137: {
2759
- code: 137,
2760
- name: "EXIT_SIGNAL_KILL",
2761
- description: "Kill signal (SIGKILL)",
2762
- context: "Forceful termination, non-graceful shutdown (not catchable)",
2763
- category: "signals",
2764
- bsdEquivalent: "128 + 9",
2765
- pythonNote: "Cannot be caught in Python (OS-level)"
2766
- },
2767
- 141: {
2768
- code: 141,
2769
- name: "EXIT_SIGNAL_PIPE",
2770
- description: "Broken pipe (SIGPIPE) - observe only",
2771
- context: "Writing to closed pipe/socket. Fulmen default is observe_only (log + graceful exit).\nApplications may override to ignore for network services.\nSee signals.yaml for SIGPIPE handling guidance.",
2772
- category: "signals",
2773
- bsdEquivalent: "128 + 13",
2774
- pythonNote: "Raised as BrokenPipeError exception"
2775
- },
2776
- 142: {
2777
- code: 142,
2778
- name: "EXIT_SIGNAL_ALRM",
2779
- description: "Alarm signal (SIGALRM) - watchdog timeout",
2780
- context: "Watchdog timer expired. Treat as timeout-induced exit.\nWatchdog pattern out of scope for v1.0.0 module implementations.",
2781
- category: "signals",
2782
- bsdEquivalent: "128 + 14",
2783
- pythonNote: "Supported by signal module, rarely used in practice"
2784
- },
2785
- 143: {
2786
- code: 143,
2787
- name: "EXIT_SIGNAL_TERM",
2788
- description: "Termination signal (SIGTERM) - graceful shutdown",
2789
- context: "Graceful shutdown requested by container orchestrator or process supervisor.\nStandard 30-second timeout for cleanup. Applications run cleanup handlers before exit.\nSee signals.yaml for graceful shutdown behavior definition.",
2790
- category: "signals",
2791
- bsdEquivalent: "128 + 15",
2792
- pythonNote: "Default signal for graceful shutdown"
2793
- },
2794
- 138: {
2795
- code: 138,
2796
- name: "EXIT_SIGNAL_USR1",
2797
- description: "User-defined signal 1 (SIGUSR1) - custom handler",
2798
- context: "Application-specific signal (e.g., reopen logs, dump stats, trigger profiling).\nApplications register custom handlers. Exit code 138 on Linux (128+10).\nPlatform differences: macOS/FreeBSD use signal 30 (exit 158), not 10.",
2799
- category: "signals"
2800
- },
2801
- 140: {
2802
- code: 140,
2803
- name: "EXIT_SIGNAL_USR2",
2804
- description: "User-defined signal 2 (SIGUSR2) - custom handler",
2805
- context: "Application-specific signal (e.g., toggle debug mode, rotate credentials).\nApplications register custom handlers. Exit code 140 on Linux (128+12).\nPlatform differences: macOS/FreeBSD use signal 31 (exit 159), not 12.",
2806
- category: "signals"
2807
- }
2808
- };
2809
- EXIT_CODES_VERSION = "v1.0.0";
2810
- }
2811
- });
2812
-
2813
- // src/foundry/exit-codes/capabilities.ts
2814
- function supportsSignalExitCodes() {
2815
- return process.platform !== "win32";
2816
- }
2817
- function getPlatform() {
2818
- return process.platform;
2819
- }
2820
- function isWindows() {
2821
- return process.platform === "win32";
2822
- }
2823
- function isPOSIX() {
2824
- return !isWindows();
2825
- }
2826
- function getPlatformCapabilities() {
2827
- return {
2828
- platform: getPlatform(),
2829
- supportsSignalExitCodes: supportsSignalExitCodes(),
2830
- isPOSIX: isPOSIX(),
2831
- isWindows: isWindows()
2832
- };
2833
- }
2834
- var init_capabilities = __esm({
2835
- "src/foundry/exit-codes/capabilities.ts"() {
2836
- }
2837
- });
2838
-
2839
- // src/foundry/exit-codes/simplified.ts
2840
- function mapExitCodeToSimplified(code, mode = "basic" /* BASIC */) {
2841
- if (code === 0) {
2842
- return 0;
2843
- }
2844
- if (mode === "basic" /* BASIC */) {
2845
- return 1;
2846
- }
2847
- const info = exitCodeMetadata[code];
2848
- if (!info) {
2849
- return 3;
2850
- }
2851
- if (info.retryHint === "retry") {
2852
- return 1;
2853
- }
2854
- if (info.retryHint === "no_retry") {
2855
- return 2;
2856
- }
2857
- if (info.retryHint === "investigate") {
2858
- return 3;
2859
- }
2860
- switch (info.category) {
2861
- case "configuration":
2862
- case "usage":
2863
- return 2;
2864
- case "networking":
2865
- case "runtime":
2866
- return 1;
2867
- case "permissions":
2868
- case "data":
2869
- return 2;
2870
- case "security":
2871
- return 3;
2872
- case "observability":
2873
- return 1;
2874
- case "testing":
2875
- return 1;
2876
- case "signals":
2877
- return 3;
2878
- default:
2879
- return 1;
2880
- }
2881
- }
2882
- function getSimplifiedCodes(mode) {
2883
- switch (mode) {
2884
- case "basic" /* BASIC */:
2885
- return [0, 1];
2886
- case "severity" /* SEVERITY */:
2887
- return [0, 1, 2, 3];
2888
- default:
2889
- return [0, 1];
2890
- }
2891
- }
2892
- function getSimplifiedCodeDescription(code, mode) {
2893
- if (mode === "basic" /* BASIC */) {
2894
- switch (code) {
2895
- case 0:
2896
- return "Success";
2897
- case 1:
2898
- return "Failure";
2899
- default:
2900
- return "Unknown";
2901
- }
2902
- }
2903
- if (mode === "severity" /* SEVERITY */) {
2904
- switch (code) {
2905
- case 0:
2906
- return "Success";
2907
- case 1:
2908
- return "Recoverable error (retry possible)";
2909
- case 2:
2910
- return "Configuration error (fix config, don't retry)";
2911
- case 3:
2912
- return "Fatal error (investigate required)";
2913
- default:
2914
- return "Unknown";
2915
- }
2916
- }
2917
- return "Unknown mode";
2918
- }
2919
- var SimplifiedMode;
2920
- var init_simplified = __esm({
2921
- "src/foundry/exit-codes/simplified.ts"() {
2922
- init_exitCodes();
2923
- SimplifiedMode = /* @__PURE__ */ ((SimplifiedMode2) => {
2924
- SimplifiedMode2["BASIC"] = "basic";
2925
- SimplifiedMode2["SEVERITY"] = "severity";
2926
- return SimplifiedMode2;
2927
- })(SimplifiedMode || {});
2928
- }
2929
- });
2930
-
2931
- // src/foundry/exit-codes/index.ts
2932
- var init_exit_codes = __esm({
2933
- "src/foundry/exit-codes/index.ts"() {
2934
- init_exitCodes();
2935
- init_capabilities();
2936
- init_simplified();
2937
- }
2938
- });
2939
-
2940
- // src/foundry/http-statuses.ts
2941
- function deepClone2(obj) {
2942
- if (obj === null || typeof obj !== "object") {
2943
- return obj;
2944
- }
2945
- if (Array.isArray(obj)) {
2946
- return obj.map((item) => deepClone2(item));
2947
- }
2948
- const cloned = {};
2949
- for (const key in obj) {
2950
- if (Object.hasOwn(obj, key)) {
2951
- cloned[key] = deepClone2(obj[key]);
2952
- }
2953
- }
2954
- return cloned;
2955
- }
2956
- function deepFreeze2(obj) {
2957
- Object.freeze(obj);
2958
- for (const key in obj) {
2959
- if (Object.hasOwn(obj, key)) {
2960
- const value = obj[key];
2961
- if (value !== null && typeof value === "object") {
2962
- deepFreeze2(value);
2963
- }
2964
- }
2965
- }
2966
- return obj;
2967
- }
2968
- async function ensureCatalogLoaded2() {
2969
- if (catalogCache2 !== null) {
2970
- return;
2971
- }
2972
- catalogCache2 = await loadHttpStatusCatalog();
2973
- for (const group of catalogCache2.groups) {
2974
- const groupId = group.id;
2975
- for (const code of group.codes) {
2976
- statusCodeIndex.set(code.value, {
2977
- value: code.value,
2978
- reason: code.reason,
2979
- group: groupId
2980
- });
2981
- }
2982
- }
2983
- }
2984
- async function getHttpStatus(code) {
2985
- await ensureCatalogLoaded2();
2986
- const status = statusCodeIndex.get(code);
2987
- return status ? deepFreeze2(deepClone2(status)) : null;
2988
- }
2989
- function isInformational(code) {
2990
- return code >= 100 && code < 200;
2991
- }
2992
- function isSuccess(code) {
2993
- return code >= 200 && code < 300;
2994
- }
2995
- function isRedirection(code) {
2996
- return code >= 300 && code < 400;
2997
- }
2998
- function isClientError(code) {
2999
- return code >= 400 && code < 500;
3000
- }
3001
- function isServerError(code) {
3002
- return code >= 500 && code < 600;
3003
- }
3004
- async function listHttpStatuses() {
3005
- await ensureCatalogLoaded2();
3006
- return Array.from(statusCodeIndex.values()).map((s) => deepFreeze2(deepClone2(s)));
3007
- }
3008
- async function getStatusReason(code) {
3009
- const status = await getHttpStatus(code);
3010
- return status?.reason ?? null;
3011
- }
3012
- function clearHttpStatusCache() {
3013
- catalogCache2 = null;
3014
- statusCodeIndex.clear();
3015
- }
3016
- var catalogCache2, statusCodeIndex;
3017
- var init_http_statuses = __esm({
3018
- "src/foundry/http-statuses.ts"() {
3019
- init_loader();
3020
- catalogCache2 = null;
3021
- statusCodeIndex = /* @__PURE__ */ new Map();
3022
- }
3023
- });
3024
-
3025
- // src/foundry/magic-numbers.ts
3026
- function hasBOM(buffer) {
3027
- if (buffer.length < 3) return false;
3028
- return buffer[0] === UTF8_BOM[0] && buffer[1] === UTF8_BOM[1] && buffer[2] === UTF8_BOM[2];
3029
- }
3030
- function getBOMOffset(buffer) {
3031
- return hasBOM(buffer) ? 3 : 0;
3032
- }
3033
- var UTF8_BOM, XML_PATTERNS, JSON_PATTERNS, YAML_PATTERNS, NDJSON_PATTERNS, CSV_PATTERNS, PROTOBUF_PATTERNS, TEXT_PATTERNS, MAGIC_NUMBER_DATABASE;
3034
- var init_magic_numbers = __esm({
3035
- "src/foundry/magic-numbers.ts"() {
3036
- UTF8_BOM = [239, 187, 191];
3037
- XML_PATTERNS = [
3038
- {
3039
- offset: 0,
3040
- bytes: [60, 63, 120, 109, 108],
3041
- description: "XML declaration: <?xml"
3042
- },
3043
- {
3044
- offset: 0,
3045
- bytes: [239, 187, 191, 60, 63, 120, 109, 108],
3046
- description: "XML with UTF-8 BOM: BOM + <?xml"
3047
- }
3048
- ];
3049
- JSON_PATTERNS = [
3050
- {
3051
- offset: 0,
3052
- bytes: [123],
3053
- description: "JSON object start: {"
3054
- },
3055
- {
3056
- offset: 0,
3057
- bytes: [91],
3058
- description: "JSON array start: ["
3059
- },
3060
- {
3061
- offset: 0,
3062
- bytes: [239, 187, 191, 123],
3063
- description: "JSON object with BOM: BOM + {"
3064
- },
3065
- {
3066
- offset: 0,
3067
- bytes: [239, 187, 191, 91],
3068
- description: "JSON array with BOM: BOM + ["
3069
- }
3070
- ];
3071
- YAML_PATTERNS = [
3072
- {
3073
- offset: 0,
3074
- bytes: [45, 45, 45],
3075
- description: "YAML document marker: ---"
3076
- },
3077
- {
3078
- offset: 0,
3079
- bytes: [37, 89, 65, 77, 76],
3080
- description: "YAML directive: %YAML"
3081
- }
3082
- ];
3083
- NDJSON_PATTERNS = [];
3084
- CSV_PATTERNS = [];
3085
- PROTOBUF_PATTERNS = [];
3086
- TEXT_PATTERNS = [];
3087
- MAGIC_NUMBER_DATABASE = [
3088
- {
3089
- mimeType: "application/xml",
3090
- patterns: XML_PATTERNS,
3091
- priority: 10,
3092
- matchStrategy: "exact"
3093
- },
3094
- {
3095
- mimeType: "application/x-ndjson",
3096
- patterns: NDJSON_PATTERNS,
3097
- priority: 9,
3098
- matchStrategy: "heuristic"
3099
- },
3100
- {
3101
- mimeType: "application/json",
3102
- patterns: JSON_PATTERNS,
3103
- priority: 8,
3104
- matchStrategy: "exact"
3105
- },
3106
- {
3107
- mimeType: "application/yaml",
3108
- patterns: YAML_PATTERNS,
3109
- priority: 7,
3110
- matchStrategy: "exact"
3111
- },
3112
- {
3113
- mimeType: "application/yaml",
3114
- patterns: [],
3115
- priority: 6.5,
3116
- matchStrategy: "heuristic"
3117
- },
3118
- {
3119
- mimeType: "text/csv",
3120
- patterns: CSV_PATTERNS,
3121
- priority: 6,
3122
- matchStrategy: "heuristic"
3123
- },
3124
- {
3125
- mimeType: "application/x-protobuf",
3126
- patterns: PROTOBUF_PATTERNS,
3127
- priority: 5,
3128
- matchStrategy: "heuristic"
3129
- },
3130
- {
3131
- mimeType: "text/plain",
3132
- patterns: TEXT_PATTERNS,
3133
- priority: 1,
3134
- matchStrategy: "heuristic"
3135
- }
3136
- ];
3137
- }
3138
- });
3139
-
3140
- // src/foundry/detector.ts
3141
- function createDetector(catalog) {
3142
- return new MimeTypeDetector(MAGIC_NUMBER_DATABASE, catalog);
3143
- }
3144
- var MimeTypeDetector;
3145
- var init_detector = __esm({
3146
- "src/foundry/detector.ts"() {
3147
- init_magic_numbers();
3148
- MimeTypeDetector = class {
3149
- patterns;
3150
- catalog;
3151
- constructor(patterns, catalog) {
3152
- this.patterns = [...patterns].sort((a, b) => b.priority - a.priority);
3153
- this.catalog = catalog;
3154
- }
3155
- /**
3156
- * Detect MIME type from buffer content
3157
- */
3158
- detect(buffer, _options = {}) {
3159
- const offset = getBOMOffset(buffer);
3160
- const workingBuffer = offset > 0 ? buffer.subarray(offset) : buffer;
3161
- for (const pattern of this.patterns) {
3162
- if (pattern.matchStrategy === "exact" && this.matchPattern(workingBuffer, pattern)) {
3163
- return this.catalog.get(pattern.mimeType) || null;
3164
- }
3165
- if (pattern.matchStrategy === "heuristic" && this.matchHeuristic(workingBuffer, pattern)) {
3166
- return this.catalog.get(pattern.mimeType) || null;
3167
- }
3168
- }
3169
- return null;
3170
- }
3171
- /**
3172
- * Match buffer against a pattern signature
3173
- */
3174
- matchPattern(buffer, signature) {
3175
- for (const pattern of signature.patterns) {
3176
- if (this.matchBytes(buffer, pattern)) {
3177
- return true;
3178
- }
3179
- }
3180
- return false;
3181
- }
3182
- /**
3183
- * Match bytes at specified offset with optional masking
3184
- */
3185
- matchBytes(buffer, pattern) {
3186
- const { offset, bytes, mask } = pattern;
3187
- if (buffer.length < offset + bytes.length) {
3188
- return false;
3189
- }
3190
- for (let i = 0; i < bytes.length; i++) {
3191
- const bufferByte = buffer[offset + i];
3192
- const patternByte = bytes[i];
3193
- const maskByte = mask ? mask[i] : 255;
3194
- if ((bufferByte & maskByte) !== (patternByte & maskByte)) {
3195
- return false;
3196
- }
3197
- }
3198
- return true;
3199
- }
3200
- /**
3201
- * Heuristic detection for formats without magic numbers
3202
- */
3203
- matchHeuristic(buffer, signature) {
3204
- switch (signature.mimeType) {
3205
- case "application/x-ndjson":
3206
- return this.detectNDJSON(buffer);
3207
- case "application/yaml":
3208
- return this.detectYAML(buffer);
3209
- case "text/csv":
3210
- return this.detectCSV(buffer);
3211
- case "application/x-protobuf":
3212
- return this.detectProtobuf(buffer);
3213
- case "text/plain":
3214
- return this.detectPlainText(buffer);
3215
- default:
3216
- return false;
3217
- }
3218
- }
3219
- /**
3220
- * Detect NDJSON (newline-delimited JSON)
3221
- */
3222
- detectNDJSON(buffer) {
3223
- try {
3224
- const text = buffer.toString("utf-8", 0, Math.min(buffer.length, 512));
3225
- const lines = text.split("\n").filter((line) => line.trim().length > 0);
3226
- if (lines.length < 2) return false;
3227
- const linesToCheck = Math.min(3, lines.length);
3228
- let validJsonLines = 0;
3229
- for (let i = 0; i < linesToCheck; i++) {
3230
- try {
3231
- JSON.parse(lines[i]);
3232
- validJsonLines++;
3233
- } catch {
3234
- return false;
3235
- }
3236
- }
3237
- return validJsonLines >= 2;
3238
- } catch {
3239
- return false;
3240
- }
3241
- }
3242
- /**
3243
- * Detect YAML format (heuristic for files without --- header)
3244
- */
3245
- detectYAML(buffer) {
3246
- try {
3247
- const text = buffer.toString("utf-8", 0, Math.min(buffer.length, 512));
3248
- const lines = text.split("\n").filter((line) => line.trim().length > 0);
3249
- if (lines.length === 0) return false;
3250
- let yamlIndicators = 0;
3251
- let nonYamlIndicators = 0;
3252
- for (const line of lines.slice(0, 10)) {
3253
- const trimmed = line.trim();
3254
- if (trimmed.startsWith("#")) continue;
3255
- if (/^[\w"'-]+\s*:\s*.+$/.test(trimmed)) {
3256
- yamlIndicators++;
3257
- continue;
3258
- }
3259
- if (/^-\s+/.test(trimmed)) {
3260
- yamlIndicators++;
3261
- continue;
3262
- }
3263
- if (trimmed.startsWith("{") || trimmed.startsWith("[") || trimmed.endsWith(",")) {
3264
- nonYamlIndicators++;
3265
- }
3266
- }
3267
- return yamlIndicators >= 2 && nonYamlIndicators === 0;
3268
- } catch {
3269
- return false;
3270
- }
3271
- }
3272
- /**
3273
- * Detect CSV format
3274
- */
3275
- detectCSV(buffer) {
3276
- try {
3277
- const text = buffer.toString("utf-8", 0, Math.min(buffer.length, 512));
3278
- const lines = text.split("\n").filter((line) => line.trim().length > 0);
3279
- if (lines.length < 2) return false;
3280
- const delimiters = [",", ";", " "];
3281
- for (const delimiter of delimiters) {
3282
- const counts = lines.map((line) => {
3283
- const escaped = delimiter.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3284
- const matches = line.match(new RegExp(escaped, "g"));
3285
- return matches ? matches.length : 0;
3286
- });
3287
- const firstCount = counts[0];
3288
- if (firstCount > 0 && counts.every((count) => count === firstCount)) {
3289
- return true;
3290
- }
3291
- }
3292
- return false;
3293
- } catch {
3294
- return false;
3295
- }
3296
- }
3297
- /**
3298
- * Detect protobuf binary format
3299
- */
3300
- detectProtobuf(buffer) {
3301
- if (buffer.length < 4) return false;
3302
- const firstByte = buffer[0];
3303
- const wireType = firstByte & 7;
3304
- const fieldNumber = firstByte >> 3;
3305
- const hasValidWireType = wireType === 0 || wireType === 1 || wireType === 2 || wireType === 5;
3306
- const hasValidFieldNumber = fieldNumber > 0 && fieldNumber < 100;
3307
- const isBinary = this.isBinaryContent(buffer);
3308
- return hasValidWireType && hasValidFieldNumber && isBinary;
3309
- }
3310
- /**
3311
- * Detect plain text format
3312
- */
3313
- detectPlainText(buffer) {
3314
- const sample = buffer.subarray(0, Math.min(buffer.length, 512));
3315
- if (sample.length === 0) return false;
3316
- let binaryBytes = 0;
3317
- for (const byte of sample) {
3318
- if (byte === 0 || byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) {
3319
- binaryBytes++;
3320
- }
3321
- }
3322
- return binaryBytes / sample.length < 0.05;
3323
- }
3324
- /**
3325
- * Check if buffer contains binary content
3326
- */
3327
- isBinaryContent(buffer) {
3328
- const sample = buffer.subarray(0, Math.min(buffer.length, 512));
3329
- let binaryBytes = 0;
3330
- for (const byte of sample) {
3331
- if (byte === 0 || byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) {
3332
- binaryBytes++;
3333
- }
3334
- }
3335
- return binaryBytes / sample.length > 0.1;
3336
- }
3337
- };
3338
- }
3339
- });
3340
- function deepClone3(obj) {
3341
- if (obj === null || typeof obj !== "object") {
3342
- return obj;
3343
- }
3344
- if (Array.isArray(obj)) {
3345
- return obj.map((item) => deepClone3(item));
3346
- }
3347
- const cloned = {};
3348
- for (const key in obj) {
3349
- if (Object.hasOwn(obj, key)) {
3350
- cloned[key] = deepClone3(obj[key]);
3351
- }
3352
- }
3353
- return cloned;
3354
- }
3355
- function deepFreeze3(obj) {
3356
- Object.freeze(obj);
3357
- for (const key in obj) {
3358
- if (Object.hasOwn(obj, key)) {
3359
- const value = obj[key];
3360
- if (value !== null && typeof value === "object") {
3361
- deepFreeze3(value);
3362
- }
3363
- }
3364
- }
3365
- return obj;
3366
- }
3367
- async function ensureCatalogLoaded3() {
3368
- if (catalogCache3 !== null) {
3369
- return;
3370
- }
3371
- catalogCache3 = await loadMimeTypeCatalog();
3372
- for (const mimeType of catalogCache3.types) {
3373
- mimeStringIndex.set(mimeType.mime.toLowerCase(), mimeType);
3374
- for (const ext of mimeType.extensions) {
3375
- const normalized = ext.toLowerCase().replace(/^\./, "");
3376
- extensionIndex.set(normalized, mimeType);
3377
- }
3378
- }
3379
- detectorInstance = createDetector(mimeStringIndex);
3380
- }
3381
- async function getMimeType(mimeString) {
3382
- await ensureCatalogLoaded3();
3383
- const normalized = mimeString.toLowerCase();
3384
- const mimeType = mimeStringIndex.get(normalized);
3385
- return mimeType ? deepFreeze3(deepClone3(mimeType)) : null;
3386
- }
3387
- async function getMimeTypeByExtension(extension) {
3388
- await ensureCatalogLoaded3();
3389
- const normalized = extension.toLowerCase().replace(/^\./, "");
3390
- const mimeType = extensionIndex.get(normalized);
3391
- return mimeType ? deepFreeze3(deepClone3(mimeType)) : null;
3392
- }
3393
- async function isSupportedMimeType(mime) {
3394
- await ensureCatalogLoaded3();
3395
- return mimeStringIndex.has(mime.toLowerCase());
3396
- }
3397
- async function detectMimeType(input, options) {
3398
- await ensureCatalogLoaded3();
3399
- if (!detectorInstance) {
3400
- throw new Error("Detector not initialized");
3401
- }
3402
- if (typeof input === "string") {
3403
- return detectMimeTypeFromFile(input, options);
3404
- }
3405
- if (Buffer.isBuffer(input)) {
3406
- return detectMimeTypeFromBuffer(input, options);
3407
- }
3408
- return detectMimeTypeFromStream(input, options);
3409
- }
3410
- async function detectMimeTypeFromFile(filePath, options = {}) {
3411
- await ensureCatalogLoaded3();
3412
- if (!detectorInstance) {
3413
- throw new Error("Detector not initialized");
3414
- }
3415
- const bytesToRead = options.bytesToRead || 512;
3416
- if (typeof Bun !== "undefined") {
3417
- const file = Bun.file(filePath);
3418
- if (!await file.exists()) {
3419
- return null;
3420
- }
3421
- const slice = file.slice(0, bytesToRead);
3422
- const arrayBuffer = await slice.arrayBuffer();
3423
- const buffer = Buffer.from(arrayBuffer);
3424
- return detectMimeTypeFromBuffer(buffer, options);
3425
- }
3426
- try {
3427
- const buffer = await readFile(filePath, { encoding: null });
3428
- const sample = buffer.subarray(0, Math.min(buffer.length, bytesToRead));
3429
- return detectMimeTypeFromBuffer(sample, options);
3430
- } catch (error) {
3431
- if (error.code === "ENOENT") {
3432
- return null;
3433
- }
3434
- throw error;
3435
- }
3436
- }
3437
- function detectMimeTypeFromBuffer(buffer, options = {}) {
3438
- if (!detectorInstance) {
3439
- throw new Error("Detector not initialized");
3440
- }
3441
- const result = detectorInstance.detect(buffer, options);
3442
- return result ? deepFreeze3(deepClone3(result)) : null;
3443
- }
3444
- async function detectMimeTypeFromStream(stream, options = {}) {
3445
- await ensureCatalogLoaded3();
3446
- const bytesToRead = options.bytesToRead || 512;
3447
- const chunks = [];
3448
- let totalBytes = 0;
3449
- const webStream = typeof stream.getReader === "function" ? stream : Readable.toWeb(stream);
3450
- const reader = webStream.getReader();
3451
- try {
3452
- while (totalBytes < bytesToRead) {
3453
- const { value, done } = await reader.read();
3454
- if (done) break;
3455
- chunks.push(value);
3456
- totalBytes += value.length;
3457
- }
3458
- const buffer = Buffer.concat(chunks.map((c) => Buffer.from(c)));
3459
- const sample = buffer.subarray(0, Math.min(buffer.length, bytesToRead));
3460
- return detectMimeTypeFromBuffer(sample, options);
3461
- } finally {
3462
- reader.releaseLock();
3463
- }
3464
- }
3465
- function matchMagicNumber(buffer, mimeType) {
3466
- if (!detectorInstance) {
3467
- throw new Error("Detector not initialized");
3468
- }
3469
- const result = detectorInstance.detect(buffer);
3470
- return result?.mime === mimeType;
3471
- }
3472
- async function listMimeTypes() {
3473
- await ensureCatalogLoaded3();
3474
- return Array.from(mimeStringIndex.values()).map((m) => deepFreeze3(deepClone3(m)));
3475
- }
3476
- function clearMimeTypeCache() {
3477
- catalogCache3 = null;
3478
- mimeStringIndex.clear();
3479
- extensionIndex.clear();
3480
- detectorInstance = null;
3481
- }
3482
- var catalogCache3, mimeStringIndex, extensionIndex, detectorInstance;
3483
- var init_mime_types = __esm({
3484
- "src/foundry/mime-types.ts"() {
3485
- init_detector();
3486
- init_loader();
3487
- catalogCache3 = null;
3488
- mimeStringIndex = /* @__PURE__ */ new Map();
3489
- extensionIndex = /* @__PURE__ */ new Map();
3490
- detectorInstance = null;
3491
- }
3492
- });
3493
- function deepClone4(obj) {
3494
- if (obj === null || typeof obj !== "object") {
3495
- return obj;
3496
- }
3497
- if (Array.isArray(obj)) {
3498
- return obj.map((item) => deepClone4(item));
3499
- }
3500
- const cloned = {};
3501
- for (const key in obj) {
3502
- if (Object.hasOwn(obj, key)) {
3503
- cloned[key] = deepClone4(obj[key]);
3504
- }
3505
- }
3506
- return cloned;
3507
- }
3508
- function deepFreeze4(obj) {
3509
- Object.freeze(obj);
3510
- for (const key in obj) {
3511
- if (Object.hasOwn(obj, key)) {
3512
- const value = obj[key];
3513
- if (value !== null && typeof value === "object") {
3514
- deepFreeze4(value);
3515
- }
3516
- }
3517
- }
3518
- return obj;
3519
- }
3520
- async function ensureCatalogLoaded4() {
3521
- if (catalogCache4 !== null) {
3522
- return;
3523
- }
3524
- catalogCache4 = await loadPatternCatalog();
3525
- for (const pattern of catalogCache4.patterns) {
3526
- patternIndex.set(pattern.id, pattern);
3527
- }
3528
- }
3529
- async function getPattern(id) {
3530
- await ensureCatalogLoaded4();
3531
- const pattern = patternIndex.get(id);
3532
- return pattern ? deepFreeze4(deepClone4(pattern)) : null;
3533
- }
3534
- async function getPatternRegex(id) {
3535
- await ensureCatalogLoaded4();
3536
- const pattern = patternIndex.get(id);
3537
- if (!pattern) {
3538
- return null;
3539
- }
3540
- if (pattern.kind !== "regex") {
3541
- throw FoundryCatalogError.invalidSchema(
3542
- "patterns",
3543
- `Pattern '${id}' is not a regex pattern (kind: ${pattern.kind})`
3544
- );
3545
- }
3546
- const cached = compiledRegexCache.get(id);
3547
- if (cached !== void 0) {
3548
- return cached;
3549
- }
3550
- let flags = "";
3551
- if (pattern.flags?.typescript?.ignoreCase) {
3552
- flags += "i";
3553
- }
3554
- const hasUnicodePropertyEscapes = /\\p\{/.test(pattern.pattern);
3555
- if (pattern.flags?.typescript?.unicode || hasUnicodePropertyEscapes) {
3556
- flags += "u";
3557
- }
3558
- const regex = new RegExp(pattern.pattern, flags);
3559
- compiledRegexCache.set(id, regex);
3560
- return regex;
3561
- }
3562
- function getCompiledGlob(id, pattern) {
3563
- const cached = compiledGlobCache.get(id);
3564
- if (cached !== void 0) {
3565
- return cached;
3566
- }
3567
- const matcher = picomatch(pattern);
3568
- compiledGlobCache.set(id, matcher);
3569
- return matcher;
3570
- }
3571
- async function matchPattern(id, value) {
3572
- await ensureCatalogLoaded4();
3573
- const pattern = patternIndex.get(id);
3574
- if (!pattern) {
3575
- throw FoundryCatalogError.missingCatalog(`Pattern '${id}' not found`);
3576
- }
3577
- if (pattern.kind === "regex") {
3578
- const regex = await getPatternRegex(id);
3579
- return regex ? regex.test(value) : false;
3580
- }
3581
- if (pattern.kind === "glob") {
3582
- const matcher = getCompiledGlob(id, pattern.pattern);
3583
- return matcher(value);
3584
- }
3585
- if (pattern.kind === "literal") {
3586
- return pattern.pattern === value;
3587
- }
3588
- throw FoundryCatalogError.invalidSchema("patterns", `Unknown pattern kind: ${pattern.kind}`);
3589
- }
3590
- async function listPatterns() {
3591
- await ensureCatalogLoaded4();
3592
- return Array.from(patternIndex.values()).map((p) => deepFreeze4(deepClone4(p)));
3593
- }
3594
- async function describePattern(id) {
3595
- const pattern = await getPattern(id);
3596
- return pattern?.description ?? null;
3597
- }
3598
- function clearPatternCache() {
3599
- catalogCache4 = null;
3600
- patternIndex.clear();
3601
- compiledRegexCache.clear();
3602
- compiledGlobCache.clear();
3603
- }
3604
- var catalogCache4, patternIndex, compiledRegexCache, compiledGlobCache;
3605
- var init_patterns = __esm({
3606
- "src/foundry/patterns.ts"() {
3607
- init_errors2();
3608
- init_loader();
3609
- catalogCache4 = null;
3610
- patternIndex = /* @__PURE__ */ new Map();
3611
- compiledRegexCache = /* @__PURE__ */ new Map();
3612
- compiledGlobCache = /* @__PURE__ */ new Map();
3613
- }
3614
- });
3615
- function getConfigPath() {
3616
- if (__dirname3.includes("/dist/")) {
3617
- return join(__dirname3, "../../config/crucible-ts/library/foundry/signals.yaml");
3618
- }
3619
- return join(__dirname3, "../../../config/crucible-ts/library/foundry/signals.yaml");
3620
- }
3621
- async function loadCatalog2() {
3622
- const filePath = SSOT_PATHS2.signals;
3623
- const catalogName = "signals";
3624
- try {
3625
- let content;
3626
- if (typeof Bun !== "undefined") {
3627
- try {
3628
- const file = Bun.file(filePath);
3629
- if (!await file.exists()) {
3630
- throw FoundryCatalogError.missingCatalog(catalogName);
3631
- }
3632
- content = await file.text();
3633
- } catch (error) {
3634
- if (error instanceof Error && error.message.includes("No such file")) {
3635
- throw FoundryCatalogError.missingCatalog(catalogName);
3636
- }
3637
- throw error;
3638
- }
3639
- } else {
3640
- try {
3641
- content = await readFile(filePath, "utf-8");
3642
- } catch (error) {
3643
- if (error.code === "ENOENT") {
3644
- throw FoundryCatalogError.missingCatalog(catalogName);
3645
- }
3646
- throw error;
3647
- }
3648
- }
3649
- const data = parse(content);
3650
- const result = await validateDataBySchemaId(data, SCHEMA_ID);
3651
- if (!result.valid) {
3652
- const errorMessages = result.diagnostics.map((d) => `${d.pointer}: ${d.message}`).join("; ");
3653
- throw FoundryCatalogError.invalidSchema(
3654
- catalogName,
3655
- `Schema validation failed: ${errorMessages}`
3656
- );
3657
- }
3658
- return data;
3659
- } catch (error) {
3660
- if (error instanceof FoundryCatalogError) {
3661
- throw error;
3662
- }
3663
- const err = error;
3664
- if (err.code === "ENOENT") {
3665
- throw FoundryCatalogError.missingCatalog(catalogName);
3666
- } else if (err.code === "EACCES") {
3667
- throw FoundryCatalogError.invalidSchema(
3668
- catalogName,
3669
- "Permission denied accessing catalog file",
3670
- err
3671
- );
3672
- } else if (err.code === "EISDIR") {
3673
- throw FoundryCatalogError.invalidSchema(
3674
- catalogName,
3675
- "Expected file but found directory",
3676
- err
3677
- );
3678
- } else if (err.code === "EMFILE" || err.code === "ENFILE") {
3679
- throw FoundryCatalogError.invalidSchema(catalogName, "Too many open files", err);
3680
- }
3681
- throw FoundryCatalogError.invalidSchema(catalogName, "Failed to load catalog", err);
3682
- }
3683
- }
3684
- async function getCatalog() {
3685
- if (!cachedCatalog) {
3686
- cachedCatalog = await loadCatalog2();
3687
- }
3688
- return cachedCatalog;
3689
- }
3690
- async function getSignalsVersion() {
3691
- const catalog = await getCatalog();
3692
- return catalog.version;
3693
- }
3694
- async function listSignals() {
3695
- const catalog = await getCatalog();
3696
- return catalog.signals.map((signal) => ({ ...signal }));
3697
- }
3698
- async function getSignal(identifier) {
3699
- const catalog = await getCatalog();
3700
- const signal = catalog.signals.find((s) => s.id === identifier || s.name === identifier);
3701
- return signal ? { ...signal } : null;
3702
- }
3703
- async function listBehaviors() {
3704
- const catalog = await getCatalog();
3705
- return catalog.behaviors.map((behavior) => ({ ...behavior }));
3706
- }
3707
- async function getBehavior(id) {
3708
- const catalog = await getCatalog();
3709
- const behavior = catalog.behaviors.find((b) => b.id === id);
3710
- return behavior ? { ...behavior } : null;
3711
- }
3712
- async function getSignalCatalog() {
3713
- return await getCatalog();
3714
- }
3715
- var __filename2, __dirname3, SSOT_PATHS2, SCHEMA_ID, cachedCatalog;
3716
- var init_catalog = __esm({
3717
- "src/foundry/signals/catalog.ts"() {
3718
- init_validator();
3719
- init_errors2();
3720
- __filename2 = fileURLToPath(import.meta.url);
3721
- __dirname3 = dirname(__filename2);
3722
- SSOT_PATHS2 = {
3723
- signals: getConfigPath()
3724
- };
3725
- SCHEMA_ID = "library/foundry/v1.0.0/signals";
3726
- cachedCatalog = null;
3727
- }
3728
- });
3729
-
3730
- // src/foundry/signals/capabilities.ts
3731
- function getPlatform2() {
3732
- const platform = process.platform;
3733
- switch (platform) {
3734
- case "linux":
3735
- return "linux";
3736
- case "darwin":
3737
- return "darwin";
3738
- case "win32":
3739
- return "win32";
3740
- case "freebsd":
3741
- return "freebsd";
3742
- default:
3743
- return "unknown";
3744
- }
3745
- }
3746
- function isPOSIX2() {
3747
- const platform = getPlatform2();
3748
- return platform === "linux" || platform === "darwin" || platform === "freebsd";
3749
- }
3750
- function isWindows2() {
3751
- return getPlatform2() === "win32";
3752
- }
3753
- async function supportsSignal(signalName) {
3754
- const signal = await getSignal(signalName);
3755
- if (!signal) {
3756
- return false;
3757
- }
3758
- if (isPOSIX2()) {
3759
- return true;
3760
- }
3761
- if (isWindows2()) {
3762
- return signal.windows_event !== null;
3763
- }
3764
- return false;
3765
- }
3766
- function supportsSignalExitCodes2() {
3767
- return isPOSIX2();
3768
- }
3769
- async function getPlatformCapabilities2() {
3770
- const platform = getPlatform2();
3771
- const isPosix = isPOSIX2();
3772
- const isWin = isWindows2();
3773
- const catalog = await getSignalCatalog();
3774
- const supported = [];
3775
- const unsupported = [];
3776
- const mapped = [];
3777
- for (const signal of catalog.signals) {
3778
- if (isPosix) {
3779
- supported.push(signal.name);
3780
- } else if (isWin) {
3781
- if (signal.windows_event !== null) {
3782
- supported.push(signal.name);
3783
- mapped.push(signal.name);
3784
- } else {
3785
- unsupported.push(signal.name);
3786
- }
3787
- } else {
3788
- unsupported.push(signal.name);
3789
- }
3790
- }
3791
- return {
3792
- platform,
3793
- isPOSIX: isPosix,
3794
- isWindows: isWin,
3795
- supportsNativeSignals: isPosix,
3796
- supportsSignalExitCodes: supportsSignalExitCodes2(),
3797
- supportedSignals: supported,
3798
- unsupportedSignals: unsupported,
3799
- mappedSignals: mapped
3800
- };
3801
- }
3802
- async function getSignalNumber(signalName) {
3803
- const signal = await getSignal(signalName);
3804
- if (!signal) {
3805
- return null;
3806
- }
3807
- const platform = getPlatform2();
3808
- if (signal.platform_overrides) {
3809
- if (platform === "darwin" && signal.platform_overrides.darwin !== void 0) {
3810
- return signal.platform_overrides.darwin;
3811
- }
3812
- if (platform === "freebsd" && signal.platform_overrides.freebsd !== void 0) {
3813
- return signal.platform_overrides.freebsd;
3814
- }
3815
- }
3816
- return signal.unix_number;
3817
- }
3818
- async function getWindowsEvent(signalName) {
3819
- const signal = await getSignal(signalName);
3820
- if (!signal) {
3821
- return null;
3822
- }
3823
- return signal.windows_event;
3824
- }
3825
- var init_capabilities2 = __esm({
3826
- "src/foundry/signals/capabilities.ts"() {
3827
- init_catalog();
3828
- }
3829
- });
3830
-
3831
- // src/foundry/signals/config-reload-endpoint.ts
3832
- function createConfigReloadEndpoint(options) {
3833
- const { loader, validator, onReload: onReload2, auth, rateLimit, logger, telemetry } = options;
3834
- return async (payload, req) => {
3835
- const correlationId = payload.correlation_id ?? generateCorrelationId();
3836
- const authResult = await auth(req);
3837
- if (!authResult.authenticated) {
3838
- if (logger) {
3839
- logger.warn("Config reload endpoint: authentication failed", {
3840
- correlation_id: correlationId,
3841
- reason: authResult.reason
3842
- });
3843
- }
3844
- if (telemetry) {
3845
- telemetry.emit("fulmen.config.http_endpoint.auth_failed", {
3846
- correlation_id: correlationId
3847
- });
3848
- }
3849
- return {
3850
- status: "error",
3851
- error: "authentication_failed",
3852
- message: authResult.reason || "Authentication required",
3853
- statusCode: 401
3854
- };
3855
- }
3856
- const identity = authResult.identity || "unknown";
3857
- if (rateLimit) {
3858
- const rateLimitResult = await rateLimit(identity);
3859
- if (!rateLimitResult.allowed) {
3860
- if (logger) {
3861
- logger.warn("Config reload endpoint: rate limit exceeded", {
3862
- correlation_id: correlationId,
3863
- identity
3864
- });
3865
- }
3866
- if (telemetry) {
3867
- telemetry.emit("fulmen.config.http_endpoint.rate_limited", {
3868
- correlation_id: correlationId
3869
- });
3870
- }
3871
- return {
3872
- status: "error",
3873
- error: "rate_limit_exceeded",
3874
- message: "Rate limit exceeded. Please try again later.",
3875
- statusCode: 429
3876
- };
3877
- }
3878
- }
3879
- if (telemetry) {
3880
- telemetry.emit("fulmen.config.http_endpoint.reload_requested", {
3881
- correlation_id: correlationId
3882
- });
3883
- }
3884
- try {
3885
- const config = await loader();
3886
- if (validator) {
3887
- const validation = await validator(config);
3888
- if (!validation.valid) {
3889
- if (logger) {
3890
- logger.warn("Config reload endpoint: validation failed", {
3891
- correlation_id: correlationId,
3892
- error_count: validation.errors?.length ?? 0
3893
- });
3894
- }
3895
- if (telemetry) {
3896
- telemetry.emit("fulmen.config.http_endpoint.reload_rejected", {
3897
- correlation_id: correlationId,
3898
- reason: "validation_failed"
3899
- });
3900
- }
3901
- return {
3902
- status: "error",
3903
- error: "validation_failed",
3904
- message: "Configuration validation failed",
3905
- validation_errors: validation.errors,
3906
- statusCode: 422
3907
- };
3908
- }
3909
- }
3910
- if (onReload2) {
3911
- await onReload2(config);
3912
- }
3913
- if (telemetry) {
3914
- telemetry.emit("fulmen.config.http_endpoint.reload_accepted", {
3915
- correlation_id: correlationId
3916
- });
3917
- }
3918
- if (logger) {
3919
- logger.info("Config reload endpoint: reload accepted", {
3920
- correlation_id: correlationId,
3921
- reason: payload.reason
3922
- });
3923
- }
3924
- return {
3925
- status: "reloaded",
3926
- correlation_id: correlationId,
3927
- message: "Configuration reloaded",
3928
- statusCode: 200
3929
- };
3930
- } catch (error) {
3931
- if (logger) {
3932
- logger.warn("Config reload endpoint: reload failed", {
3933
- correlation_id: correlationId,
3934
- error: error instanceof Error ? error.message : String(error)
3935
- });
3936
- }
3937
- if (telemetry) {
3938
- telemetry.emit("fulmen.config.http_endpoint.reload_error", {
3939
- correlation_id: correlationId,
3940
- error_type: error instanceof Error ? error.constructor.name : "unknown"
3941
- });
3942
- }
3943
- return {
3944
- status: "error",
3945
- error: "reload_failed",
3946
- message: error instanceof Error ? error.message : String(error),
3947
- statusCode: 500
3948
- };
3949
- }
3950
- };
3951
- }
3952
- function generateCorrelationId() {
3953
- return `cfg-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
3954
- }
3955
- var init_config_reload_endpoint = __esm({
3956
- "src/foundry/signals/config-reload-endpoint.ts"() {
3957
- }
3958
- });
3959
-
3960
- // src/appidentity/runtime.ts
3961
- function detectRuntime() {
3962
- const versions = process.versions;
3963
- if (typeof versions.bun === "string" && versions.bun.length > 0) {
3964
- return { name: "bun", version: versions.bun };
3965
- }
3966
- if (typeof versions.node === "string" && versions.node.length > 0) {
3967
- return { name: "node", version: versions.node };
3968
- }
3969
- return { name: "unknown" };
3970
- }
3971
- function buildRuntimeInfo(options = {}) {
3972
- const runtime = detectRuntime();
3973
- const serviceName = options.serviceName ?? options.identity?.app.binary_name ?? "unknown-service";
3974
- const vendor = options.vendor ?? options.identity?.app.vendor;
3975
- return {
3976
- service: {
3977
- name: serviceName,
3978
- vendor,
3979
- version: options.version
3980
- },
3981
- runtime,
3982
- platform: {
3983
- os: process.platform,
3984
- arch: process.arch
3985
- }
3986
- };
3987
- }
3988
- var init_runtime = __esm({
3989
- "src/appidentity/runtime.ts"() {
3990
- }
3991
- });
3992
-
3993
- // src/foundry/signals/control-discovery-endpoint.ts
3994
- function createControlDiscoveryEndpoint(options) {
3995
- const { identity, version, endpoints, auth, authSummary, logger, telemetry } = options;
3996
- return async (req) => {
3997
- if (auth) {
3998
- const authResult = await auth(req);
3999
- if (!authResult.authenticated) {
4000
- if (logger) {
4001
- logger.warn("Control discovery endpoint: authentication failed", {
4002
- reason: authResult.reason
4003
- });
4004
- }
4005
- if (telemetry) {
4006
- telemetry.emit("fulmen.control.discovery.auth_failed", {
4007
- service: identity.app.binary_name
4008
- });
4009
- }
4010
- return {
4011
- status: "error",
4012
- error: "authentication_failed",
4013
- message: authResult.reason || "Authentication required",
4014
- statusCode: 401
4015
- };
4016
- }
4017
- }
4018
- if (telemetry) {
4019
- telemetry.emit("fulmen.control.discovery.served", {
4020
- service: identity.app.binary_name
4021
- });
4022
- }
4023
- const runtime = buildRuntimeInfo({ identity, version });
4024
- return {
4025
- status: "ok",
4026
- service: {
4027
- name: identity.app.binary_name,
4028
- vendor: identity.app.vendor,
4029
- version
4030
- },
4031
- runtime: {
4032
- name: runtime.runtime.name,
4033
- version: runtime.runtime.version,
4034
- platform: runtime.platform.os,
4035
- arch: runtime.platform.arch
4036
- },
4037
- auth_summary: authSummary,
4038
- endpoints,
4039
- statusCode: 200
4040
- };
4041
- };
4042
- }
4043
- var init_control_discovery_endpoint = __esm({
4044
- "src/foundry/signals/control-discovery-endpoint.ts"() {
4045
- init_runtime();
4046
- }
4047
- });
4048
-
4049
- // src/foundry/signals/convenience.ts
4050
- async function onShutdown(manager, handler, options = {}) {
4051
- await manager.register("SIGTERM", handler, options);
4052
- await manager.register("SIGINT", handler, options);
4053
- }
4054
- async function onReload(manager, handler, options = {}) {
4055
- await manager.register("SIGHUP", handler, options);
4056
- }
4057
- async function onUSR1(manager, handler, options = {}) {
4058
- await manager.register("SIGUSR1", handler, options);
4059
- }
4060
- async function onUSR2(manager, handler, options = {}) {
4061
- await manager.register("SIGUSR2", handler, options);
4062
- }
4063
- async function onEmergencyQuit(manager, handler, options = {}) {
4064
- await manager.register("SIGQUIT", handler, options);
4065
- }
4066
- async function onAnyShutdown(manager, handler, options = {}) {
4067
- await manager.register("SIGTERM", handler, options);
4068
- await manager.register("SIGINT", handler, options);
4069
- await manager.register("SIGQUIT", handler, options);
4070
- }
4071
- var init_convenience = __esm({
4072
- "src/foundry/signals/convenience.ts"() {
4073
- }
4074
- });
4075
-
4076
- // src/foundry/signals/double-tap.ts
4077
- async function createDoubleTapTracker(signalName, config = {}) {
4078
- const signal = await getSignal(signalName);
4079
- const defaultWindowMs = signal?.double_tap_window_seconds ? signal.double_tap_window_seconds * 1e3 : 2e3;
4080
- const defaultExitCode = signal?.double_tap_exit_code || 130;
4081
- const defaultHintMessage = signal?.double_tap_message || "Press Ctrl+C again within 2s to force quit";
4082
- return {
4083
- firstTapTime: null,
4084
- windowMs: config.windowMs ?? defaultWindowMs,
4085
- exitCode: config.exitCode ?? defaultExitCode,
4086
- hintMessage: config.hintMessage ?? defaultHintMessage,
4087
- logger: config.logger,
4088
- testMode: config.testMode ?? false
4089
- };
4090
- }
4091
- function handleDoubleTap(state) {
4092
- const now = Date.now();
4093
- if (state.firstTapTime === null) {
4094
- state.firstTapTime = now;
4095
- if (state.logger) {
4096
- state.logger.info(state.hintMessage);
4097
- } else {
4098
- console.log(state.hintMessage);
4099
- }
4100
- return false;
4101
- }
4102
- const elapsed = now - state.firstTapTime;
4103
- if (elapsed < state.windowMs) {
4104
- if (state.logger) {
4105
- state.logger.info("Force quitting...");
4106
- } else {
4107
- console.log("Force quitting...");
4108
- }
4109
- if (!state.testMode) {
4110
- process.exit(state.exitCode);
4111
- }
4112
- return true;
4113
- }
4114
- state.firstTapTime = now;
4115
- if (state.logger) {
4116
- state.logger.info(state.hintMessage);
4117
- } else {
4118
- console.log(state.hintMessage);
4119
- }
4120
- return false;
4121
- }
4122
- function resetDoubleTap(state) {
4123
- state.firstTapTime = null;
4124
- }
4125
- function isWithinWindow(state) {
4126
- if (state.firstTapTime === null) {
4127
- return false;
4128
- }
4129
- const elapsed = Date.now() - state.firstTapTime;
4130
- return elapsed < state.windowMs;
4131
- }
4132
- function getWindowTimeRemaining(state) {
4133
- if (state.firstTapTime === null) {
4134
- return null;
4135
- }
4136
- const elapsed = Date.now() - state.firstTapTime;
4137
- const remaining = state.windowMs - elapsed;
4138
- return remaining > 0 ? remaining : null;
4139
- }
4140
- var init_double_tap = __esm({
4141
- "src/foundry/signals/double-tap.ts"() {
4142
- init_catalog();
4143
- }
4144
- });
4145
-
4146
- // src/foundry/signals/windows.ts
4147
- async function handleWindowsFallback(signalName, options = {}) {
4148
- const signal = await getSignal(signalName);
4149
- if (!signal) {
4150
- return {
4151
- supported: false,
4152
- logged: false
4153
- };
4154
- }
4155
- if (signal.windows_event !== null) {
4156
- return {
4157
- supported: true,
4158
- logged: false
4159
- };
4160
- }
4161
- const fallback = signal.windows_fallback;
4162
- if (!fallback) {
4163
- return {
4164
- supported: false,
4165
- logged: false
4166
- };
4167
- }
4168
- if (options.silent) {
4169
- return {
4170
- supported: false,
4171
- fallback,
4172
- logged: false
4173
- };
4174
- }
4175
- const logger = options.logger || defaultLogger;
4176
- const telemetry = options.telemetry;
4177
- const logMeta = {
4178
- signal: signal.name,
4179
- platform: "windows",
4180
- fallback: fallback.fallback_behavior,
4181
- operation_hint: fallback.operation_hint
4182
- };
4183
- logger.info(fallback.log_message, logMeta);
4184
- if (telemetry) {
4185
- telemetry.emit(fallback.telemetry_event, fallback.telemetry_tags);
4186
- }
4187
- return {
4188
- supported: false,
4189
- fallback,
4190
- logged: true
4191
- };
4192
- }
4193
- async function getFallbackMetadata(signalName) {
4194
- const signal = await getSignal(signalName);
4195
- if (!signal || !signal.windows_fallback) {
4196
- return null;
4197
- }
4198
- return signal.windows_fallback;
4199
- }
4200
- async function requiresFallback(signalName) {
4201
- const signal = await getSignal(signalName);
4202
- if (!signal) {
4203
- return false;
4204
- }
4205
- return signal.windows_event === null && signal.windows_fallback !== void 0;
4206
- }
4207
- async function getHttpFallbackGuidance(signalName) {
4208
- const fallback = await getFallbackMetadata(signalName);
4209
- if (!fallback || fallback.fallback_behavior !== "http_admin_endpoint") {
4210
- return null;
4211
- }
4212
- return fallback.operation_hint;
4213
- }
4214
- var defaultLogger;
4215
- var init_windows = __esm({
4216
- "src/foundry/signals/windows.ts"() {
4217
- init_catalog();
4218
- defaultLogger = {
4219
- info(message, meta) {
4220
- if (meta) {
4221
- console.info(message, meta);
4222
- } else {
4223
- console.info(message);
4224
- }
4225
- },
4226
- warn(message, meta) {
4227
- if (meta) {
4228
- console.warn(message, meta);
4229
- } else {
4230
- console.warn(message);
4231
- }
4232
- }
4233
- };
4234
- }
4235
- });
4236
-
4237
- // src/foundry/signals/guards.ts
4238
- async function ensureSupported(signalName, options = {}) {
4239
- const { includeGuidance = true } = options;
4240
- const signal = await getSignal(signalName);
4241
- if (!signal) {
4242
- throw FoundryCatalogError.invalidSchema(
4243
- "signals",
4244
- `Signal "${signalName}" not found in catalog. Valid signals: SIGTERM, SIGINT, SIGHUP, SIGQUIT, SIGPIPE, SIGALRM, SIGUSR1, SIGUSR2`
4245
- );
4246
- }
4247
- const supported = await supportsSignal(signalName);
4248
- if (supported) {
4249
- return;
4250
- }
4251
- let message = `Signal ${signal.name} is not supported on this platform`;
4252
- if (isWindows2() && includeGuidance) {
4253
- const fallback = await getFallbackMetadata(signalName);
4254
- if (fallback) {
4255
- message += `. ${fallback.log_message}`;
4256
- switch (fallback.fallback_behavior) {
4257
- case "http_admin_endpoint":
4258
- message += `. Use HTTP endpoint: ${fallback.operation_hint}`;
4259
- break;
4260
- case "exception_handling":
4261
- message += `. Alternative: ${fallback.operation_hint}`;
4262
- break;
4263
- case "timer_api":
4264
- message += `. Alternative: ${fallback.operation_hint}`;
4265
- break;
4266
- }
4267
- }
4268
- }
4269
- throw FoundryCatalogError.invalidSchema("signals", message);
4270
- }
4271
- function ensureSignalExitCodesSupported() {
4272
- if (!isPOSIX2()) {
4273
- throw FoundryCatalogError.invalidSchema(
4274
- "signals",
4275
- "Signal-based exit codes (128+N pattern) are not supported on this platform. Windows does not propagate signal numbers via exit codes. Use explicit exit codes or monitor via HTTP admin endpoint."
4276
- );
4277
- }
4278
- }
4279
- function ensurePOSIX() {
4280
- if (!isPOSIX2()) {
4281
- throw FoundryCatalogError.invalidSchema(
4282
- "signals",
4283
- "This operation requires a POSIX-compliant platform (Linux, macOS, FreeBSD). Current platform does not support native signal handling."
4284
- );
4285
- }
4286
- }
4287
- function ensureWindows() {
4288
- if (!isWindows2()) {
4289
- throw FoundryCatalogError.invalidSchema(
4290
- "signals",
4291
- "This operation requires Windows platform. Current platform uses native signals."
4292
- );
4293
- }
4294
- }
4295
- var init_guards = __esm({
4296
- "src/foundry/signals/guards.ts"() {
4297
- init_errors2();
4298
- init_capabilities2();
4299
- init_catalog();
4300
- init_windows();
4301
- }
4302
- });
4303
-
4304
- // src/foundry/signals/http-helper.ts
4305
- function createSignalEndpoint(options) {
4306
- const { manager, auth, rateLimit, logger, telemetry, allowedSignals } = options;
4307
- return async (payload, req) => {
4308
- const correlationId = payload.correlation_id ?? generateCorrelationId2();
4309
- const authResult = await auth(req);
4310
- if (!authResult.authenticated) {
4311
- if (logger) {
4312
- logger.warn("Signal endpoint: authentication failed", {
4313
- correlation_id: correlationId,
4314
- reason: authResult.reason
4315
- });
4316
- }
4317
- if (telemetry) {
4318
- telemetry.emit("fulmen.signal.http_endpoint.auth_failed", {
4319
- correlation_id: correlationId
4320
- });
4321
- }
4322
- return {
4323
- status: "error",
4324
- error: "authentication_failed",
4325
- message: authResult.reason || "Authentication required",
4326
- statusCode: 401
4327
- };
4328
- }
4329
- const identity = authResult.identity || "unknown";
4330
- if (!payload.signal) {
4331
- return {
4332
- status: "error",
4333
- error: "invalid_request",
4334
- message: "Signal name is required",
4335
- statusCode: 400
4336
- };
4337
- }
4338
- const signalName = normalizeSignalName(payload.signal);
4339
- const defaultAllowed = [
4340
- "SIGHUP",
4341
- "SIGTERM",
4342
- "SIGINT",
4343
- "SIGQUIT",
4344
- "SIGUSR1",
4345
- "SIGUSR2",
4346
- "SIGPIPE",
4347
- "SIGALRM"
4348
- ];
4349
- const allowed = (allowedSignals || defaultAllowed).map((s) => normalizeSignalName(s));
4350
- if (!allowed.includes(signalName)) {
4351
- return {
4352
- status: "error",
4353
- error: "invalid_signal",
4354
- message: `Signal '${payload.signal}' is not recognized. Valid signals: ${allowed.join(", ")}`,
4355
- valid_signals: allowed,
4356
- statusCode: 400
4357
- };
4358
- }
4359
- const supported = await supportsSignal(signalName);
4360
- if (!supported) {
4361
- return {
4362
- status: "error",
4363
- error: "signal_not_supported",
4364
- message: `Signal ${signalName} is not supported on this platform`,
4365
- statusCode: 400
4366
- };
4367
- }
4368
- if (rateLimit) {
4369
- const rateLimitResult = await rateLimit(identity, signalName);
4370
- if (!rateLimitResult.allowed) {
4371
- if (logger) {
4372
- logger.warn("Signal endpoint: rate limit exceeded", {
4373
- correlation_id: correlationId,
4374
- identity,
4375
- signal: signalName
4376
- });
4377
- }
4378
- if (telemetry) {
4379
- telemetry.emit("fulmen.signal.http_endpoint.rate_limited", {
4380
- correlation_id: correlationId,
4381
- signal: signalName
4382
- });
4383
- }
4384
- return {
4385
- status: "error",
4386
- error: "rate_limit_exceeded",
4387
- message: "Rate limit exceeded. Please try again later.",
4388
- statusCode: 429
4389
- };
4390
- }
4391
- }
4392
- if (logger) {
4393
- logger.info("Signal endpoint: signal received", {
4394
- correlation_id: correlationId,
4395
- identity,
4396
- signal: signalName,
4397
- reason: payload.reason
4398
- });
4399
- }
4400
- if (telemetry) {
4401
- telemetry.emit("fulmen.signal.http_endpoint.signal_received", {
4402
- correlation_id: correlationId,
4403
- signal: signalName
4404
- });
4405
- }
4406
- void manager.trigger(signalName).catch((error) => {
4407
- if (logger) {
4408
- logger.warn("Signal handler execution failed", {
4409
- correlation_id: correlationId,
4410
- signal: signalName,
4411
- error: error instanceof Error ? error.message : String(error)
4412
- });
4413
- }
4414
- });
4415
- return {
4416
- status: "accepted",
4417
- signal: signalName,
4418
- correlation_id: correlationId,
4419
- message: "Signal will be processed asynchronously",
4420
- statusCode: 202
4421
- };
4422
- };
4423
- }
4424
- function normalizeSignalName(signal) {
4425
- const upper = signal.toUpperCase();
4426
- if (upper.startsWith("SIG")) {
4427
- return upper;
4428
- }
4429
- return `SIG${upper}`;
4430
- }
4431
- function generateCorrelationId2() {
4432
- return `sig-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
4433
- }
4434
- function createBearerTokenAuth(expectedToken) {
4435
- return (req) => {
4436
- const headers = req.headers;
4437
- const authHeader = headers?.authorization || headers?.Authorization;
4438
- if (!authHeader) {
4439
- return {
4440
- authenticated: false,
4441
- reason: "Missing Authorization header"
4442
- };
4443
- }
4444
- const [scheme, token] = authHeader.split(" ");
4445
- if (scheme !== "Bearer" || token !== expectedToken) {
4446
- return {
4447
- authenticated: false,
4448
- reason: "Invalid bearer token"
4449
- };
4450
- }
4451
- return {
4452
- authenticated: true,
4453
- identity: "bearer-token-user"
4454
- };
4455
- };
4456
- }
4457
- function createSimpleRateLimiter(requestsPerMinute) {
4458
- const requests = /* @__PURE__ */ new Map();
4459
- const windowMs = 6e4;
4460
- return (identity) => {
4461
- const now = Date.now();
4462
- const key = identity;
4463
- let timestamps = requests.get(key) || [];
4464
- timestamps = timestamps.filter((ts) => now - ts < windowMs);
4465
- if (timestamps.length >= requestsPerMinute) {
4466
- const oldestTimestamp = Math.min(...timestamps);
4467
- const resetAt = oldestTimestamp + windowMs;
4468
- return {
4469
- allowed: false,
4470
- remaining: 0,
4471
- reset_at: resetAt
4472
- };
4473
- }
4474
- timestamps.push(now);
4475
- requests.set(key, timestamps);
4476
- return {
4477
- allowed: true,
4478
- remaining: requestsPerMinute - timestamps.length,
4479
- reset_at: now + windowMs
4480
- };
4481
- };
4482
- }
4483
- var init_http_helper = __esm({
4484
- "src/foundry/signals/http-helper.ts"() {
4485
- init_capabilities2();
4486
- }
4487
- });
4488
-
4489
- // src/foundry/signals/manager.ts
4490
- function createSignalManager(options = {}) {
4491
- return new SignalManager(options);
4492
- }
4493
- var SignalManager;
4494
- var init_manager = __esm({
4495
- "src/foundry/signals/manager.ts"() {
4496
- init_capabilities2();
4497
- init_catalog();
4498
- init_double_tap();
4499
- init_windows();
4500
- SignalManager = class {
4501
- handlers = /* @__PURE__ */ new Map();
4502
- nativeListeners = /* @__PURE__ */ new Map();
4503
- options;
4504
- handlerIdCounter = 0;
4505
- doubleTapTrackers = /* @__PURE__ */ new Map();
4506
- shuttingDown = false;
4507
- constructor(options = {}) {
4508
- this.options = {
4509
- defaultTimeoutMs: options.defaultTimeoutMs ?? 3e4,
4510
- timeoutBehavior: options.timeoutBehavior ?? "log_and_continue",
4511
- testMode: options.testMode ?? false,
4512
- doubleTapWindowMs: options.doubleTapWindowMs ?? 2e3,
4513
- doubleTapExitCode: options.doubleTapExitCode ?? 130,
4514
- logger: options.logger,
4515
- telemetry: options.telemetry
4516
- };
4517
- }
4518
- /**
4519
- * Register a signal handler
4520
- *
4521
- * @param signal - Signal name (e.g., "SIGTERM") or NodeJS.Signals
4522
- * @param handler - Handler function
4523
- * @param options - Handler options
4524
- */
4525
- async register(signal, handler, options = {}) {
4526
- const signalName = typeof signal === "string" ? signal : signal;
4527
- const supported = await supportsSignal(signalName);
4528
- if (!supported) {
4529
- if (isWindows2()) {
4530
- await handleWindowsFallback(signalName, {
4531
- logger: this.options.logger,
4532
- telemetry: this.options.telemetry
4533
- });
4534
- }
4535
- return;
4536
- }
4537
- if (!this.handlers.has(signalName)) {
4538
- this.handlers.set(signalName, []);
4539
- }
4540
- const registration = {
4541
- signal: signalName,
4542
- handler,
4543
- priority: options.priority ?? 0,
4544
- timeoutMs: options.timeoutMs ?? this.options.defaultTimeoutMs,
4545
- id: options.id ?? `handler-${++this.handlerIdCounter}`,
4546
- registeredAt: Date.now()
4547
- };
4548
- const handlers = this.handlers.get(signalName);
4549
- if (!handlers) {
4550
- throw new Error(`Handler list not initialized for signal ${signalName}`);
4551
- }
4552
- handlers.push(registration);
4553
- handlers.sort((a, b) => {
4554
- if (a.priority !== b.priority) {
4555
- return b.priority - a.priority;
4556
- }
4557
- return a.registeredAt - b.registeredAt;
4558
- });
4559
- if (!this.nativeListeners.has(signalName)) {
4560
- await this.registerNativeListener(signalName);
4561
- }
4562
- if (this.options.logger) {
4563
- this.options.logger.info(`Signal handler registered: ${signalName}`, {
4564
- handler_id: registration.id,
4565
- priority: registration.priority,
4566
- timeout_ms: registration.timeoutMs
4567
- });
4568
- }
4569
- if (this.options.telemetry) {
4570
- this.options.telemetry.emit("fulmen.signal.handler_registered", {
4571
- signal: signalName,
4572
- handler_id: registration.id,
4573
- priority: String(registration.priority)
4574
- });
4575
- }
4576
- }
4577
- /**
4578
- * Register native Node.js signal listener
4579
- */
4580
- async registerNativeListener(signalName) {
4581
- const signal = await getSignal(signalName);
4582
- if (!signal) {
4583
- return;
4584
- }
4585
- const useDoubleTap = signal.default_behavior === "graceful_shutdown_with_double_tap";
4586
- if (useDoubleTap) {
4587
- const tracker = await createDoubleTapTracker(signalName, {
4588
- windowMs: this.options.doubleTapWindowMs,
4589
- exitCode: this.options.doubleTapExitCode,
4590
- logger: this.options.logger,
4591
- testMode: this.options.testMode
4592
- });
4593
- this.doubleTapTrackers.set(signalName, tracker);
4594
- }
4595
- const listener = async (sig) => {
4596
- if (useDoubleTap) {
4597
- const tracker = this.doubleTapTrackers.get(signalName);
4598
- if (tracker) {
4599
- const forceQuit = handleDoubleTap(tracker);
4600
- if (forceQuit) {
4601
- return;
4602
- }
4603
- }
4604
- }
4605
- await this.executeHandlers(signalName, sig);
4606
- };
4607
- process.on(signalName, listener);
4608
- this.nativeListeners.set(signalName, listener);
4609
- }
4610
- /**
4611
- * Execute all registered handlers for a signal
4612
- */
4613
- async executeHandlers(signalName, signal) {
4614
- const handlers = this.handlers.get(signalName);
4615
- if (!handlers || handlers.length === 0) {
4616
- return;
4617
- }
4618
- this.shuttingDown = true;
4619
- if (this.options.logger) {
4620
- this.options.logger.info(`Signal received: ${signalName}`, {
4621
- handler_count: handlers.length
4622
- });
4623
- }
4624
- for (const registration of handlers) {
4625
- try {
4626
- await this.executeWithTimeout(registration, signal);
4627
- } catch (error) {
4628
- if (this.options.logger) {
4629
- this.options.logger.warn(`Signal handler failed: ${signalName}`, {
4630
- handler_id: registration.id,
4631
- error: error instanceof Error ? error.message : String(error)
4632
- });
4633
- }
4634
- if (this.options.telemetry) {
4635
- this.options.telemetry.emit("fulmen.signal.handler_error", {
4636
- signal: signalName,
4637
- handler_id: registration.id,
4638
- error_type: error instanceof Error ? error.constructor.name : "unknown"
4639
- });
4640
- }
4641
- if (this.options.timeoutBehavior === "force_exit") {
4642
- const exitCode = (await getSignal(signalName))?.exit_code ?? 1;
4643
- if (!this.options.testMode) {
4644
- process.exit(exitCode);
4645
- }
4646
- return;
4647
- }
4648
- }
4649
- }
4650
- const tracker = this.doubleTapTrackers.get(signalName);
4651
- if (tracker) {
4652
- resetDoubleTap(tracker);
4653
- }
4654
- }
4655
- /**
4656
- * Execute a handler with timeout enforcement
4657
- */
4658
- async executeWithTimeout(registration, signal) {
4659
- const timeoutPromise = new Promise((_, reject) => {
4660
- setTimeout(() => {
4661
- reject(new Error(`Handler timeout exceeded: ${registration.timeoutMs}ms`));
4662
- }, registration.timeoutMs);
4663
- });
4664
- const handlerPromise = Promise.resolve(registration.handler(signal));
4665
- try {
4666
- await Promise.race([handlerPromise, timeoutPromise]);
4667
- if (this.options.telemetry) {
4668
- this.options.telemetry.emit("fulmen.signal.handler_completed", {
4669
- signal: registration.signal,
4670
- handler_id: registration.id
4671
- });
4672
- }
4673
- } catch (error) {
4674
- if (this.options.telemetry) {
4675
- this.options.telemetry.emit("fulmen.signal.handler_timeout", {
4676
- signal: registration.signal,
4677
- handler_id: registration.id,
4678
- timeout_ms: String(registration.timeoutMs)
4679
- });
4680
- }
4681
- throw error;
4682
- }
4683
- }
4684
- /**
4685
- * Unregister a signal handler
4686
- *
4687
- * @param signal - Signal name
4688
- * @param handler - Handler to remove (if not provided, removes all handlers)
4689
- */
4690
- unregister(signal, handler) {
4691
- const handlers = this.handlers.get(signal);
4692
- if (!handlers) {
4693
- return;
4694
- }
4695
- if (handler) {
4696
- const index = handlers.findIndex((h) => h.handler === handler);
4697
- if (index !== -1) {
4698
- handlers.splice(index, 1);
4699
- }
4700
- } else {
4701
- handlers.length = 0;
4702
- }
4703
- if (handlers.length === 0) {
4704
- const listener = this.nativeListeners.get(signal);
4705
- if (listener) {
4706
- process.off(signal, listener);
4707
- this.nativeListeners.delete(signal);
4708
- }
4709
- this.handlers.delete(signal);
4710
- }
4711
- }
4712
- /**
4713
- * Check if a signal has registered handlers
4714
- */
4715
- isRegistered(signal) {
4716
- const handlers = this.handlers.get(signal);
4717
- return handlers !== void 0 && handlers.length > 0;
4718
- }
4719
- /**
4720
- * Get handler count for a signal
4721
- */
4722
- getHandlerCount(signal) {
4723
- const handlers = this.handlers.get(signal);
4724
- return handlers?.length ?? 0;
4725
- }
4726
- /**
4727
- * Trigger signal handlers manually (for testing)
4728
- *
4729
- * @param signal - Signal name
4730
- */
4731
- async trigger(signal) {
4732
- const handlers = this.handlers.get(signal);
4733
- if (!handlers || handlers.length === 0) {
4734
- return;
4735
- }
4736
- await this.executeHandlers(signal, signal);
4737
- }
4738
- /**
4739
- * Shutdown the signal manager and cleanup all handlers
4740
- */
4741
- async shutdown() {
4742
- for (const [signal, listener] of this.nativeListeners.entries()) {
4743
- process.off(signal, listener);
4744
- }
4745
- this.nativeListeners.clear();
4746
- this.handlers.clear();
4747
- this.doubleTapTrackers.clear();
4748
- this.shuttingDown = false;
4749
- }
4750
- /**
4751
- * Check if manager is currently shutting down
4752
- */
4753
- isShuttingDown() {
4754
- return this.shuttingDown;
4755
- }
4756
- };
4757
- }
4758
- });
4759
-
4760
- // src/foundry/signals/reload.ts
4761
- function createConfigReloadHandler(options) {
4762
- const {
4763
- loader,
4764
- validator,
4765
- onValidated,
4766
- exitCode = 129,
4767
- logger,
4768
- telemetry,
4769
- testMode = false
4770
- } = options;
4771
- return async () => {
4772
- if (logger) {
4773
- logger.info("Config reload requested (SIGHUP)");
4774
- }
4775
- if (telemetry) {
4776
- telemetry.emit("fulmen.signal.config_reload_requested", {
4777
- signal: "SIGHUP"
4778
- });
4779
- }
4780
- try {
4781
- const newConfig = await loader();
4782
- const result = await validator(newConfig);
4783
- if (!result.valid) {
4784
- if (logger) {
4785
- logger.warn("Config validation failed - continuing with current config", {
4786
- error_count: result.errors?.length ?? 0,
4787
- errors: result.errors
4788
- });
4789
- }
4790
- if (telemetry) {
4791
- telemetry.emit("fulmen.signal.config_reload_rejected", {
4792
- signal: "SIGHUP",
4793
- reason: "validation_failed",
4794
- error_count: String(result.errors?.length ?? 0)
4795
- });
4796
- }
4797
- return;
4798
- }
4799
- if (logger) {
4800
- logger.info("Config validation succeeded - exiting for restart");
4801
- }
4802
- if (telemetry) {
4803
- telemetry.emit("fulmen.signal.config_reload_accepted", {
4804
- signal: "SIGHUP"
4805
- });
4806
- }
4807
- if (onValidated) {
4808
- await onValidated(newConfig);
4809
- }
4810
- if (!testMode) {
4811
- process.exit(exitCode);
4812
- }
4813
- } catch (error) {
4814
- if (logger) {
4815
- logger.warn("Config reload failed with error - continuing with current config", {
4816
- error: error instanceof Error ? error.message : String(error)
4817
- });
4818
- }
4819
- if (telemetry) {
4820
- telemetry.emit("fulmen.signal.config_reload_error", {
4821
- signal: "SIGHUP",
4822
- error_type: error instanceof Error ? error.constructor.name : "unknown"
4823
- });
4824
- }
4825
- }
4826
- };
4827
- }
4828
- var ConfigReloadTracker;
4829
- var init_reload = __esm({
4830
- "src/foundry/signals/reload.ts"() {
4831
- ConfigReloadTracker = class {
4832
- failures = 0;
4833
- lastFailureTime = null;
4834
- maxFailures;
4835
- logger;
4836
- telemetry;
4837
- constructor(options) {
4838
- this.maxFailures = options.maxFailures ?? 3;
4839
- this.logger = options.logger;
4840
- this.telemetry = options.telemetry;
4841
- }
4842
- /**
4843
- * Record a reload failure
4844
- *
4845
- * @returns true if threshold exceeded, false otherwise
4846
- */
4847
- recordFailure() {
4848
- this.failures++;
4849
- this.lastFailureTime = Date.now();
4850
- if (this.failures >= this.maxFailures) {
4851
- if (this.logger) {
4852
- this.logger.warn(
4853
- `${this.failures} consecutive config reload failures - check config source`,
4854
- {
4855
- failure_count: this.failures,
4856
- threshold: this.maxFailures
4857
- }
4858
- );
4859
- }
4860
- if (this.telemetry) {
4861
- this.telemetry.emit("fulmen.signal.config_reload_threshold_exceeded", {
4862
- failure_count: String(this.failures),
4863
- threshold: String(this.maxFailures)
4864
- });
4865
- }
4866
- return true;
4867
- }
4868
- return false;
4869
- }
4870
- /**
4871
- * Record a successful reload (resets counter)
4872
- */
4873
- recordSuccess() {
4874
- this.failures = 0;
4875
- this.lastFailureTime = null;
4876
- }
4877
- /**
4878
- * Get current failure count
4879
- */
4880
- getFailureCount() {
4881
- return this.failures;
4882
- }
4883
- /**
4884
- * Get last failure timestamp
4885
- */
4886
- getLastFailureTime() {
4887
- return this.lastFailureTime;
4888
- }
4889
- };
4890
- }
4891
- });
4892
-
4893
- // src/foundry/signals/index.ts
4894
- var init_signals = __esm({
4895
- "src/foundry/signals/index.ts"() {
4896
- init_capabilities2();
4897
- init_catalog();
4898
- init_config_reload_endpoint();
4899
- init_control_discovery_endpoint();
4900
- init_convenience();
4901
- init_double_tap();
4902
- init_guards();
4903
- init_http_helper();
4904
- init_manager();
4905
- init_reload();
4906
- init_windows();
4907
- }
4908
- });
4909
- function distance(a, b, metric = "levenshtein") {
4910
- switch (metric) {
4911
- case "levenshtein":
4912
- return levenshtein(a, b);
4913
- case "damerau_osa":
4914
- return osa_distance(a, b);
4915
- case "damerau_unrestricted":
4916
- return damerau_levenshtein(a, b);
4917
- case "jaro_winkler":
4918
- return jaro_winkler(a, b);
4919
- case "substring":
4920
- return substringSimilarity(a, b).score;
4921
- default:
4922
- throw new Error(
4923
- `Invalid metric '${metric}': must be one of: levenshtein, damerau_osa, damerau_unrestricted, jaro_winkler, substring`
4924
- );
4925
- }
4926
- }
4927
- var init_distance = __esm({
4928
- "src/foundry/similarity/distance.ts"() {
4929
- }
4930
- });
4931
-
4932
- // src/foundry/similarity/errors.ts
4933
- var init_errors3 = __esm({
4934
- "src/foundry/similarity/errors.ts"() {
4935
- init_errors2();
4936
- }
4937
- });
4938
- function toNormalizationLocale(locale) {
4939
- if (!locale) {
4940
- return void 0;
4941
- }
4942
- if (locale === "tr" || locale === "az" || locale === "lt") {
4943
- return locale;
4944
- }
4945
- return void 0;
4946
- }
4947
- function normalize(value, preset = "default", locale) {
4948
- if (typeof preset === "object") {
4949
- const targetPreset = preset.stripAccents ? "aggressive" : "default";
4950
- const targetLocale = toNormalizationLocale(preset.locale ?? locale);
4951
- return normalize$1(value, targetPreset, targetLocale);
4952
- }
4953
- return normalize$1(value, preset, toNormalizationLocale(locale));
4954
- }
4955
- function casefold(value, locale) {
4956
- if (locale === "tr") {
4957
- return value.toLocaleLowerCase("tr-TR");
4958
- }
4959
- return value.toLowerCase();
4960
- }
4961
- function stripAccents(value) {
4962
- return value.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
4963
- }
4964
- function equalsIgnoreCase(a, b, options) {
4965
- return normalize(a, options) === normalize(b, options);
4966
- }
4967
- var init_normalization = __esm({
4968
- "src/foundry/similarity/normalization.ts"() {
4969
- }
4970
- });
4971
- function score(a, b, metric = "levenshtein") {
4972
- if (metric === "substring") {
4973
- return substringSimilarity(a, b).score;
4974
- }
4975
- return score$1(a, b, metric);
4976
- }
4977
- var init_score = __esm({
4978
- "src/foundry/similarity/score.ts"() {
4979
- }
4980
- });
4981
- function suggest(input, candidates, options) {
4982
- const metric = options?.metric ?? DEFAULT_METRIC;
4983
- const minScore = options?.minScore ?? DEFAULT_MIN_SCORE;
4984
- const maxSuggestions = options?.maxSuggestions ?? DEFAULT_MAX_SUGGESTIONS;
4985
- let normalizePreset = options?.normalizePreset ?? DEFAULT_NORMALIZE_PRESET;
4986
- if (options?.normalize === false) {
4987
- normalizePreset = "none";
4988
- } else if (options?.normalize === true && !options?.normalizePreset) {
4989
- normalizePreset = "default";
4990
- }
4991
- const wasmOptions = {
4992
- metric,
4993
- normalizePreset,
4994
- minScore,
4995
- maxSuggestions,
4996
- preferPrefix: options?.preferPrefix,
4997
- jaroPrefixScale: options?.jaroPrefixScale,
4998
- jaroMaxPrefix: options?.jaroMaxPrefix
4999
- };
5000
- const results = suggest$1(input, candidates, wasmOptions);
5001
- return results.map((r) => ({
5002
- value: r.value,
5003
- score: r.score,
5004
- matchedRange: r.matchedRange,
5005
- reason: r.reason,
5006
- normalizedValue: r.normalizedValue
5007
- }));
5008
- }
5009
- var DEFAULT_MIN_SCORE, DEFAULT_MAX_SUGGESTIONS, DEFAULT_METRIC, DEFAULT_NORMALIZE_PRESET;
5010
- var init_suggest = __esm({
5011
- "src/foundry/similarity/suggest.ts"() {
5012
- DEFAULT_MIN_SCORE = 0.6;
5013
- DEFAULT_MAX_SUGGESTIONS = 3;
5014
- DEFAULT_METRIC = "levenshtein";
5015
- DEFAULT_NORMALIZE_PRESET = "default";
5016
- }
5017
- });
5018
-
5019
- // src/foundry/similarity/index.ts
5020
- var init_similarity = __esm({
5021
- "src/foundry/similarity/index.ts"() {
5022
- init_distance();
5023
- init_errors3();
5024
- init_normalization();
5025
- init_score();
5026
- init_suggest();
5027
- }
5028
- });
5029
-
5030
- // src/foundry/index.ts
5031
- var foundry_exports = {};
5032
- __export(foundry_exports, {
5033
- ConfigReloadTracker: () => ConfigReloadTracker,
5034
- EXIT_CODES_VERSION: () => EXIT_CODES_VERSION,
5035
- FoundryCatalogError: () => FoundryCatalogError,
5036
- SignalManager: () => SignalManager,
5037
- SimplifiedMode: () => SimplifiedMode,
5038
- VERSION: () => VERSION,
5039
- casefold: () => casefold,
5040
- clearCountryCodeCache: () => clearCountryCodeCache,
5041
- clearHttpStatusCache: () => clearHttpStatusCache,
5042
- clearMimeTypeCache: () => clearMimeTypeCache,
5043
- clearPatternCache: () => clearPatternCache,
5044
- createBearerTokenAuth: () => createBearerTokenAuth,
5045
- createConfigReloadEndpoint: () => createConfigReloadEndpoint,
5046
- createConfigReloadHandler: () => createConfigReloadHandler,
5047
- createControlDiscoveryEndpoint: () => createControlDiscoveryEndpoint,
5048
- createDoubleTapTracker: () => createDoubleTapTracker,
5049
- createSignalEndpoint: () => createSignalEndpoint,
5050
- createSignalManager: () => createSignalManager,
5051
- createSimpleRateLimiter: () => createSimpleRateLimiter,
5052
- describePattern: () => describePattern,
5053
- detectMimeType: () => detectMimeType,
5054
- detectMimeTypeFromBuffer: () => detectMimeTypeFromBuffer,
5055
- detectMimeTypeFromFile: () => detectMimeTypeFromFile,
5056
- detectMimeTypeFromStream: () => detectMimeTypeFromStream,
5057
- distance: () => distance,
5058
- ensurePOSIX: () => ensurePOSIX,
5059
- ensureSignalExitCodesSupported: () => ensureSignalExitCodesSupported,
5060
- ensureSupported: () => ensureSupported,
5061
- ensureWindows: () => ensureWindows,
5062
- equalsIgnoreCase: () => equalsIgnoreCase,
5063
- exitCodeMetadata: () => exitCodeMetadata,
5064
- exitCodes: () => exitCodes,
5065
- getBehavior: () => getBehavior,
5066
- getCountryByAlpha2: () => getCountryByAlpha2,
5067
- getCountryByAlpha3: () => getCountryByAlpha3,
5068
- getCountryByNumeric: () => getCountryByNumeric,
5069
- getExitCodeInfo: () => getExitCodeInfo,
5070
- getFallbackMetadata: () => getFallbackMetadata,
5071
- getHttpFallbackGuidance: () => getHttpFallbackGuidance,
5072
- getHttpStatus: () => getHttpStatus,
5073
- getMimeType: () => getMimeType,
5074
- getMimeTypeByExtension: () => getMimeTypeByExtension,
5075
- getPattern: () => getPattern,
5076
- getPatternRegex: () => getPatternRegex,
5077
- getPlatform: () => getPlatform,
5078
- getPlatformCapabilities: () => getPlatformCapabilities,
5079
- getSignal: () => getSignal,
5080
- getSignalCatalog: () => getSignalCatalog,
5081
- getSignalNumber: () => getSignalNumber,
5082
- getSignalPlatformCapabilities: () => getPlatformCapabilities2,
5083
- getSignalsVersion: () => getSignalsVersion,
5084
- getSimplifiedCodeDescription: () => getSimplifiedCodeDescription,
5085
- getSimplifiedCodes: () => getSimplifiedCodes,
5086
- getStatusReason: () => getStatusReason,
5087
- getWindowTimeRemaining: () => getWindowTimeRemaining,
5088
- getWindowsEvent: () => getWindowsEvent,
5089
- handleDoubleTap: () => handleDoubleTap,
5090
- handleWindowsFallback: () => handleWindowsFallback,
5091
- isClientError: () => isClientError,
5092
- isInformational: () => isInformational,
5093
- isPOSIX: () => isPOSIX,
5094
- isRedirection: () => isRedirection,
5095
- isServerError: () => isServerError,
5096
- isSignalPOSIX: () => isPOSIX2,
5097
- isSignalWindows: () => isWindows2,
5098
- isSuccess: () => isSuccess,
5099
- isSupportedMimeType: () => isSupportedMimeType,
5100
- isWindows: () => isWindows,
5101
- isWithinWindow: () => isWithinWindow,
5102
- listBehaviors: () => listBehaviors,
5103
- listCountries: () => listCountries,
5104
- listHttpStatuses: () => listHttpStatuses,
5105
- listMimeTypes: () => listMimeTypes,
5106
- listPatterns: () => listPatterns,
5107
- listSignals: () => listSignals,
5108
- loadAllCatalogs: () => loadAllCatalogs,
5109
- loadCountryCodeCatalog: () => loadCountryCodeCatalog,
5110
- loadHttpStatusCatalog: () => loadHttpStatusCatalog,
5111
- loadMimeTypeCatalog: () => loadMimeTypeCatalog,
5112
- loadPatternCatalog: () => loadPatternCatalog,
5113
- mapExitCodeToSimplified: () => mapExitCodeToSimplified,
5114
- matchMagicNumber: () => matchMagicNumber,
5115
- matchPattern: () => matchPattern,
5116
- normalize: () => normalize,
5117
- onAnyShutdown: () => onAnyShutdown,
5118
- onEmergencyQuit: () => onEmergencyQuit,
5119
- onReload: () => onReload,
5120
- onShutdown: () => onShutdown,
5121
- onUSR1: () => onUSR1,
5122
- onUSR2: () => onUSR2,
5123
- requiresFallback: () => requiresFallback,
5124
- resetDoubleTap: () => resetDoubleTap,
5125
- score: () => score,
5126
- stripAccents: () => stripAccents,
5127
- suggest: () => suggest,
5128
- supportsSignal: () => supportsSignal,
5129
- supportsSignalBasedExitCodes: () => supportsSignalExitCodes2,
5130
- supportsSignalExitCodes: () => supportsSignalExitCodes
5131
- });
5132
- var VERSION;
5133
- var init_foundry = __esm({
5134
- "src/foundry/index.ts"() {
5135
- init_country_codes();
5136
- init_errors2();
5137
- init_exit_codes();
5138
- init_http_statuses();
5139
- init_loader();
5140
- init_mime_types();
5141
- init_patterns();
5142
- init_signals();
5143
- init_similarity();
5144
- VERSION = "0.1.1";
5145
- }
5146
- });
5147
-
5148
- // src/appidentity/cache.ts
5149
- function getCachedIdentity() {
5150
- return cachedIdentity;
5151
- }
5152
- function setCachedIdentity(identity) {
5153
- cachedIdentity = identity;
5154
- }
5155
- function clearIdentityCache() {
5156
- cachedIdentity = null;
5157
- }
5158
- var cachedIdentity;
5159
- var init_cache = __esm({
5160
- "src/appidentity/cache.ts"() {
5161
- cachedIdentity = null;
1430
+ // src/schema/index.ts
1431
+ var init_schema = __esm({
1432
+ "src/schema/index.ts"() {
1433
+ init_ajv_formats();
1434
+ init_cli();
1435
+ init_errors();
1436
+ init_export();
1437
+ init_goneat_bridge();
1438
+ init_normalizer();
1439
+ init_registry();
1440
+ init_utils();
1441
+ init_validator();
5162
1442
  }
5163
1443
  });
5164
1444
  var init_correlation = __esm({
@@ -5485,7 +1765,7 @@ var init_fulmen_error = __esm({
5485
1765
  });
5486
1766
 
5487
1767
  // src/errors/index.ts
5488
- var init_errors4 = __esm({
1768
+ var init_errors2 = __esm({
5489
1769
  "src/errors/index.ts"() {
5490
1770
  init_correlation();
5491
1771
  init_fulmen_error();
@@ -5496,14 +1776,10 @@ var init_errors4 = __esm({
5496
1776
  });
5497
1777
 
5498
1778
  // src/appidentity/errors.ts
5499
- var errors_exports2 = {};
5500
- __export(errors_exports2, {
5501
- AppIdentityError: () => AppIdentityError
5502
- });
5503
1779
  var AppIdentityError;
5504
- var init_errors5 = __esm({
1780
+ var init_errors3 = __esm({
5505
1781
  "src/appidentity/errors.ts"() {
5506
- init_errors4();
1782
+ init_errors2();
5507
1783
  AppIdentityError = class _AppIdentityError extends FulmenError {
5508
1784
  identityPath;
5509
1785
  constructor(message, identityPath, cause) {
@@ -5629,6 +1905,82 @@ ${cause.message}`;
5629
1905
  };
5630
1906
  }
5631
1907
  });
1908
+ function deepFreeze(obj) {
1909
+ Object.freeze(obj);
1910
+ Object.getOwnPropertyNames(obj).forEach((prop) => {
1911
+ const value = obj[prop];
1912
+ if (value !== null && (typeof value === "object" || typeof value === "function") && !Object.isFrozen(value)) {
1913
+ deepFreeze(value);
1914
+ }
1915
+ });
1916
+ return obj;
1917
+ }
1918
+ async function registerEmbeddedIdentity(data) {
1919
+ if (isRegistered) {
1920
+ throw AppIdentityError.alreadyRegistered();
1921
+ }
1922
+ let identity;
1923
+ if (typeof data === "string") {
1924
+ let parsed;
1925
+ try {
1926
+ parsed = parse(data);
1927
+ } catch (error) {
1928
+ throw AppIdentityError.embeddedParseFailed(
1929
+ error instanceof Error ? error : new Error(String(error))
1930
+ );
1931
+ }
1932
+ const result = await validateDataBySchemaId(parsed, APP_IDENTITY_SCHEMA_ID);
1933
+ if (!result.valid) {
1934
+ throw AppIdentityError.embeddedValidationFailed(result.diagnostics);
1935
+ }
1936
+ identity = parsed;
1937
+ } else {
1938
+ const result = await validateDataBySchemaId(data, APP_IDENTITY_SCHEMA_ID);
1939
+ if (!result.valid) {
1940
+ throw AppIdentityError.embeddedValidationFailed(result.diagnostics);
1941
+ }
1942
+ identity = data;
1943
+ }
1944
+ embeddedIdentity = deepFreeze(structuredClone(identity));
1945
+ isRegistered = true;
1946
+ }
1947
+ function hasEmbeddedIdentity() {
1948
+ return isRegistered;
1949
+ }
1950
+ function getEmbeddedIdentity() {
1951
+ return embeddedIdentity;
1952
+ }
1953
+ function clearEmbeddedIdentity() {
1954
+ embeddedIdentity = null;
1955
+ isRegistered = false;
1956
+ }
1957
+ var embeddedIdentity, isRegistered;
1958
+ var init_embedded = __esm({
1959
+ "src/appidentity/embedded.ts"() {
1960
+ init_schema();
1961
+ init_constants();
1962
+ init_errors3();
1963
+ embeddedIdentity = null;
1964
+ isRegistered = false;
1965
+ }
1966
+ });
1967
+
1968
+ // src/appidentity/cache.ts
1969
+ function getCachedIdentity() {
1970
+ return cachedIdentity;
1971
+ }
1972
+ function setCachedIdentity(identity) {
1973
+ cachedIdentity = identity;
1974
+ }
1975
+ function clearIdentityCache() {
1976
+ cachedIdentity = null;
1977
+ }
1978
+ var cachedIdentity;
1979
+ var init_cache = __esm({
1980
+ "src/appidentity/cache.ts"() {
1981
+ cachedIdentity = null;
1982
+ }
1983
+ });
5632
1984
  async function discoverIdentityPath(options) {
5633
1985
  if (options?.path) {
5634
1986
  const exists = await fileExists(options.path);
@@ -5680,30 +2032,22 @@ async function fileExists(path) {
5680
2032
  var init_discovery = __esm({
5681
2033
  "src/appidentity/discovery.ts"() {
5682
2034
  init_constants();
5683
- init_errors5();
2035
+ init_errors3();
5684
2036
  }
5685
2037
  });
5686
-
5687
- // src/appidentity/loader.ts
5688
- var loader_exports = {};
5689
- __export(loader_exports, {
5690
- clearIdentityCache: () => clearIdentityCache,
5691
- getCachedIdentity: () => getCachedIdentity,
5692
- loadIdentity: () => loadIdentity
5693
- });
5694
- function deepFreeze5(obj) {
2038
+ function deepFreeze2(obj) {
5695
2039
  Object.freeze(obj);
5696
2040
  Object.getOwnPropertyNames(obj).forEach((prop) => {
5697
2041
  const value = obj[prop];
5698
2042
  if (value !== null && (typeof value === "object" || typeof value === "function") && !Object.isFrozen(value)) {
5699
- deepFreeze5(value);
2043
+ deepFreeze2(value);
5700
2044
  }
5701
2045
  });
5702
2046
  return obj;
5703
2047
  }
5704
2048
  async function loadIdentity(options) {
5705
2049
  if (options?.identity) {
5706
- return deepFreeze5(structuredClone(options.identity));
2050
+ return deepFreeze2(structuredClone(options.identity));
5707
2051
  }
5708
2052
  if (!options?.skipCache) {
5709
2053
  const cached = getCachedIdentity();
@@ -5761,399 +2105,61 @@ async function loadIdentity(options) {
5761
2105
  throw AppIdentityError.validationFailed(discovery.path, result.diagnostics);
5762
2106
  }
5763
2107
  }
5764
- const identity = deepFreeze5(structuredClone(parsed));
2108
+ const identity = deepFreeze2(structuredClone(parsed));
5765
2109
  setCachedIdentity(identity);
5766
2110
  return identity;
5767
2111
  }
5768
- var init_loader2 = __esm({
2112
+ var init_loader = __esm({
5769
2113
  "src/appidentity/loader.ts"() {
5770
2114
  init_schema();
5771
2115
  init_cache();
5772
2116
  init_constants();
5773
2117
  init_discovery();
5774
2118
  init_embedded();
5775
- init_errors5();
5776
- }
5777
- });
5778
- function createCLI(options = {}) {
5779
- const program = new Command();
5780
- program.name("tsfulmen-schema").description("Schema validation and discovery CLI for Fulmen (developer tool)").version("0.1.0");
5781
- program.command("list").description("List available schemas from registry").argument("[prefix]", "Filter schemas by prefix").option("--base-dir <path>", "Override schema base directory").action(async (prefix, cmdOptions) => {
5782
- try {
5783
- const schemas = await listSchemas(prefix, {
5784
- baseDir: cmdOptions?.baseDir || options.baseDir
5785
- });
5786
- if (schemas.length === 0) {
5787
- console.log("No schemas found");
5788
- return;
5789
- }
5790
- console.log(`Found ${schemas.length} schema(s):
5791
- `);
5792
- for (const schema of schemas) {
5793
- console.log(` ${schema.id}`);
5794
- console.log(` Format: ${schema.format}`);
5795
- console.log(` Path: ${schema.relativePath}`);
5796
- if (schema.description) {
5797
- console.log(` Description: ${schema.description}`);
5798
- }
5799
- console.log();
5800
- }
5801
- } catch (error) {
5802
- console.error("Error listing schemas:", error.message);
5803
- process.exit(1);
5804
- }
5805
- });
5806
- program.command("show").description("Show schema details").requiredOption("--schema-id <id>", "Schema ID to show").option("--base-dir <path>", "Override schema base directory").action(async (cmdOptions) => {
5807
- try {
5808
- const registry = getSchemaRegistry({
5809
- baseDir: cmdOptions.baseDir || options.baseDir
5810
- });
5811
- const schema = await registry.getSchema(cmdOptions.schemaId);
5812
- console.log("Schema Details:\n");
5813
- console.log(` ID: ${schema.id}`);
5814
- console.log(` Format: ${schema.format}`);
5815
- console.log(` Path: ${schema.path}`);
5816
- console.log(` Relative Path: ${schema.relativePath}`);
5817
- if (schema.version) {
5818
- console.log(` Version: ${schema.version}`);
5819
- }
5820
- if (schema.description) {
5821
- console.log(` Description: ${schema.description}`);
5822
- }
5823
- if (schema.schemaDraft) {
5824
- console.log(` Schema Draft: ${schema.schemaDraft}`);
5825
- }
5826
- const content = await readFile(schema.path, "utf-8");
5827
- console.log("\nSchema Content:");
5828
- console.log(content);
5829
- } catch (error) {
5830
- console.error("Error showing schema:", error.message);
5831
- process.exit(1);
5832
- }
5833
- });
5834
- program.command("validate").description("Validate data file against schema").requiredOption("--schema-id <id>", "Schema ID to validate against").argument("<file>", "Data file to validate").option("--use-goneat", "Use goneat for validation (requires goneat binary)").option("--goneat-path <path>", "Path to goneat binary").option("--base-dir <path>", "Override schema base directory").action(
5835
- async (file, cmdOptions) => {
5836
- try {
5837
- let result;
5838
- if (cmdOptions.useGoneat) {
5839
- const available = await isGoneatAvailable(cmdOptions.goneatPath);
5840
- if (!available) {
5841
- console.error("\u274C goneat not available. Install goneat or remove --use-goneat flag.");
5842
- console.error(" AJV validation (default) works without external dependencies.");
5843
- process.exit(1);
5844
- }
5845
- const registry = getSchemaRegistry({
5846
- baseDir: cmdOptions.baseDir || options.baseDir
5847
- });
5848
- const schema = await registry.getSchema(cmdOptions.schemaId);
5849
- console.log("Using goneat validation...");
5850
- result = await runGoneatValidation(schema.path, file, cmdOptions.goneatPath);
5851
- } else {
5852
- console.log("Using AJV validation...");
5853
- result = await validateFileBySchemaId(file, cmdOptions.schemaId, {
5854
- baseDir: cmdOptions.baseDir || options.baseDir
5855
- });
5856
- }
5857
- if (result.valid) {
5858
- console.log(`\u2705 Validation passed (${result.source})`);
5859
- process.exit(0);
5860
- } else {
5861
- console.log(`\u274C Validation failed (${result.source})`);
5862
- console.log("\nDiagnostics:");
5863
- console.log(formatDiagnostics(result.diagnostics));
5864
- process.exit(1);
5865
- }
5866
- } catch (error) {
5867
- console.error("Error validating file:", error.message);
5868
- process.exit(1);
5869
- }
5870
- }
5871
- );
5872
- program.command("validate-schema").description("Validate a schema file itself").argument("<file>", "Schema file to validate").action(async (file) => {
5873
- try {
5874
- const content = await readFile(file, "utf-8");
5875
- const { validateSchema: validateSchema2 } = await Promise.resolve().then(() => (init_validator(), validator_exports));
5876
- const result = await validateSchema2(content);
5877
- if (result.valid) {
5878
- console.log("\u2705 Schema is valid");
5879
- process.exit(0);
5880
- } else {
5881
- console.log("\u274C Schema is invalid");
5882
- console.log("\nDiagnostics:");
5883
- console.log(formatDiagnostics(result.diagnostics));
5884
- process.exit(1);
5885
- }
5886
- } catch (error) {
5887
- console.error("Error validating schema:", error.message);
5888
- process.exit(1);
5889
- }
5890
- });
5891
- program.command("normalize").description("Normalize schema to canonical JSON format").argument("<file>", "Schema file to normalize").option("--compact", "Output compact JSON (no formatting)").option("-o, --output <file>", "Write to output file instead of stdout").action(async (file, cmdOptions) => {
5892
- try {
5893
- const content = await readFile(file, "utf-8");
5894
- const normalized = normalizeSchema(content, {
5895
- compact: cmdOptions.compact
5896
- });
5897
- if (cmdOptions.output) {
5898
- await writeFile(cmdOptions.output, normalized, "utf-8");
5899
- console.log(`\u2705 Normalized schema written to ${cmdOptions.output}`);
5900
- } else {
5901
- console.log(normalized);
5902
- }
5903
- } catch (error) {
5904
- console.error("Error normalizing schema:", error.message);
5905
- process.exit(1);
5906
- }
5907
- });
5908
- program.command("compare").description("Compare two schemas for semantic equality").argument("<file1>", "First schema file").argument("<file2>", "Second schema file").option("--show-normalized", "Show normalized outputs").action(async (file1, file2, cmdOptions) => {
5909
- try {
5910
- const content1 = await readFile(file1, "utf-8");
5911
- const content2 = await readFile(file2, "utf-8");
5912
- const result = compareSchemas(content1, content2);
5913
- if (result.equal) {
5914
- console.log("\u2705 Schemas are semantically equal");
5915
- } else {
5916
- console.log("\u274C Schemas differ");
5917
- }
5918
- if (cmdOptions.showNormalized) {
5919
- console.log("\nNormalized Schema 1:");
5920
- console.log(result.normalizedA);
5921
- console.log("\nNormalized Schema 2:");
5922
- console.log(result.normalizedB);
5923
- }
5924
- process.exit(result.equal ? 0 : 1);
5925
- } catch (error) {
5926
- console.error("Error comparing schemas:", error.message);
5927
- process.exit(1);
5928
- }
5929
- });
5930
- program.command("export").description("Export schema from registry to file with provenance").requiredOption("--schema-id <id>", "Schema ID to export").requiredOption("--out <path>", "Output file path").option("--force", "Overwrite existing file", false).option("--no-provenance", "Exclude provenance metadata").option("--no-validate", "Skip schema validation before export").option("--format <format>", "Export format (json|yaml|auto)", "auto").option("--base-dir <path>", "Override schema base directory").action(
5931
- async (cmdOptions) => {
5932
- try {
5933
- const { exportSchema: exportSchema2 } = await Promise.resolve().then(() => (init_export(), export_exports));
5934
- const { exitCodes: exitCodes2 } = await Promise.resolve().then(() => (init_foundry(), foundry_exports));
5935
- const result = await exportSchema2({
5936
- schemaId: cmdOptions.schemaId,
5937
- outPath: cmdOptions.out,
5938
- includeProvenance: cmdOptions.provenance ?? true,
5939
- validate: cmdOptions.validate ?? true,
5940
- overwrite: cmdOptions.force ?? false,
5941
- format: cmdOptions.format ?? "auto",
5942
- baseDir: cmdOptions.baseDir || options.baseDir
5943
- });
5944
- console.log("\u2705 Schema exported successfully");
5945
- console.log(` Schema ID: ${result.schemaId}`);
5946
- console.log(` Output: ${result.outPath}`);
5947
- console.log(` Format: ${result.format}`);
5948
- if (result.provenance) {
5949
- console.log("\nProvenance:");
5950
- console.log(` Crucible: ${result.provenance.crucible_version}`);
5951
- console.log(` Library: ${result.provenance.library_version}`);
5952
- if (result.provenance.revision) {
5953
- console.log(` Revision: ${result.provenance.revision}`);
5954
- }
5955
- console.log(` Exported: ${result.provenance.exported_at}`);
5956
- }
5957
- process.exit(exitCodes2.EXIT_SUCCESS);
5958
- } catch (error) {
5959
- const { exitCodes: exitCodes2 } = await Promise.resolve().then(() => (init_foundry(), foundry_exports));
5960
- const { SchemaExportError: SchemaExportError2, SchemaValidationError: SchemaValidationError2, ExportErrorReason: ExportErrorReason2 } = await Promise.resolve().then(() => (init_errors(), errors_exports));
5961
- console.error("\u274C Schema export failed:", error.message);
5962
- if (error instanceof SchemaExportError2) {
5963
- if (error.outPath) {
5964
- console.error(` Output path: ${error.outPath}`);
5965
- }
5966
- switch (error.reason) {
5967
- case ExportErrorReason2.FILE_EXISTS:
5968
- case ExportErrorReason2.WRITE_FAILED:
5969
- process.exit(exitCodes2.EXIT_FILE_WRITE_ERROR);
5970
- break;
5971
- case ExportErrorReason2.INVALID_FORMAT:
5972
- process.exit(exitCodes2.EXIT_INVALID_ARGUMENT);
5973
- break;
5974
- default:
5975
- process.exit(exitCodes2.EXIT_FAILURE);
5976
- }
5977
- }
5978
- if (error instanceof SchemaValidationError2) {
5979
- const errorMsg = error.message.toLowerCase();
5980
- if (errorMsg.includes("not found")) {
5981
- process.exit(exitCodes2.EXIT_FILE_NOT_FOUND);
5982
- }
5983
- process.exit(exitCodes2.EXIT_DATA_INVALID);
5984
- }
5985
- process.exit(exitCodes2.EXIT_FAILURE);
5986
- }
5987
- }
5988
- );
5989
- program.command("identity-show").description("Show application identity from .fulmen/app.yaml").option("--path <path>", "Explicit path to app.yaml").option("--json", "Output as JSON").action(async (cmdOptions) => {
5990
- try {
5991
- const { loadIdentity: loadIdentity2 } = await Promise.resolve().then(() => (init_loader2(), loader_exports));
5992
- const { exitCodes: exitCodes2 } = await Promise.resolve().then(() => (init_foundry(), foundry_exports));
5993
- const identity = await loadIdentity2({ path: cmdOptions.path });
5994
- if (cmdOptions.json) {
5995
- console.log(JSON.stringify(identity, null, 2));
5996
- } else {
5997
- console.log("Application Identity:\n");
5998
- console.log(` Binary Name: ${identity.app.binary_name}`);
5999
- console.log(` Vendor: ${identity.app.vendor}`);
6000
- console.log(` Env Prefix: ${identity.app.env_prefix}`);
6001
- console.log(` Config Name: ${identity.app.config_name}`);
6002
- console.log(` Description: ${identity.app.description}`);
6003
- if (identity.metadata) {
6004
- console.log("\nMetadata:");
6005
- if (identity.metadata.license) {
6006
- console.log(` License: ${identity.metadata.license}`);
6007
- }
6008
- if (identity.metadata.repository_category) {
6009
- console.log(` Category: ${identity.metadata.repository_category}`);
6010
- }
6011
- if (identity.metadata.telemetry_namespace) {
6012
- console.log(` Telemetry: ${identity.metadata.telemetry_namespace}`);
6013
- }
6014
- if (identity.metadata.project_url) {
6015
- console.log(` Project URL: ${identity.metadata.project_url}`);
6016
- }
6017
- }
6018
- }
6019
- process.exit(exitCodes2.EXIT_SUCCESS);
6020
- } catch (error) {
6021
- const { exitCodes: exitCodes2 } = await Promise.resolve().then(() => (init_foundry(), foundry_exports));
6022
- const { AppIdentityError: AppIdentityError2 } = await Promise.resolve().then(() => (init_errors5(), errors_exports2));
6023
- console.error("\u274C Failed to load identity:", error.message);
6024
- if (error instanceof AppIdentityError2) {
6025
- if (error.message.includes("not found")) {
6026
- process.exit(exitCodes2.EXIT_FILE_NOT_FOUND);
6027
- }
6028
- if (error.message.includes("Invalid") || error.message.includes("validation")) {
6029
- process.exit(exitCodes2.EXIT_DATA_INVALID);
6030
- }
6031
- }
6032
- process.exit(exitCodes2.EXIT_FAILURE);
6033
- }
6034
- });
6035
- program.command("identity-validate").description("Validate application identity against schema").argument("[file]", "Path to app.yaml (defaults to discovery)").action(async (file) => {
6036
- try {
6037
- const { loadIdentity: loadIdentity2 } = await Promise.resolve().then(() => (init_loader2(), loader_exports));
6038
- const { exitCodes: exitCodes2 } = await Promise.resolve().then(() => (init_foundry(), foundry_exports));
6039
- console.log("Validating application identity...");
6040
- const identity = await loadIdentity2({ path: file });
6041
- console.log("\u2705 Identity is valid");
6042
- console.log(` Binary: ${identity.app.binary_name}`);
6043
- console.log(` Vendor: ${identity.app.vendor}`);
6044
- process.exit(exitCodes2.EXIT_SUCCESS);
6045
- } catch (error) {
6046
- const { exitCodes: exitCodes2 } = await Promise.resolve().then(() => (init_foundry(), foundry_exports));
6047
- const { AppIdentityError: AppIdentityError2 } = await Promise.resolve().then(() => (init_errors5(), errors_exports2));
6048
- console.error("\u274C Identity validation failed:", error.message);
6049
- if (error instanceof AppIdentityError2) {
6050
- if (error.message.includes("not found")) {
6051
- process.exit(exitCodes2.EXIT_FILE_NOT_FOUND);
6052
- }
6053
- if (error.message.includes("Invalid") || error.message.includes("validation")) {
6054
- process.exit(exitCodes2.EXIT_DATA_INVALID);
6055
- }
6056
- }
6057
- process.exit(exitCodes2.EXIT_FAILURE);
6058
- }
6059
- });
6060
- return program;
6061
- }
6062
- var init_cli = __esm({
6063
- "src/schema/cli.ts"() {
6064
- init_goneat_bridge();
6065
- init_normalizer();
6066
- init_registry();
6067
- init_utils();
6068
- init_validator();
6069
- if (import.meta.url === `file://${process.argv[1]}`) {
6070
- const program = createCLI();
6071
- program.parse(process.argv);
6072
- }
2119
+ init_errors3();
6073
2120
  }
6074
2121
  });
6075
2122
 
6076
- // src/schema/index.ts
6077
- var init_schema = __esm({
6078
- "src/schema/index.ts"() {
6079
- init_ajv_formats();
6080
- init_cli();
6081
- init_errors();
6082
- init_export();
6083
- init_goneat_bridge();
6084
- init_normalizer();
6085
- init_registry();
6086
- init_utils();
6087
- init_validator();
6088
- }
6089
- });
6090
- function deepFreeze6(obj) {
6091
- Object.freeze(obj);
6092
- Object.getOwnPropertyNames(obj).forEach((prop) => {
6093
- const value = obj[prop];
6094
- if (value !== null && (typeof value === "object" || typeof value === "function") && !Object.isFrozen(value)) {
6095
- deepFreeze6(value);
6096
- }
6097
- });
6098
- return obj;
6099
- }
6100
- async function registerEmbeddedIdentity(data) {
6101
- if (isRegistered) {
6102
- throw AppIdentityError.alreadyRegistered();
2123
+ // src/appidentity/runtime.ts
2124
+ function detectRuntime() {
2125
+ const versions = process.versions;
2126
+ if (typeof versions.bun === "string" && versions.bun.length > 0) {
2127
+ return { name: "bun", version: versions.bun };
6103
2128
  }
6104
- let identity;
6105
- if (typeof data === "string") {
6106
- let parsed;
6107
- try {
6108
- parsed = parse(data);
6109
- } catch (error) {
6110
- throw AppIdentityError.embeddedParseFailed(
6111
- error instanceof Error ? error : new Error(String(error))
6112
- );
6113
- }
6114
- const result = await validateDataBySchemaId(parsed, APP_IDENTITY_SCHEMA_ID);
6115
- if (!result.valid) {
6116
- throw AppIdentityError.embeddedValidationFailed(result.diagnostics);
6117
- }
6118
- identity = parsed;
6119
- } else {
6120
- const result = await validateDataBySchemaId(data, APP_IDENTITY_SCHEMA_ID);
6121
- if (!result.valid) {
6122
- throw AppIdentityError.embeddedValidationFailed(result.diagnostics);
6123
- }
6124
- identity = data;
2129
+ if (typeof versions.node === "string" && versions.node.length > 0) {
2130
+ return { name: "node", version: versions.node };
6125
2131
  }
6126
- embeddedIdentity = deepFreeze6(structuredClone(identity));
6127
- isRegistered = true;
6128
- }
6129
- function hasEmbeddedIdentity() {
6130
- return isRegistered;
6131
- }
6132
- function getEmbeddedIdentity() {
6133
- return embeddedIdentity;
2132
+ return { name: "unknown" };
6134
2133
  }
6135
- function clearEmbeddedIdentity() {
6136
- embeddedIdentity = null;
6137
- isRegistered = false;
2134
+ function buildRuntimeInfo(options = {}) {
2135
+ const runtime = detectRuntime();
2136
+ const serviceName = options.serviceName ?? options.identity?.app.binary_name ?? "unknown-service";
2137
+ const vendor = options.vendor ?? options.identity?.app.vendor;
2138
+ return {
2139
+ service: {
2140
+ name: serviceName,
2141
+ vendor,
2142
+ version: options.version
2143
+ },
2144
+ runtime,
2145
+ platform: {
2146
+ os: process.platform,
2147
+ arch: process.arch
2148
+ }
2149
+ };
6138
2150
  }
6139
- var embeddedIdentity, isRegistered;
6140
- var init_embedded = __esm({
6141
- "src/appidentity/embedded.ts"() {
6142
- init_schema();
6143
- init_constants();
6144
- init_errors5();
6145
- embeddedIdentity = null;
6146
- isRegistered = false;
2151
+ var init_runtime = __esm({
2152
+ "src/appidentity/runtime.ts"() {
6147
2153
  }
6148
2154
  });
6149
2155
 
6150
2156
  // src/appidentity/index.ts
6151
2157
  init_constants();
6152
2158
  init_embedded();
6153
- init_errors5();
2159
+ init_errors3();
6154
2160
 
6155
2161
  // src/appidentity/helpers.ts
6156
- init_loader2();
2162
+ init_loader();
6157
2163
  async function getBinaryName(options) {
6158
2164
  const identity = await loadIdentity(options);
6159
2165
  return identity.app.binary_name;
@@ -6192,7 +2198,7 @@ async function getEnvVar(key, options) {
6192
2198
  }
6193
2199
 
6194
2200
  // src/appidentity/index.ts
6195
- init_loader2();
2201
+ init_loader();
6196
2202
  init_runtime();
6197
2203
 
6198
2204
  export { APP_IDENTITY_DIR, APP_IDENTITY_ENV_VAR, APP_IDENTITY_FILENAME, APP_IDENTITY_SCHEMA_ID, AppIdentityError, MAX_ANCESTOR_SEARCH_DEPTH, buildEnvVar, buildRuntimeInfo, clearEmbeddedIdentity, clearIdentityCache, getBinaryName, getCachedIdentity, getConfigIdentifiers, getConfigName, getEmbeddedIdentity, getEnvPrefix, getEnvVar, getTelemetryNamespace, getVendor, hasEmbeddedIdentity, loadIdentity, registerEmbeddedIdentity };