emviz 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -105,7 +105,7 @@ var require_path = __commonJS({
105
105
  Object.defineProperty(exports, "__esModule", { value: true });
106
106
  exports.convertPosixPathToPattern = exports.convertWindowsPathToPattern = exports.convertPathToPattern = exports.escapePosixPath = exports.escapeWindowsPath = exports.escape = exports.removeLeadingDotSegment = exports.makeAbsolute = exports.unixify = void 0;
107
107
  var os2 = __require("os");
108
- var path6 = __require("path");
108
+ var path8 = __require("path");
109
109
  var IS_WINDOWS_PLATFORM = os2.platform() === "win32";
110
110
  var LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2;
111
111
  var POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g;
@@ -117,7 +117,7 @@ var require_path = __commonJS({
117
117
  }
118
118
  exports.unixify = unixify;
119
119
  function makeAbsolute(cwd, filepath) {
120
- return path6.resolve(cwd, filepath);
120
+ return path8.resolve(cwd, filepath);
121
121
  }
122
122
  exports.makeAbsolute = makeAbsolute;
123
123
  function removeLeadingDotSegment(entry) {
@@ -1414,7 +1414,7 @@ var require_braces = __commonJS({
1414
1414
  var require_constants2 = __commonJS({
1415
1415
  "../../node_modules/.pnpm/picomatch@2.3.2/node_modules/picomatch/lib/constants.js"(exports, module) {
1416
1416
  "use strict";
1417
- var path6 = __require("path");
1417
+ var path8 = __require("path");
1418
1418
  var WIN_SLASH = "\\\\/";
1419
1419
  var WIN_NO_SLASH = `[^${WIN_SLASH}]`;
1420
1420
  var DEFAULT_MAX_EXTGLOB_RECURSION = 0;
@@ -1588,7 +1588,7 @@ var require_constants2 = __commonJS({
1588
1588
  /* | */
1589
1589
  CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
1590
1590
  /* \uFEFF */
1591
- SEP: path6.sep,
1591
+ SEP: path8.sep,
1592
1592
  /**
1593
1593
  * Create EXTGLOB_CHARS
1594
1594
  */
@@ -1615,7 +1615,7 @@ var require_constants2 = __commonJS({
1615
1615
  var require_utils2 = __commonJS({
1616
1616
  "../../node_modules/.pnpm/picomatch@2.3.2/node_modules/picomatch/lib/utils.js"(exports) {
1617
1617
  "use strict";
1618
- var path6 = __require("path");
1618
+ var path8 = __require("path");
1619
1619
  var win32 = process.platform === "win32";
1620
1620
  var {
1621
1621
  REGEX_BACKSLASH,
@@ -1644,7 +1644,7 @@ var require_utils2 = __commonJS({
1644
1644
  if (options && typeof options.windows === "boolean") {
1645
1645
  return options.windows;
1646
1646
  }
1647
- return win32 === true || path6.sep === "\\";
1647
+ return win32 === true || path8.sep === "\\";
1648
1648
  };
1649
1649
  exports.escapeLast = (input, char, lastIdx) => {
1650
1650
  const idx = input.lastIndexOf(char, lastIdx);
@@ -3008,7 +3008,7 @@ var require_parse2 = __commonJS({
3008
3008
  var require_picomatch = __commonJS({
3009
3009
  "../../node_modules/.pnpm/picomatch@2.3.2/node_modules/picomatch/lib/picomatch.js"(exports, module) {
3010
3010
  "use strict";
3011
- var path6 = __require("path");
3011
+ var path8 = __require("path");
3012
3012
  var scan = require_scan();
3013
3013
  var parse = require_parse2();
3014
3014
  var utils = require_utils2();
@@ -3093,7 +3093,7 @@ var require_picomatch = __commonJS({
3093
3093
  };
3094
3094
  picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
3095
3095
  const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
3096
- return regex.test(path6.basename(input));
3096
+ return regex.test(path8.basename(input));
3097
3097
  };
3098
3098
  picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
3099
3099
  picomatch.parse = (pattern, options) => {
@@ -3320,7 +3320,7 @@ var require_pattern = __commonJS({
3320
3320
  "use strict";
3321
3321
  Object.defineProperty(exports, "__esModule", { value: true });
3322
3322
  exports.isAbsolute = exports.partitionAbsoluteAndRelative = exports.removeDuplicateSlashes = exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0;
3323
- var path6 = __require("path");
3323
+ var path8 = __require("path");
3324
3324
  var globParent = require_glob_parent();
3325
3325
  var micromatch = require_micromatch();
3326
3326
  var GLOBSTAR = "**";
@@ -3415,8 +3415,8 @@ var require_pattern = __commonJS({
3415
3415
  }
3416
3416
  exports.endsWithSlashGlobStar = endsWithSlashGlobStar;
3417
3417
  function isAffectDepthOfReadingPattern(pattern) {
3418
- const basename = path6.basename(pattern);
3419
- return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
3418
+ const basename2 = path8.basename(pattern);
3419
+ return endsWithSlashGlobStar(pattern) || isStaticPattern(basename2);
3420
3420
  }
3421
3421
  exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
3422
3422
  function expandPatternsWithBraceExpansion(patterns) {
@@ -3473,7 +3473,7 @@ var require_pattern = __commonJS({
3473
3473
  }
3474
3474
  exports.partitionAbsoluteAndRelative = partitionAbsoluteAndRelative;
3475
3475
  function isAbsolute(pattern) {
3476
- return path6.isAbsolute(pattern);
3476
+ return path8.isAbsolute(pattern);
3477
3477
  }
3478
3478
  exports.isAbsolute = isAbsolute;
3479
3479
  }
@@ -3648,10 +3648,10 @@ var require_utils3 = __commonJS({
3648
3648
  exports.array = array;
3649
3649
  var errno = require_errno();
3650
3650
  exports.errno = errno;
3651
- var fs6 = require_fs();
3652
- exports.fs = fs6;
3653
- var path6 = require_path();
3654
- exports.path = path6;
3651
+ var fs8 = require_fs();
3652
+ exports.fs = fs8;
3653
+ var path8 = require_path();
3654
+ exports.path = path8;
3655
3655
  var pattern = require_pattern();
3656
3656
  exports.pattern = pattern;
3657
3657
  var stream = require_stream();
@@ -3763,8 +3763,8 @@ var require_async = __commonJS({
3763
3763
  "use strict";
3764
3764
  Object.defineProperty(exports, "__esModule", { value: true });
3765
3765
  exports.read = void 0;
3766
- function read(path6, settings, callback) {
3767
- settings.fs.lstat(path6, (lstatError, lstat) => {
3766
+ function read(path8, settings, callback) {
3767
+ settings.fs.lstat(path8, (lstatError, lstat) => {
3768
3768
  if (lstatError !== null) {
3769
3769
  callFailureCallback(callback, lstatError);
3770
3770
  return;
@@ -3773,7 +3773,7 @@ var require_async = __commonJS({
3773
3773
  callSuccessCallback(callback, lstat);
3774
3774
  return;
3775
3775
  }
3776
- settings.fs.stat(path6, (statError, stat) => {
3776
+ settings.fs.stat(path8, (statError, stat) => {
3777
3777
  if (statError !== null) {
3778
3778
  if (settings.throwErrorOnBrokenSymbolicLink) {
3779
3779
  callFailureCallback(callback, statError);
@@ -3805,13 +3805,13 @@ var require_sync = __commonJS({
3805
3805
  "use strict";
3806
3806
  Object.defineProperty(exports, "__esModule", { value: true });
3807
3807
  exports.read = void 0;
3808
- function read(path6, settings) {
3809
- const lstat = settings.fs.lstatSync(path6);
3808
+ function read(path8, settings) {
3809
+ const lstat = settings.fs.lstatSync(path8);
3810
3810
  if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
3811
3811
  return lstat;
3812
3812
  }
3813
3813
  try {
3814
- const stat = settings.fs.statSync(path6);
3814
+ const stat = settings.fs.statSync(path8);
3815
3815
  if (settings.markSymbolicLink) {
3816
3816
  stat.isSymbolicLink = () => true;
3817
3817
  }
@@ -3833,12 +3833,12 @@ var require_fs2 = __commonJS({
3833
3833
  "use strict";
3834
3834
  Object.defineProperty(exports, "__esModule", { value: true });
3835
3835
  exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
3836
- var fs6 = __require("fs");
3836
+ var fs8 = __require("fs");
3837
3837
  exports.FILE_SYSTEM_ADAPTER = {
3838
- lstat: fs6.lstat,
3839
- stat: fs6.stat,
3840
- lstatSync: fs6.lstatSync,
3841
- statSync: fs6.statSync
3838
+ lstat: fs8.lstat,
3839
+ stat: fs8.stat,
3840
+ lstatSync: fs8.lstatSync,
3841
+ statSync: fs8.statSync
3842
3842
  };
3843
3843
  function createFileSystemAdapter(fsMethods) {
3844
3844
  if (fsMethods === void 0) {
@@ -3855,12 +3855,12 @@ var require_settings = __commonJS({
3855
3855
  "../../node_modules/.pnpm/@nodelib+fs.stat@2.0.5/node_modules/@nodelib/fs.stat/out/settings.js"(exports) {
3856
3856
  "use strict";
3857
3857
  Object.defineProperty(exports, "__esModule", { value: true });
3858
- var fs6 = require_fs2();
3858
+ var fs8 = require_fs2();
3859
3859
  var Settings = class {
3860
3860
  constructor(_options = {}) {
3861
3861
  this._options = _options;
3862
3862
  this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
3863
- this.fs = fs6.createFileSystemAdapter(this._options.fs);
3863
+ this.fs = fs8.createFileSystemAdapter(this._options.fs);
3864
3864
  this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
3865
3865
  this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
3866
3866
  }
@@ -3882,17 +3882,17 @@ var require_out = __commonJS({
3882
3882
  var sync = require_sync();
3883
3883
  var settings_1 = require_settings();
3884
3884
  exports.Settings = settings_1.default;
3885
- function stat(path6, optionsOrSettingsOrCallback, callback) {
3885
+ function stat(path8, optionsOrSettingsOrCallback, callback) {
3886
3886
  if (typeof optionsOrSettingsOrCallback === "function") {
3887
- async.read(path6, getSettings(), optionsOrSettingsOrCallback);
3887
+ async.read(path8, getSettings(), optionsOrSettingsOrCallback);
3888
3888
  return;
3889
3889
  }
3890
- async.read(path6, getSettings(optionsOrSettingsOrCallback), callback);
3890
+ async.read(path8, getSettings(optionsOrSettingsOrCallback), callback);
3891
3891
  }
3892
3892
  exports.stat = stat;
3893
- function statSync(path6, optionsOrSettings) {
3893
+ function statSync(path8, optionsOrSettings) {
3894
3894
  const settings = getSettings(optionsOrSettings);
3895
- return sync.read(path6, settings);
3895
+ return sync.read(path8, settings);
3896
3896
  }
3897
3897
  exports.statSync = statSync;
3898
3898
  function getSettings(settingsOrOptions = {}) {
@@ -4015,8 +4015,8 @@ var require_utils4 = __commonJS({
4015
4015
  "use strict";
4016
4016
  Object.defineProperty(exports, "__esModule", { value: true });
4017
4017
  exports.fs = void 0;
4018
- var fs6 = require_fs3();
4019
- exports.fs = fs6;
4018
+ var fs8 = require_fs3();
4019
+ exports.fs = fs8;
4020
4020
  }
4021
4021
  });
4022
4022
 
@@ -4108,16 +4108,16 @@ var require_async2 = __commonJS({
4108
4108
  return;
4109
4109
  }
4110
4110
  const tasks = names.map((name) => {
4111
- const path6 = common.joinPathSegments(directory, name, settings.pathSegmentSeparator);
4111
+ const path8 = common.joinPathSegments(directory, name, settings.pathSegmentSeparator);
4112
4112
  return (done) => {
4113
- fsStat.stat(path6, settings.fsStatSettings, (error, stats) => {
4113
+ fsStat.stat(path8, settings.fsStatSettings, (error, stats) => {
4114
4114
  if (error !== null) {
4115
4115
  done(error);
4116
4116
  return;
4117
4117
  }
4118
4118
  const entry = {
4119
4119
  name,
4120
- path: path6,
4120
+ path: path8,
4121
4121
  dirent: utils.fs.createDirentFromStats(name, stats)
4122
4122
  };
4123
4123
  if (settings.stats) {
@@ -4211,14 +4211,14 @@ var require_fs4 = __commonJS({
4211
4211
  "use strict";
4212
4212
  Object.defineProperty(exports, "__esModule", { value: true });
4213
4213
  exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
4214
- var fs6 = __require("fs");
4214
+ var fs8 = __require("fs");
4215
4215
  exports.FILE_SYSTEM_ADAPTER = {
4216
- lstat: fs6.lstat,
4217
- stat: fs6.stat,
4218
- lstatSync: fs6.lstatSync,
4219
- statSync: fs6.statSync,
4220
- readdir: fs6.readdir,
4221
- readdirSync: fs6.readdirSync
4216
+ lstat: fs8.lstat,
4217
+ stat: fs8.stat,
4218
+ lstatSync: fs8.lstatSync,
4219
+ statSync: fs8.statSync,
4220
+ readdir: fs8.readdir,
4221
+ readdirSync: fs8.readdirSync
4222
4222
  };
4223
4223
  function createFileSystemAdapter(fsMethods) {
4224
4224
  if (fsMethods === void 0) {
@@ -4235,15 +4235,15 @@ var require_settings2 = __commonJS({
4235
4235
  "../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/settings.js"(exports) {
4236
4236
  "use strict";
4237
4237
  Object.defineProperty(exports, "__esModule", { value: true });
4238
- var path6 = __require("path");
4238
+ var path8 = __require("path");
4239
4239
  var fsStat = require_out();
4240
- var fs6 = require_fs4();
4240
+ var fs8 = require_fs4();
4241
4241
  var Settings = class {
4242
4242
  constructor(_options = {}) {
4243
4243
  this._options = _options;
4244
4244
  this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
4245
- this.fs = fs6.createFileSystemAdapter(this._options.fs);
4246
- this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path6.sep);
4245
+ this.fs = fs8.createFileSystemAdapter(this._options.fs);
4246
+ this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path8.sep);
4247
4247
  this.stats = this._getValue(this._options.stats, false);
4248
4248
  this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
4249
4249
  this.fsStatSettings = new fsStat.Settings({
@@ -4270,17 +4270,17 @@ var require_out2 = __commonJS({
4270
4270
  var sync = require_sync2();
4271
4271
  var settings_1 = require_settings2();
4272
4272
  exports.Settings = settings_1.default;
4273
- function scandir(path6, optionsOrSettingsOrCallback, callback) {
4273
+ function scandir(path8, optionsOrSettingsOrCallback, callback) {
4274
4274
  if (typeof optionsOrSettingsOrCallback === "function") {
4275
- async.read(path6, getSettings(), optionsOrSettingsOrCallback);
4275
+ async.read(path8, getSettings(), optionsOrSettingsOrCallback);
4276
4276
  return;
4277
4277
  }
4278
- async.read(path6, getSettings(optionsOrSettingsOrCallback), callback);
4278
+ async.read(path8, getSettings(optionsOrSettingsOrCallback), callback);
4279
4279
  }
4280
4280
  exports.scandir = scandir;
4281
- function scandirSync(path6, optionsOrSettings) {
4281
+ function scandirSync(path8, optionsOrSettings) {
4282
4282
  const settings = getSettings(optionsOrSettings);
4283
- return sync.read(path6, settings);
4283
+ return sync.read(path8, settings);
4284
4284
  }
4285
4285
  exports.scandirSync = scandirSync;
4286
4286
  function getSettings(settingsOrOptions = {}) {
@@ -4927,7 +4927,7 @@ var require_settings3 = __commonJS({
4927
4927
  "../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/settings.js"(exports) {
4928
4928
  "use strict";
4929
4929
  Object.defineProperty(exports, "__esModule", { value: true });
4930
- var path6 = __require("path");
4930
+ var path8 = __require("path");
4931
4931
  var fsScandir = require_out2();
4932
4932
  var Settings = class {
4933
4933
  constructor(_options = {}) {
@@ -4937,7 +4937,7 @@ var require_settings3 = __commonJS({
4937
4937
  this.deepFilter = this._getValue(this._options.deepFilter, null);
4938
4938
  this.entryFilter = this._getValue(this._options.entryFilter, null);
4939
4939
  this.errorFilter = this._getValue(this._options.errorFilter, null);
4940
- this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path6.sep);
4940
+ this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path8.sep);
4941
4941
  this.fsScandirSettings = new fsScandir.Settings({
4942
4942
  followSymbolicLinks: this._options.followSymbolicLinks,
4943
4943
  fs: this._options.fs,
@@ -4999,7 +4999,7 @@ var require_reader2 = __commonJS({
4999
4999
  "../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/readers/reader.js"(exports) {
5000
5000
  "use strict";
5001
5001
  Object.defineProperty(exports, "__esModule", { value: true });
5002
- var path6 = __require("path");
5002
+ var path8 = __require("path");
5003
5003
  var fsStat = require_out();
5004
5004
  var utils = require_utils3();
5005
5005
  var Reader = class {
@@ -5012,7 +5012,7 @@ var require_reader2 = __commonJS({
5012
5012
  });
5013
5013
  }
5014
5014
  _getFullEntryPath(filepath) {
5015
- return path6.resolve(this._settings.cwd, filepath);
5015
+ return path8.resolve(this._settings.cwd, filepath);
5016
5016
  }
5017
5017
  _makeEntry(stats, pattern) {
5018
5018
  const entry = {
@@ -5428,7 +5428,7 @@ var require_provider = __commonJS({
5428
5428
  "../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/provider.js"(exports) {
5429
5429
  "use strict";
5430
5430
  Object.defineProperty(exports, "__esModule", { value: true });
5431
- var path6 = __require("path");
5431
+ var path8 = __require("path");
5432
5432
  var deep_1 = require_deep();
5433
5433
  var entry_1 = require_entry();
5434
5434
  var error_1 = require_error();
@@ -5442,7 +5442,7 @@ var require_provider = __commonJS({
5442
5442
  this.entryTransformer = new entry_2.default(this._settings);
5443
5443
  }
5444
5444
  _getRootDirectory(task) {
5445
- return path6.resolve(this._settings.cwd, task.base);
5445
+ return path8.resolve(this._settings.cwd, task.base);
5446
5446
  }
5447
5447
  _getReaderOptions(task) {
5448
5448
  const basePath = task.base === "." ? "" : task.base;
@@ -5623,16 +5623,16 @@ var require_settings4 = __commonJS({
5623
5623
  "use strict";
5624
5624
  Object.defineProperty(exports, "__esModule", { value: true });
5625
5625
  exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
5626
- var fs6 = __require("fs");
5626
+ var fs8 = __require("fs");
5627
5627
  var os2 = __require("os");
5628
5628
  var CPU_COUNT = Math.max(os2.cpus().length, 1);
5629
5629
  exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
5630
- lstat: fs6.lstat,
5631
- lstatSync: fs6.lstatSync,
5632
- stat: fs6.stat,
5633
- statSync: fs6.statSync,
5634
- readdir: fs6.readdir,
5635
- readdirSync: fs6.readdirSync
5630
+ lstat: fs8.lstat,
5631
+ lstatSync: fs8.lstatSync,
5632
+ stat: fs8.stat,
5633
+ statSync: fs8.statSync,
5634
+ readdir: fs8.readdir,
5635
+ readdirSync: fs8.readdirSync
5636
5636
  };
5637
5637
  var Settings = class {
5638
5638
  constructor(_options = {}) {
@@ -5855,17 +5855,17 @@ var require_visit = __commonJS({
5855
5855
  visit.BREAK = BREAK;
5856
5856
  visit.SKIP = SKIP;
5857
5857
  visit.REMOVE = REMOVE;
5858
- function visit_(key, node, visitor, path6) {
5859
- const ctrl = callVisitor(key, node, visitor, path6);
5858
+ function visit_(key, node, visitor, path8) {
5859
+ const ctrl = callVisitor(key, node, visitor, path8);
5860
5860
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
5861
- replaceNode(key, path6, ctrl);
5862
- return visit_(key, ctrl, visitor, path6);
5861
+ replaceNode(key, path8, ctrl);
5862
+ return visit_(key, ctrl, visitor, path8);
5863
5863
  }
5864
5864
  if (typeof ctrl !== "symbol") {
5865
5865
  if (identity.isCollection(node)) {
5866
- path6 = Object.freeze(path6.concat(node));
5866
+ path8 = Object.freeze(path8.concat(node));
5867
5867
  for (let i = 0; i < node.items.length; ++i) {
5868
- const ci = visit_(i, node.items[i], visitor, path6);
5868
+ const ci = visit_(i, node.items[i], visitor, path8);
5869
5869
  if (typeof ci === "number")
5870
5870
  i = ci - 1;
5871
5871
  else if (ci === BREAK)
@@ -5876,13 +5876,13 @@ var require_visit = __commonJS({
5876
5876
  }
5877
5877
  }
5878
5878
  } else if (identity.isPair(node)) {
5879
- path6 = Object.freeze(path6.concat(node));
5880
- const ck = visit_("key", node.key, visitor, path6);
5879
+ path8 = Object.freeze(path8.concat(node));
5880
+ const ck = visit_("key", node.key, visitor, path8);
5881
5881
  if (ck === BREAK)
5882
5882
  return BREAK;
5883
5883
  else if (ck === REMOVE)
5884
5884
  node.key = null;
5885
- const cv = visit_("value", node.value, visitor, path6);
5885
+ const cv = visit_("value", node.value, visitor, path8);
5886
5886
  if (cv === BREAK)
5887
5887
  return BREAK;
5888
5888
  else if (cv === REMOVE)
@@ -5903,17 +5903,17 @@ var require_visit = __commonJS({
5903
5903
  visitAsync.BREAK = BREAK;
5904
5904
  visitAsync.SKIP = SKIP;
5905
5905
  visitAsync.REMOVE = REMOVE;
5906
- async function visitAsync_(key, node, visitor, path6) {
5907
- const ctrl = await callVisitor(key, node, visitor, path6);
5906
+ async function visitAsync_(key, node, visitor, path8) {
5907
+ const ctrl = await callVisitor(key, node, visitor, path8);
5908
5908
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
5909
- replaceNode(key, path6, ctrl);
5910
- return visitAsync_(key, ctrl, visitor, path6);
5909
+ replaceNode(key, path8, ctrl);
5910
+ return visitAsync_(key, ctrl, visitor, path8);
5911
5911
  }
5912
5912
  if (typeof ctrl !== "symbol") {
5913
5913
  if (identity.isCollection(node)) {
5914
- path6 = Object.freeze(path6.concat(node));
5914
+ path8 = Object.freeze(path8.concat(node));
5915
5915
  for (let i = 0; i < node.items.length; ++i) {
5916
- const ci = await visitAsync_(i, node.items[i], visitor, path6);
5916
+ const ci = await visitAsync_(i, node.items[i], visitor, path8);
5917
5917
  if (typeof ci === "number")
5918
5918
  i = ci - 1;
5919
5919
  else if (ci === BREAK)
@@ -5924,13 +5924,13 @@ var require_visit = __commonJS({
5924
5924
  }
5925
5925
  }
5926
5926
  } else if (identity.isPair(node)) {
5927
- path6 = Object.freeze(path6.concat(node));
5928
- const ck = await visitAsync_("key", node.key, visitor, path6);
5927
+ path8 = Object.freeze(path8.concat(node));
5928
+ const ck = await visitAsync_("key", node.key, visitor, path8);
5929
5929
  if (ck === BREAK)
5930
5930
  return BREAK;
5931
5931
  else if (ck === REMOVE)
5932
5932
  node.key = null;
5933
- const cv = await visitAsync_("value", node.value, visitor, path6);
5933
+ const cv = await visitAsync_("value", node.value, visitor, path8);
5934
5934
  if (cv === BREAK)
5935
5935
  return BREAK;
5936
5936
  else if (cv === REMOVE)
@@ -5957,23 +5957,23 @@ var require_visit = __commonJS({
5957
5957
  }
5958
5958
  return visitor;
5959
5959
  }
5960
- function callVisitor(key, node, visitor, path6) {
5960
+ function callVisitor(key, node, visitor, path8) {
5961
5961
  if (typeof visitor === "function")
5962
- return visitor(key, node, path6);
5962
+ return visitor(key, node, path8);
5963
5963
  if (identity.isMap(node))
5964
- return visitor.Map?.(key, node, path6);
5964
+ return visitor.Map?.(key, node, path8);
5965
5965
  if (identity.isSeq(node))
5966
- return visitor.Seq?.(key, node, path6);
5966
+ return visitor.Seq?.(key, node, path8);
5967
5967
  if (identity.isPair(node))
5968
- return visitor.Pair?.(key, node, path6);
5968
+ return visitor.Pair?.(key, node, path8);
5969
5969
  if (identity.isScalar(node))
5970
- return visitor.Scalar?.(key, node, path6);
5970
+ return visitor.Scalar?.(key, node, path8);
5971
5971
  if (identity.isAlias(node))
5972
- return visitor.Alias?.(key, node, path6);
5972
+ return visitor.Alias?.(key, node, path8);
5973
5973
  return void 0;
5974
5974
  }
5975
- function replaceNode(key, path6, node) {
5976
- const parent = path6[path6.length - 1];
5975
+ function replaceNode(key, path8, node) {
5976
+ const parent = path8[path8.length - 1];
5977
5977
  if (identity.isCollection(parent)) {
5978
5978
  parent.items[key] = node;
5979
5979
  } else if (identity.isPair(parent)) {
@@ -6583,10 +6583,10 @@ var require_Collection = __commonJS({
6583
6583
  var createNode = require_createNode();
6584
6584
  var identity = require_identity();
6585
6585
  var Node = require_Node();
6586
- function collectionFromPath(schema, path6, value) {
6586
+ function collectionFromPath(schema, path8, value) {
6587
6587
  let v = value;
6588
- for (let i = path6.length - 1; i >= 0; --i) {
6589
- const k = path6[i];
6588
+ for (let i = path8.length - 1; i >= 0; --i) {
6589
+ const k = path8[i];
6590
6590
  if (typeof k === "number" && Number.isInteger(k) && k >= 0) {
6591
6591
  const a = [];
6592
6592
  a[k] = v;
@@ -6605,7 +6605,7 @@ var require_Collection = __commonJS({
6605
6605
  sourceObjects: /* @__PURE__ */ new Map()
6606
6606
  });
6607
6607
  }
6608
- var isEmptyPath = (path6) => path6 == null || typeof path6 === "object" && !!path6[Symbol.iterator]().next().done;
6608
+ var isEmptyPath = (path8) => path8 == null || typeof path8 === "object" && !!path8[Symbol.iterator]().next().done;
6609
6609
  var Collection = class extends Node.NodeBase {
6610
6610
  constructor(type, schema) {
6611
6611
  super(type);
@@ -6635,11 +6635,11 @@ var require_Collection = __commonJS({
6635
6635
  * be a Pair instance or a `{ key, value }` object, which may not have a key
6636
6636
  * that already exists in the map.
6637
6637
  */
6638
- addIn(path6, value) {
6639
- if (isEmptyPath(path6))
6638
+ addIn(path8, value) {
6639
+ if (isEmptyPath(path8))
6640
6640
  this.add(value);
6641
6641
  else {
6642
- const [key, ...rest] = path6;
6642
+ const [key, ...rest] = path8;
6643
6643
  const node = this.get(key, true);
6644
6644
  if (identity.isCollection(node))
6645
6645
  node.addIn(rest, value);
@@ -6653,8 +6653,8 @@ var require_Collection = __commonJS({
6653
6653
  * Removes a value from the collection.
6654
6654
  * @returns `true` if the item was found and removed.
6655
6655
  */
6656
- deleteIn(path6) {
6657
- const [key, ...rest] = path6;
6656
+ deleteIn(path8) {
6657
+ const [key, ...rest] = path8;
6658
6658
  if (rest.length === 0)
6659
6659
  return this.delete(key);
6660
6660
  const node = this.get(key, true);
@@ -6668,8 +6668,8 @@ var require_Collection = __commonJS({
6668
6668
  * scalar values from their surrounding node; to disable set `keepScalar` to
6669
6669
  * `true` (collections are always returned intact).
6670
6670
  */
6671
- getIn(path6, keepScalar) {
6672
- const [key, ...rest] = path6;
6671
+ getIn(path8, keepScalar) {
6672
+ const [key, ...rest] = path8;
6673
6673
  const node = this.get(key, true);
6674
6674
  if (rest.length === 0)
6675
6675
  return !keepScalar && identity.isScalar(node) ? node.value : node;
@@ -6687,8 +6687,8 @@ var require_Collection = __commonJS({
6687
6687
  /**
6688
6688
  * Checks if the collection includes a value with the key `key`.
6689
6689
  */
6690
- hasIn(path6) {
6691
- const [key, ...rest] = path6;
6690
+ hasIn(path8) {
6691
+ const [key, ...rest] = path8;
6692
6692
  if (rest.length === 0)
6693
6693
  return this.has(key);
6694
6694
  const node = this.get(key, true);
@@ -6698,8 +6698,8 @@ var require_Collection = __commonJS({
6698
6698
  * Sets a value in this collection. For `!!set`, `value` needs to be a
6699
6699
  * boolean to add/remove the item from the set.
6700
6700
  */
6701
- setIn(path6, value) {
6702
- const [key, ...rest] = path6;
6701
+ setIn(path8, value) {
6702
+ const [key, ...rest] = path8;
6703
6703
  if (rest.length === 0) {
6704
6704
  this.set(key, value);
6705
6705
  } else {
@@ -9214,9 +9214,9 @@ var require_Document = __commonJS({
9214
9214
  this.contents.add(value);
9215
9215
  }
9216
9216
  /** Adds a value to the document. */
9217
- addIn(path6, value) {
9217
+ addIn(path8, value) {
9218
9218
  if (assertCollection(this.contents))
9219
- this.contents.addIn(path6, value);
9219
+ this.contents.addIn(path8, value);
9220
9220
  }
9221
9221
  /**
9222
9222
  * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
@@ -9291,14 +9291,14 @@ var require_Document = __commonJS({
9291
9291
  * Removes a value from the document.
9292
9292
  * @returns `true` if the item was found and removed.
9293
9293
  */
9294
- deleteIn(path6) {
9295
- if (Collection.isEmptyPath(path6)) {
9294
+ deleteIn(path8) {
9295
+ if (Collection.isEmptyPath(path8)) {
9296
9296
  if (this.contents == null)
9297
9297
  return false;
9298
9298
  this.contents = null;
9299
9299
  return true;
9300
9300
  }
9301
- return assertCollection(this.contents) ? this.contents.deleteIn(path6) : false;
9301
+ return assertCollection(this.contents) ? this.contents.deleteIn(path8) : false;
9302
9302
  }
9303
9303
  /**
9304
9304
  * Returns item at `key`, or `undefined` if not found. By default unwraps
@@ -9313,10 +9313,10 @@ var require_Document = __commonJS({
9313
9313
  * scalar values from their surrounding node; to disable set `keepScalar` to
9314
9314
  * `true` (collections are always returned intact).
9315
9315
  */
9316
- getIn(path6, keepScalar) {
9317
- if (Collection.isEmptyPath(path6))
9316
+ getIn(path8, keepScalar) {
9317
+ if (Collection.isEmptyPath(path8))
9318
9318
  return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents;
9319
- return identity.isCollection(this.contents) ? this.contents.getIn(path6, keepScalar) : void 0;
9319
+ return identity.isCollection(this.contents) ? this.contents.getIn(path8, keepScalar) : void 0;
9320
9320
  }
9321
9321
  /**
9322
9322
  * Checks if the document includes a value with the key `key`.
@@ -9327,10 +9327,10 @@ var require_Document = __commonJS({
9327
9327
  /**
9328
9328
  * Checks if the document includes a value at `path`.
9329
9329
  */
9330
- hasIn(path6) {
9331
- if (Collection.isEmptyPath(path6))
9330
+ hasIn(path8) {
9331
+ if (Collection.isEmptyPath(path8))
9332
9332
  return this.contents !== void 0;
9333
- return identity.isCollection(this.contents) ? this.contents.hasIn(path6) : false;
9333
+ return identity.isCollection(this.contents) ? this.contents.hasIn(path8) : false;
9334
9334
  }
9335
9335
  /**
9336
9336
  * Sets a value in this document. For `!!set`, `value` needs to be a
@@ -9347,13 +9347,13 @@ var require_Document = __commonJS({
9347
9347
  * Sets a value in this document. For `!!set`, `value` needs to be a
9348
9348
  * boolean to add/remove the item from the set.
9349
9349
  */
9350
- setIn(path6, value) {
9351
- if (Collection.isEmptyPath(path6)) {
9350
+ setIn(path8, value) {
9351
+ if (Collection.isEmptyPath(path8)) {
9352
9352
  this.contents = value;
9353
9353
  } else if (this.contents == null) {
9354
- this.contents = Collection.collectionFromPath(this.schema, Array.from(path6), value);
9354
+ this.contents = Collection.collectionFromPath(this.schema, Array.from(path8), value);
9355
9355
  } else if (assertCollection(this.contents)) {
9356
- this.contents.setIn(path6, value);
9356
+ this.contents.setIn(path8, value);
9357
9357
  }
9358
9358
  }
9359
9359
  /**
@@ -11313,9 +11313,9 @@ var require_cst_visit = __commonJS({
11313
11313
  visit.BREAK = BREAK;
11314
11314
  visit.SKIP = SKIP;
11315
11315
  visit.REMOVE = REMOVE;
11316
- visit.itemAtPath = (cst, path6) => {
11316
+ visit.itemAtPath = (cst, path8) => {
11317
11317
  let item = cst;
11318
- for (const [field, index] of path6) {
11318
+ for (const [field, index] of path8) {
11319
11319
  const tok = item?.[field];
11320
11320
  if (tok && "items" in tok) {
11321
11321
  item = tok.items[index];
@@ -11324,23 +11324,23 @@ var require_cst_visit = __commonJS({
11324
11324
  }
11325
11325
  return item;
11326
11326
  };
11327
- visit.parentCollection = (cst, path6) => {
11328
- const parent = visit.itemAtPath(cst, path6.slice(0, -1));
11329
- const field = path6[path6.length - 1][0];
11327
+ visit.parentCollection = (cst, path8) => {
11328
+ const parent = visit.itemAtPath(cst, path8.slice(0, -1));
11329
+ const field = path8[path8.length - 1][0];
11330
11330
  const coll = parent?.[field];
11331
11331
  if (coll && "items" in coll)
11332
11332
  return coll;
11333
11333
  throw new Error("Parent collection not found");
11334
11334
  };
11335
- function _visit(path6, item, visitor) {
11336
- let ctrl = visitor(item, path6);
11335
+ function _visit(path8, item, visitor) {
11336
+ let ctrl = visitor(item, path8);
11337
11337
  if (typeof ctrl === "symbol")
11338
11338
  return ctrl;
11339
11339
  for (const field of ["key", "value"]) {
11340
11340
  const token = item[field];
11341
11341
  if (token && "items" in token) {
11342
11342
  for (let i = 0; i < token.items.length; ++i) {
11343
- const ci = _visit(Object.freeze(path6.concat([[field, i]])), token.items[i], visitor);
11343
+ const ci = _visit(Object.freeze(path8.concat([[field, i]])), token.items[i], visitor);
11344
11344
  if (typeof ci === "number")
11345
11345
  i = ci - 1;
11346
11346
  else if (ci === BREAK)
@@ -11351,10 +11351,10 @@ var require_cst_visit = __commonJS({
11351
11351
  }
11352
11352
  }
11353
11353
  if (typeof ctrl === "function" && field === "key")
11354
- ctrl = ctrl(item, path6);
11354
+ ctrl = ctrl(item, path8);
11355
11355
  }
11356
11356
  }
11357
- return typeof ctrl === "function" ? ctrl(item, path6) : ctrl;
11357
+ return typeof ctrl === "function" ? ctrl(item, path8) : ctrl;
11358
11358
  }
11359
11359
  exports.visit = visit;
11360
11360
  }
@@ -12656,14 +12656,14 @@ var require_parser = __commonJS({
12656
12656
  case "scalar":
12657
12657
  case "single-quoted-scalar":
12658
12658
  case "double-quoted-scalar": {
12659
- const fs6 = this.flowScalar(this.type);
12659
+ const fs8 = this.flowScalar(this.type);
12660
12660
  if (atNextItem || it.value) {
12661
- map.items.push({ start, key: fs6, sep: [] });
12661
+ map.items.push({ start, key: fs8, sep: [] });
12662
12662
  this.onKeyLine = true;
12663
12663
  } else if (it.sep) {
12664
- this.stack.push(fs6);
12664
+ this.stack.push(fs8);
12665
12665
  } else {
12666
- Object.assign(it, { key: fs6, sep: [] });
12666
+ Object.assign(it, { key: fs8, sep: [] });
12667
12667
  this.onKeyLine = true;
12668
12668
  }
12669
12669
  return;
@@ -12791,13 +12791,13 @@ var require_parser = __commonJS({
12791
12791
  case "scalar":
12792
12792
  case "single-quoted-scalar":
12793
12793
  case "double-quoted-scalar": {
12794
- const fs6 = this.flowScalar(this.type);
12794
+ const fs8 = this.flowScalar(this.type);
12795
12795
  if (!it || it.value)
12796
- fc.items.push({ start: [], key: fs6, sep: [] });
12796
+ fc.items.push({ start: [], key: fs8, sep: [] });
12797
12797
  else if (it.sep)
12798
- this.stack.push(fs6);
12798
+ this.stack.push(fs8);
12799
12799
  else
12800
- Object.assign(it, { key: fs6, sep: [] });
12800
+ Object.assign(it, { key: fs8, sep: [] });
12801
12801
  return;
12802
12802
  }
12803
12803
  case "flow-map-end":
@@ -13106,19 +13106,103 @@ var require_dist = __commonJS({
13106
13106
  });
13107
13107
 
13108
13108
  // src/index.ts
13109
- import fs5 from "node:fs";
13109
+ import fs7 from "node:fs";
13110
13110
  import http from "node:http";
13111
- import os from "node:os";
13112
- import path5 from "node:path";
13113
- import { execFileSync } from "node:child_process";
13111
+ import path7 from "node:path";
13112
+ import { execFileSync as execFileSync3 } from "node:child_process";
13114
13113
  import { fileURLToPath } from "node:url";
13115
13114
 
13116
13115
  // ../parser/dist/index.js
13117
13116
  var import_fast_glob = __toESM(require_out4(), 1);
13118
- var import_yaml3 = __toESM(require_dist(), 1);
13117
+ var import_yaml4 = __toESM(require_dist(), 1);
13119
13118
  import fs2 from "node:fs";
13120
13119
  import path2 from "node:path";
13121
13120
 
13121
+ // ../parser/dist/actors.js
13122
+ var import_yaml = __toESM(require_dist(), 1);
13123
+ var palette = ["#2563EB", "#7C3AED", "#0F766E", "#B45309", "#BE185D", "#4338CA", "#047857", "#9F1239"];
13124
+ function actorColor(id) {
13125
+ let hash = 0;
13126
+ for (const character of id)
13127
+ hash = Math.imul(hash, 31) + character.codePointAt(0) >>> 0;
13128
+ return palette[hash % palette.length];
13129
+ }
13130
+ function parseActorReferences(value) {
13131
+ if (value === void 0)
13132
+ return { actors: [] };
13133
+ if (!Array.isArray(value))
13134
+ return { actors: [], actorIssues: ["screen.actors must be an array of actor IDs."] };
13135
+ const actors = [];
13136
+ const actorIssues = [];
13137
+ for (const id of value) {
13138
+ if (typeof id !== "string" || !id.trim() || id !== id.trim()) {
13139
+ actorIssues.push("screen.actors IDs must be nonempty strings without surrounding whitespace.");
13140
+ } else if (actors.includes(id)) {
13141
+ actorIssues.push(`screen.actors lists "${id}" more than once.`);
13142
+ } else {
13143
+ actors.push(id);
13144
+ }
13145
+ }
13146
+ return { actors, ...actorIssues.length ? { actorIssues } : {} };
13147
+ }
13148
+ function loadActors(content, sourcePath, slices) {
13149
+ const definitions = /* @__PURE__ */ new Map();
13150
+ const actorIssues = [];
13151
+ const issue = (message, path8 = sourcePath) => actorIssues.push({ message, path: path8 });
13152
+ if (content !== void 0) {
13153
+ let raw;
13154
+ try {
13155
+ raw = import_yaml.default.parse(content);
13156
+ } catch (error) {
13157
+ issue(`Invalid actor registry: ${error instanceof Error ? error.message : String(error)}`);
13158
+ }
13159
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || !("actors" in raw) || !raw.actors || typeof raw.actors !== "object" || Array.isArray(raw.actors)) {
13160
+ issue("Actor registry must contain an actors mapping.");
13161
+ } else {
13162
+ for (const [id, value] of Object.entries(raw.actors)) {
13163
+ if (!id.trim() || id !== id.trim()) {
13164
+ issue("Actor IDs must be nonempty strings without surrounding whitespace.");
13165
+ continue;
13166
+ }
13167
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
13168
+ issue(`Actor "${id}" must be a mapping with optional name and color.`);
13169
+ continue;
13170
+ }
13171
+ const entry = value;
13172
+ let name = id;
13173
+ let color = actorColor(id);
13174
+ if (entry.name !== void 0) {
13175
+ if (typeof entry.name !== "string" || !entry.name.trim())
13176
+ issue(`Actor "${id}" name must be a nonempty string.`);
13177
+ else
13178
+ name = entry.name.trim();
13179
+ }
13180
+ if (entry.color !== void 0) {
13181
+ if (typeof entry.color !== "string" || !/^#[0-9a-f]{6}$/i.test(entry.color))
13182
+ issue(`Actor "${id}" color must be a quoted #RRGGBB value.`);
13183
+ else
13184
+ color = entry.color.toUpperCase();
13185
+ }
13186
+ definitions.set(id, { id, name, color });
13187
+ }
13188
+ }
13189
+ }
13190
+ const registered = new Set(definitions.keys());
13191
+ for (const slice of slices) {
13192
+ for (const message of slice.screen.actorIssues ?? [])
13193
+ issue(message, slice.path);
13194
+ if (slice.screen.type !== "user")
13195
+ continue;
13196
+ for (const id of slice.screen.actors) {
13197
+ if (content !== void 0 && !registered.has(id))
13198
+ issue(`screen.actors references undefined actor "${id}".`, slice.path);
13199
+ if (!definitions.has(id))
13200
+ definitions.set(id, { id, name: id, color: actorColor(id) });
13201
+ }
13202
+ }
13203
+ return { actors: [...definitions.values()], actorIssues };
13204
+ }
13205
+
13122
13206
  // ../parser/dist/id.js
13123
13207
  function slugify(value) {
13124
13208
  const normalized = value.normalize("NFKC").replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "").toLowerCase();
@@ -13220,6 +13304,9 @@ function buildGraph(project) {
13220
13304
  type: slice.screen.type === "system" ? "processor" : "screen",
13221
13305
  label: slice.screen.name ?? (slice.screen.type === "system" ? "Processor" : "Screen"),
13222
13306
  actors: slice.screen.actors,
13307
+ ...slice.screen.type === "user" ? {
13308
+ actorDefinitions: slice.screen.actors.map((id2) => project.actors?.find((actor) => actor.id === id2)).filter((actor) => Boolean(actor))
13309
+ } : {},
13223
13310
  screenType: slice.screen.type
13224
13311
  });
13225
13312
  connect("slice-screen", currentSliceId, currentScreenId);
@@ -13257,7 +13344,7 @@ function buildGraph(project) {
13257
13344
  }
13258
13345
 
13259
13346
  // ../parser/dist/config.js
13260
- var import_yaml = __toESM(require_dist(), 1);
13347
+ var import_yaml2 = __toESM(require_dist(), 1);
13261
13348
  import fs from "node:fs";
13262
13349
  import path from "node:path";
13263
13350
  function findProjectRoot(startDir) {
@@ -13278,7 +13365,10 @@ function readConfig(projectRoot) {
13278
13365
  if (!fs.existsSync(configPath)) {
13279
13366
  throw new Error(`Missing .event-modeling/config.yaml at ${projectRoot}`);
13280
13367
  }
13281
- const raw = import_yaml.default.parse(fs.readFileSync(configPath, "utf8"));
13368
+ return parseConfig(fs.readFileSync(configPath, "utf8"));
13369
+ }
13370
+ function parseConfig(content) {
13371
+ const raw = import_yaml2.default.parse(content);
13282
13372
  const eventModelDir = raw?.paths?.event_model_dir ?? "event-model";
13283
13373
  const featuresDir = raw?.paths?.features_dir ?? "src/features";
13284
13374
  const sliceExtension = raw?.paths?.slice_extension ?? ".slice.yaml";
@@ -13289,26 +13379,32 @@ function readConfig(projectRoot) {
13289
13379
  featuresDir,
13290
13380
  sliceExtension,
13291
13381
  eventsFile: raw?.paths?.events_file ?? path.posix.join(eventModelDir, "events.yaml"),
13382
+ actorsFile: path.posix.normalize(raw?.paths?.actors_file ?? path.posix.join(eventModelDir, "actors.yaml")),
13292
13383
  storiesDir: raw?.paths?.stories_dir ?? path.posix.join(eventModelDir, "stories")
13293
13384
  }
13294
13385
  };
13295
13386
  }
13296
13387
 
13297
13388
  // ../parser/dist/browser.js
13298
- var import_yaml2 = __toESM(require_dist(), 1);
13299
-
13300
- // ../parser/dist/index.js
13301
- function asStringArray(value) {
13302
- return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
13303
- }
13389
+ var import_yaml3 = __toESM(require_dist(), 1);
13304
13390
  function normalizeRelativePath(filePath) {
13305
- return filePath.replaceAll("\\", "/").replace(/^\/+/, "");
13391
+ const parts = [];
13392
+ for (const part of filePath.replaceAll("\\", "/").split("/")) {
13393
+ if (!part || part === ".")
13394
+ continue;
13395
+ if (part === ".." && parts.length > 0 && parts.at(-1) !== "..")
13396
+ parts.pop();
13397
+ else
13398
+ parts.push(part);
13399
+ }
13400
+ return parts.join("/");
13306
13401
  }
13307
- function rel(projectRoot, filePath) {
13308
- return path2.relative(projectRoot, filePath).split(path2.sep).join(path2.posix.sep);
13402
+ function basename(filePath, extension = "") {
13403
+ const name = normalizeRelativePath(filePath).split("/").at(-1) ?? filePath;
13404
+ return extension && name.endsWith(extension) ? name.slice(0, -extension.length) : name;
13309
13405
  }
13310
- function resolveProjectPath(projectRoot, relativePath) {
13311
- return path2.resolve(projectRoot, relativePath);
13406
+ function asStringArray(value) {
13407
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
13312
13408
  }
13313
13409
  function parseEventsText(sourcePath, content) {
13314
13410
  const raw = import_yaml3.default.parse(content);
@@ -13320,23 +13416,15 @@ function parseEventsText(sourcePath, content) {
13320
13416
  sourcePath
13321
13417
  }));
13322
13418
  }
13323
- function parseEvents(projectRoot, eventsPath) {
13324
- const absolutePath = resolveProjectPath(projectRoot, eventsPath);
13325
- return parseEventsText(rel(projectRoot, absolutePath), fs2.readFileSync(absolutePath, "utf8"));
13326
- }
13327
13419
  function parseStoryText(storyPath, content) {
13328
13420
  const raw = import_yaml3.default.parse(content);
13329
13421
  return {
13330
- name: typeof raw?.name === "string" ? raw.name : path2.basename(storyPath, ".yaml"),
13422
+ name: typeof raw?.name === "string" ? raw.name : basename(storyPath, ".yaml"),
13331
13423
  description: typeof raw?.description === "string" ? raw.description : "",
13332
13424
  path: storyPath,
13333
13425
  slices: asStringArray(raw?.slices).map(normalizeRelativePath)
13334
13426
  };
13335
13427
  }
13336
- function parseStories(projectRoot, storiesDir) {
13337
- const pattern = path2.posix.join(storiesDir, "*.yaml");
13338
- return import_fast_glob.default.sync(pattern, { cwd: projectRoot, onlyFiles: true, ignore: ["node_modules/**", ".git/**", "dist/**"] }).sort().map((storyPath) => parseStoryText(storyPath, fs2.readFileSync(resolveProjectPath(projectRoot, storyPath), "utf8")));
13339
- }
13340
13428
  function parseCommands(value) {
13341
13429
  if (!Array.isArray(value))
13342
13430
  return [];
@@ -13372,7 +13460,7 @@ function parseScreen(raw) {
13372
13460
  return {
13373
13461
  type: raw?.type === "system" ? "system" : "user",
13374
13462
  name: typeof raw?.name === "string" ? raw.name : void 0,
13375
- actors: asStringArray(raw?.actors),
13463
+ ...parseActorReferences(raw?.actors),
13376
13464
  reads: asStringArray(raw?.reads),
13377
13465
  executes: asStringArray(raw?.executes)
13378
13466
  };
@@ -13380,7 +13468,7 @@ function parseScreen(raw) {
13380
13468
  function parseSliceText(slicePath, content, storyBySlice) {
13381
13469
  const raw = import_yaml3.default.parse(content);
13382
13470
  return {
13383
- title: typeof raw?.slice === "string" ? raw.slice : path2.basename(slicePath),
13471
+ title: typeof raw?.slice === "string" ? raw.slice : basename(slicePath),
13384
13472
  path: slicePath,
13385
13473
  storyName: storyBySlice.get(slicePath),
13386
13474
  screen: parseScreen(raw?.screen),
@@ -13390,6 +13478,147 @@ function parseSliceText(slicePath, content, storyBySlice) {
13390
13478
  raw: content
13391
13479
  };
13392
13480
  }
13481
+ function loadEventModelProjectFromFiles(files, options = {}) {
13482
+ const normalizedFiles = new Map(files.map((file) => [normalizeRelativePath(file.path), file.content]));
13483
+ const configContent = normalizedFiles.get(".event-modeling/config.yaml");
13484
+ const configRaw = configContent ? import_yaml3.default.parse(configContent) : null;
13485
+ const eventModelDir = configRaw?.paths?.event_model_dir ?? "event-model";
13486
+ const featuresDir = configRaw?.paths?.features_dir ?? "event-model/features";
13487
+ const sliceExtension = configRaw?.paths?.slice_extension ?? ".slice.yaml";
13488
+ const eventsFile = configRaw?.paths?.events_file ?? `${eventModelDir}/events.yaml`;
13489
+ const actorsFile = normalizeRelativePath(configRaw?.paths?.actors_file ?? `${eventModelDir}/actors.yaml`);
13490
+ const storiesDir = configRaw?.paths?.stories_dir ?? `${eventModelDir}/stories`;
13491
+ const eventsContent = normalizedFiles.get(eventsFile);
13492
+ if (eventsContent === void 0)
13493
+ throw new Error(`Missing events file: ${eventsFile}`);
13494
+ const events = parseEventsText(eventsFile, eventsContent);
13495
+ const stories = [...normalizedFiles.entries()].filter(([filePath]) => filePath.split("/").slice(0, -1).join("/") === storiesDir && filePath.endsWith(".yaml")).sort(([a], [b]) => a.localeCompare(b)).map(([filePath, content]) => parseStoryText(filePath, content));
13496
+ const storyBySlice = /* @__PURE__ */ new Map();
13497
+ for (const story of stories)
13498
+ for (const slicePath of story.slices)
13499
+ storyBySlice.set(normalizeRelativePath(slicePath), story.name);
13500
+ const storySlicePaths = stories.flatMap((story) => story.slices.map(normalizeRelativePath));
13501
+ const discoveredSlicePaths = [...normalizedFiles.keys()].filter((filePath) => (featuresDir === "" || filePath.startsWith(`${featuresDir}/`)) && filePath.endsWith(sliceExtension));
13502
+ const slicePaths = [.../* @__PURE__ */ new Set([...storySlicePaths, ...discoveredSlicePaths])].sort();
13503
+ const slices = slicePaths.filter((filePath) => normalizedFiles.has(filePath)).map((filePath) => parseSliceText(filePath, normalizedFiles.get(filePath) ?? "", storyBySlice));
13504
+ const actorData = loadActors(normalizedFiles.get(actorsFile), actorsFile, slices);
13505
+ const projectWithoutGraph = {
13506
+ root: options.root ?? "browser-import",
13507
+ config: {
13508
+ language: configRaw?.language,
13509
+ paths: { eventModelDir, featuresDir, sliceExtension, eventsFile, actorsFile, storiesDir }
13510
+ },
13511
+ events,
13512
+ stories,
13513
+ slices,
13514
+ ...actorData
13515
+ };
13516
+ const graph = buildGraph(projectWithoutGraph);
13517
+ return { ...projectWithoutGraph, ...graph };
13518
+ }
13519
+
13520
+ // ../parser/dist/index.js
13521
+ function asStringArray2(value) {
13522
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
13523
+ }
13524
+ function normalizeRelativePath2(filePath) {
13525
+ const parts = [];
13526
+ for (const part of filePath.replaceAll("\\", "/").split("/")) {
13527
+ if (!part || part === ".")
13528
+ continue;
13529
+ if (part === ".." && parts.length > 0 && parts.at(-1) !== "..")
13530
+ parts.pop();
13531
+ else
13532
+ parts.push(part);
13533
+ }
13534
+ return parts.join("/");
13535
+ }
13536
+ function rel(projectRoot, filePath) {
13537
+ return path2.relative(projectRoot, filePath).split(path2.sep).join(path2.posix.sep);
13538
+ }
13539
+ function resolveProjectPath(projectRoot, relativePath) {
13540
+ return path2.resolve(projectRoot, relativePath);
13541
+ }
13542
+ function parseEventsText2(sourcePath, content) {
13543
+ const raw = import_yaml4.default.parse(content);
13544
+ const eventMap = raw?.events && typeof raw.events === "object" ? raw.events : raw ?? {};
13545
+ return Object.entries(eventMap).map(([name, entry]) => ({
13546
+ name,
13547
+ fields: typeof entry?.fields === "string" ? entry.fields : void 0,
13548
+ description: typeof entry?.description === "string" ? entry.description : void 0,
13549
+ sourcePath
13550
+ }));
13551
+ }
13552
+ function parseEvents(projectRoot, eventsPath) {
13553
+ const absolutePath = resolveProjectPath(projectRoot, eventsPath);
13554
+ return parseEventsText2(rel(projectRoot, absolutePath), fs2.readFileSync(absolutePath, "utf8"));
13555
+ }
13556
+ function parseStoryText2(storyPath, content) {
13557
+ const raw = import_yaml4.default.parse(content);
13558
+ return {
13559
+ name: typeof raw?.name === "string" ? raw.name : path2.basename(storyPath, ".yaml"),
13560
+ description: typeof raw?.description === "string" ? raw.description : "",
13561
+ path: storyPath,
13562
+ slices: asStringArray2(raw?.slices).map(normalizeRelativePath2)
13563
+ };
13564
+ }
13565
+ function parseStories(projectRoot, storiesDir) {
13566
+ const pattern = path2.posix.join(storiesDir, "*.yaml");
13567
+ return import_fast_glob.default.sync(pattern, { cwd: projectRoot, onlyFiles: true, ignore: ["node_modules/**", ".git/**", "dist/**"] }).sort().map((storyPath) => parseStoryText2(storyPath, fs2.readFileSync(resolveProjectPath(projectRoot, storyPath), "utf8")));
13568
+ }
13569
+ function parseCommands2(value) {
13570
+ if (!Array.isArray(value))
13571
+ return [];
13572
+ return value.filter((item) => Boolean(item) && typeof item === "object").map((item) => ({
13573
+ name: typeof item.name === "string" ? item.name : "",
13574
+ fields: typeof item.fields === "string" ? item.fields : void 0,
13575
+ notes: typeof item.notes === "string" ? item.notes : void 0,
13576
+ produces: asStringArray2(item.produces)
13577
+ }));
13578
+ }
13579
+ function parseQueries2(value) {
13580
+ if (!Array.isArray(value))
13581
+ return [];
13582
+ return value.filter((item) => Boolean(item) && typeof item === "object").map((item) => ({
13583
+ name: typeof item.name === "string" ? item.name : "",
13584
+ fields: typeof item.fields === "string" ? item.fields : void 0,
13585
+ notes: typeof item.notes === "string" ? item.notes : void 0,
13586
+ fromEvents: asStringArray2(item.from_events)
13587
+ }));
13588
+ }
13589
+ function parseGwt2(value) {
13590
+ if (!Array.isArray(value))
13591
+ return [];
13592
+ return value.filter((item) => Boolean(item) && typeof item === "object").map((item) => ({
13593
+ name: typeof item.name === "string" ? item.name : void 0,
13594
+ description: typeof item.description === "string" ? item.description : void 0,
13595
+ given: Array.isArray(item.given) ? item.given : [],
13596
+ when: Array.isArray(item.when) ? item.when : [],
13597
+ then: Array.isArray(item.then) ? item.then : []
13598
+ }));
13599
+ }
13600
+ function parseScreen2(raw) {
13601
+ return {
13602
+ type: raw?.type === "system" ? "system" : "user",
13603
+ name: typeof raw?.name === "string" ? raw.name : void 0,
13604
+ ...parseActorReferences(raw?.actors),
13605
+ reads: asStringArray2(raw?.reads),
13606
+ executes: asStringArray2(raw?.executes)
13607
+ };
13608
+ }
13609
+ function parseSliceText2(slicePath, content, storyBySlice) {
13610
+ const raw = import_yaml4.default.parse(content);
13611
+ return {
13612
+ title: typeof raw?.slice === "string" ? raw.slice : path2.basename(slicePath),
13613
+ path: slicePath,
13614
+ storyName: storyBySlice.get(slicePath),
13615
+ screen: parseScreen2(raw?.screen),
13616
+ commands: parseCommands2(raw?.commands),
13617
+ queries: parseQueries2(raw?.queries),
13618
+ gwt: parseGwt2(raw?.gwt),
13619
+ raw: content
13620
+ };
13621
+ }
13393
13622
  function parseSlices(projectRoot, stories, sliceGlob) {
13394
13623
  const storyBySlice = /* @__PURE__ */ new Map();
13395
13624
  for (const story of stories) {
@@ -13404,7 +13633,7 @@ function parseSlices(projectRoot, stories, sliceGlob) {
13404
13633
  ignore: ["node_modules/**", ".git/**", "dist/**", "build/**"]
13405
13634
  });
13406
13635
  const paths = [.../* @__PURE__ */ new Set([...storySlices, ...discoveredSlices])].sort();
13407
- return paths.filter((slicePath) => fs2.existsSync(resolveProjectPath(projectRoot, slicePath))).map((slicePath) => parseSliceText(slicePath, fs2.readFileSync(resolveProjectPath(projectRoot, slicePath), "utf8"), storyBySlice));
13636
+ return paths.filter((slicePath) => fs2.existsSync(resolveProjectPath(projectRoot, slicePath))).map((slicePath) => parseSliceText2(slicePath, fs2.readFileSync(resolveProjectPath(projectRoot, slicePath), "utf8"), storyBySlice));
13408
13637
  }
13409
13638
  function loadEventModelProject(startDir) {
13410
13639
  const root = findProjectRoot(startDir);
@@ -13412,7 +13641,11 @@ function loadEventModelProject(startDir) {
13412
13641
  const events = parseEvents(root, config.paths.eventsFile);
13413
13642
  const stories = parseStories(root, config.paths.storiesDir);
13414
13643
  const slices = parseSlices(root, stories, path2.posix.join(config.paths.featuresDir, `**/*${config.paths.sliceExtension}`));
13415
- const projectWithoutGraph = { root, config, events, stories, slices };
13644
+ const actorsPath = config.paths.actorsFile ?? path2.posix.join(config.paths.eventModelDir, "actors.yaml");
13645
+ const absoluteActorsPath = resolveProjectPath(root, actorsPath);
13646
+ const actorsContent = fs2.existsSync(absoluteActorsPath) ? fs2.readFileSync(absoluteActorsPath, "utf8") : void 0;
13647
+ const actorData = loadActors(actorsContent, actorsPath, slices);
13648
+ const projectWithoutGraph = { root, config, events, stories, slices, ...actorData };
13416
13649
  const graph = buildGraph(projectWithoutGraph);
13417
13650
  return {
13418
13651
  ...projectWithoutGraph,
@@ -13420,9 +13653,53 @@ function loadEventModelProject(startDir) {
13420
13653
  };
13421
13654
  }
13422
13655
 
13423
- // ../graph/dist/index.js
13656
+ // src/gitSources.ts
13424
13657
  import fs3 from "node:fs";
13658
+ import os from "node:os";
13425
13659
  import path3 from "node:path";
13660
+ import { execFileSync } from "node:child_process";
13661
+ function materializeGitRef(ref, cwd = process.cwd()) {
13662
+ const tempRoot = fs3.mkdtempSync(path3.join(os.tmpdir(), "emviz-diff-"));
13663
+ const files = execFileSync("git", ["ls-tree", "-r", "-z", "--name-only", ref, "--", ".event-modeling", "event-model"], {
13664
+ cwd,
13665
+ encoding: "utf8"
13666
+ }).split("\0").filter(Boolean);
13667
+ if (files.includes(".event-modeling/config.yaml")) {
13668
+ const configText = execFileSync("git", ["show", `${ref}:.event-modeling/config.yaml`], {
13669
+ cwd,
13670
+ encoding: "utf8",
13671
+ maxBuffer: 20 * 1024 * 1024
13672
+ });
13673
+ const config = parseConfig(configText);
13674
+ const actorsFile = path3.posix.normalize(config.paths.actorsFile ?? path3.posix.join(config.paths.eventModelDir, "actors.yaml"));
13675
+ if (path3.isAbsolute(actorsFile) || actorsFile === ".." || actorsFile.startsWith("../")) {
13676
+ throw new Error("Actor registry must stay inside the project directory.");
13677
+ }
13678
+ if (!files.includes(actorsFile)) {
13679
+ const tracked = execFileSync("git", ["ls-tree", "-r", "-z", "--name-only", ref, "--", actorsFile], {
13680
+ cwd,
13681
+ encoding: "utf8"
13682
+ }).split("\0");
13683
+ if (tracked.includes(actorsFile)) files.push(actorsFile);
13684
+ }
13685
+ }
13686
+ if (files.length === 0) throw new Error(`Git ref "${ref}" does not contain .event-modeling or event-model files.`);
13687
+ for (const file of files) {
13688
+ const content = execFileSync("git", ["show", `${ref}:${file}`], {
13689
+ cwd,
13690
+ encoding: "utf8",
13691
+ maxBuffer: 20 * 1024 * 1024
13692
+ });
13693
+ const outputPath = path3.join(tempRoot, file);
13694
+ fs3.mkdirSync(path3.dirname(outputPath), { recursive: true });
13695
+ fs3.writeFileSync(outputPath, content);
13696
+ }
13697
+ return tempRoot;
13698
+ }
13699
+
13700
+ // ../graph/dist/index.js
13701
+ import fs4 from "node:fs";
13702
+ import path4 from "node:path";
13426
13703
  function selectorForNode(node) {
13427
13704
  switch (node.type) {
13428
13705
  case "story":
@@ -13446,7 +13723,7 @@ function sourceTypeForNode(node) {
13446
13723
  return node.type === "processor" ? "screen" : node.type;
13447
13724
  }
13448
13725
  function defaultModelId(projectRoot) {
13449
- return path3.basename(projectRoot).replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase() || "event_model";
13726
+ return path4.basename(projectRoot).replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase() || "event_model";
13450
13727
  }
13451
13728
  function nodeSelectorKey(node) {
13452
13729
  return JSON.stringify({ type: node.type, selector: node.selector });
@@ -13485,6 +13762,7 @@ function comparableNode(node) {
13485
13762
  sliceTitle: node.sliceTitle,
13486
13763
  sourceName: node.sourceName,
13487
13764
  actors: node.actors,
13765
+ actorDefinitions: node.actorDefinitions,
13488
13766
  screenType: node.screenType,
13489
13767
  fields: node.fields,
13490
13768
  description: node.description,
@@ -13497,8 +13775,7 @@ function edgeKey(edge, nodeKeys) {
13497
13775
  return stableJson({
13498
13776
  kind: edge.kind,
13499
13777
  source: nodeKeys.get(edge.source) ?? edge.source,
13500
- target: nodeKeys.get(edge.target) ?? edge.target,
13501
- label: edge.label
13778
+ target: nodeKeys.get(edge.target) ?? edge.target
13502
13779
  });
13503
13780
  }
13504
13781
  function comparableEdge(edge, nodeKeys) {
@@ -13519,6 +13796,8 @@ function cloneProject(project) {
13519
13796
  return {
13520
13797
  ...project,
13521
13798
  events: project.events.map((event) => ({ ...event })),
13799
+ actors: project.actors?.map((actor) => ({ ...actor })),
13800
+ actorIssues: project.actorIssues?.map((issue) => ({ ...issue })),
13522
13801
  stories: project.stories.map((story) => ({ ...story, slices: [...story.slices] })),
13523
13802
  slices: project.slices.map((slice) => ({
13524
13803
  ...slice,
@@ -13532,7 +13811,7 @@ function cloneProject(project) {
13532
13811
  then: [...scenario.then]
13533
13812
  }))
13534
13813
  })),
13535
- nodes: project.nodes.map((node) => ({ ...node })),
13814
+ nodes: project.nodes.map((node) => structuredClone(node)),
13536
13815
  edges: project.edges.map((edge) => ({ ...edge }))
13537
13816
  };
13538
13817
  }
@@ -13621,6 +13900,7 @@ function buildGraphSidecar(project, existing) {
13621
13900
  },
13622
13901
  sources: {
13623
13902
  events: project.config.paths.eventsFile,
13903
+ actors: project.config.paths.actorsFile,
13624
13904
  stories: [`${project.config.paths.storiesDir}/**/*.yaml`],
13625
13905
  slices: [`${project.config.paths.featuresDir}/**/*${project.config.paths.sliceExtension}`]
13626
13906
  },
@@ -13654,6 +13934,8 @@ function diffEventModelProjects(base, target, labels = {}) {
13654
13934
  const targetNodesByKey = new Map(target.nodes.map((node) => [targetNodeKeysById.get(node.id), node]));
13655
13935
  const nodeStatus = {};
13656
13936
  const previousGwtNodes = {};
13937
+ const previousNodes = {};
13938
+ const previousEdges = {};
13657
13939
  const mergedNodeIdByBaseId = /* @__PURE__ */ new Map();
13658
13940
  mergeRemovedModelContainers(merged, base);
13659
13941
  for (const targetNode of target.nodes) {
@@ -13664,8 +13946,11 @@ function diffEventModelProjects(base, target, labels = {}) {
13664
13946
  continue;
13665
13947
  }
13666
13948
  nodeStatus[targetNode.id] = stableJson(comparableNode(baseNode)) === stableJson(comparableNode(targetNode)) ? "unchanged" : "changed";
13667
- if (targetNode.type === "gwt" && nodeStatus[targetNode.id] === "changed")
13668
- previousGwtNodes[targetNode.id] = structuredClone(baseNode);
13949
+ if (nodeStatus[targetNode.id] === "changed") {
13950
+ previousNodes[targetNode.id] = structuredClone(baseNode);
13951
+ if (targetNode.type === "gwt")
13952
+ previousGwtNodes[targetNode.id] = structuredClone(baseNode);
13953
+ }
13669
13954
  }
13670
13955
  for (const baseNode of base.nodes) {
13671
13956
  const key = baseNodeKeysById.get(baseNode.id);
@@ -13673,8 +13958,9 @@ function diffEventModelProjects(base, target, labels = {}) {
13673
13958
  continue;
13674
13959
  const id = uniqueNodeId(existingNodeIds, baseNode.id);
13675
13960
  mergedNodeIdByBaseId.set(baseNode.id, id);
13676
- merged.nodes.push({ ...baseNode, id });
13961
+ merged.nodes.push({ ...structuredClone(baseNode), id });
13677
13962
  nodeStatus[id] = "removed";
13963
+ previousNodes[id] = structuredClone(baseNode);
13678
13964
  }
13679
13965
  const baseEdgesByKey = new Map(base.edges.map((edge) => [edgeKey(edge, baseNodeKeysById), edge]));
13680
13966
  const targetEdgesByKey = new Map(target.edges.map((edge) => [edgeKey(edge, targetNodeKeysById), edge]));
@@ -13687,6 +13973,8 @@ function diffEventModelProjects(base, target, labels = {}) {
13687
13973
  continue;
13688
13974
  }
13689
13975
  edgeStatus[targetEdge.id] = stableJson(comparableEdge(baseEdge, baseNodeKeysById)) === stableJson(comparableEdge(targetEdge, targetNodeKeysById)) ? "unchanged" : "changed";
13976
+ if (edgeStatus[targetEdge.id] === "changed")
13977
+ previousEdges[targetEdge.id] = structuredClone(baseEdge);
13690
13978
  }
13691
13979
  for (const baseEdge of base.edges) {
13692
13980
  const key = edgeKey(baseEdge, baseNodeKeysById);
@@ -13697,6 +13985,7 @@ function diffEventModelProjects(base, target, labels = {}) {
13697
13985
  const id = uniqueEdgeId(existingEdgeIds, baseEdge.id);
13698
13986
  merged.edges.push({ ...baseEdge, id, source, target: targetId });
13699
13987
  edgeStatus[id] = "removed";
13988
+ previousEdges[id] = structuredClone(baseEdge);
13700
13989
  }
13701
13990
  return {
13702
13991
  project: merged,
@@ -13704,6 +13993,8 @@ function diffEventModelProjects(base, target, labels = {}) {
13704
13993
  base: { label: labels.base ?? "base" },
13705
13994
  target: { label: labels.target ?? "target" },
13706
13995
  previousGwtNodes,
13996
+ previousNodes,
13997
+ previousEdges,
13707
13998
  nodeStatus,
13708
13999
  edgeStatus,
13709
14000
  summary: {
@@ -13714,13 +14005,13 @@ function diffEventModelProjects(base, target, labels = {}) {
13714
14005
  };
13715
14006
  }
13716
14007
  function readGraphSidecar(projectRoot) {
13717
- const sidecarPath = path3.join(projectRoot, ".event-modeling", "graph.json");
13718
- if (!fs3.existsSync(sidecarPath))
14008
+ const sidecarPath = path4.join(projectRoot, ".event-modeling", "graph.json");
14009
+ if (!fs4.existsSync(sidecarPath))
13719
14010
  return void 0;
13720
- return JSON.parse(fs3.readFileSync(sidecarPath, "utf8"));
14011
+ return JSON.parse(fs4.readFileSync(sidecarPath, "utf8"));
13721
14012
  }
13722
14013
  function writeGraphSidecar(project) {
13723
- const sidecarPath = path3.join(project.root, ".event-modeling", "graph.json");
14014
+ const sidecarPath = path4.join(project.root, ".event-modeling", "graph.json");
13724
14015
  const existing = readGraphSidecar(project.root);
13725
14016
  const next = buildGraphSidecar(project, existing);
13726
14017
  const generated = generatedNodes(project);
@@ -13729,8 +14020,8 @@ function writeGraphSidecar(project) {
13729
14020
  const added = Object.entries(generated).filter(([, node]) => !existingSelectorKeys.has(nodeSelectorKey(node))).map(([id]) => id);
13730
14021
  const preserved = Object.entries(existing?.nodes ?? {}).filter(([, node]) => generatedSelectorKeys.has(nodeSelectorKey(node))).map(([id]) => id);
13731
14022
  const stale = Object.entries(existing?.nodes ?? {}).filter(([, node]) => !generatedSelectorKeys.has(nodeSelectorKey(node))).map(([id]) => id);
13732
- fs3.mkdirSync(path3.dirname(sidecarPath), { recursive: true });
13733
- fs3.writeFileSync(sidecarPath, `${JSON.stringify(next, null, 2)}
14023
+ fs4.mkdirSync(path4.dirname(sidecarPath), { recursive: true });
14024
+ fs4.writeFileSync(sidecarPath, `${JSON.stringify(next, null, 2)}
13734
14025
  `);
13735
14026
  return {
13736
14027
  path: sidecarPath,
@@ -13751,8 +14042,8 @@ function resolveSidecarNode(project, node) {
13751
14042
  }
13752
14043
 
13753
14044
  // ../validator/dist/index.js
13754
- import fs4 from "node:fs";
13755
- import path4 from "node:path";
14045
+ import fs5 from "node:fs";
14046
+ import path5 from "node:path";
13756
14047
  function finding(severity, check, message, pathValue, nodeId) {
13757
14048
  return {
13758
14049
  id: `${check}:${pathValue ?? "project"}:${message}`,
@@ -13853,8 +14144,8 @@ function connectedComponentCount(project) {
13853
14144
  }
13854
14145
  return components;
13855
14146
  }
13856
- function validateEventModelProject(project) {
13857
- const findings = [];
14147
+ function validateEventModelProject(project, snapshot) {
14148
+ const findings = (project.actorIssues ?? []).map((issue) => finding("error", "A1", issue.message, issue.path));
13858
14149
  const eventNames = new Set(project.events.map((event) => event.name));
13859
14150
  const produced = /* @__PURE__ */ new Map();
13860
14151
  const consumed = /* @__PURE__ */ new Map();
@@ -13863,7 +14154,7 @@ function validateEventModelProject(project) {
13863
14154
  findings.push(finding("warning", "S4", `Story "${story.name}" has ${story.slices.length} slices; consider splitting it.`, story.path));
13864
14155
  }
13865
14156
  for (const slicePath of story.slices) {
13866
- if (!fs4.existsSync(path4.join(project.root, slicePath))) {
14157
+ if (snapshot ? !snapshot.sourcePaths.has(slicePath) : !fs5.existsSync(path5.join(project.root, slicePath))) {
13867
14158
  findings.push(finding("error", "S2", `Story "${story.name}" lists missing slice "${slicePath}".`, story.path));
13868
14159
  }
13869
14160
  }
@@ -13978,7 +14269,7 @@ function validateEventModelProject(project) {
13978
14269
  if (commandSliceCount > 0 && project.events.length / commandSliceCount > 2) {
13979
14270
  findings.push(finding("warning", "M4", `The model has ${(project.events.length / commandSliceCount).toFixed(1)} events per command slice; check for UI/runtime events leaking into the model.`));
13980
14271
  }
13981
- const sidecar = readGraphSidecar(project.root);
14272
+ const sidecar = snapshot ? snapshot.sidecar : readGraphSidecar(project.root);
13982
14273
  if (sidecar) {
13983
14274
  for (const [nodeId, sidecarNode] of Object.entries(sidecar.nodes)) {
13984
14275
  const matches = resolveSidecarNode(project, sidecarNode);
@@ -14001,11 +14292,507 @@ function validateEventModelProject(project) {
14001
14292
  };
14002
14293
  }
14003
14294
 
14295
+ // src/feedback.ts
14296
+ import fs6 from "node:fs";
14297
+ import path6 from "node:path";
14298
+ import { randomUUID, createHash, timingSafeEqual } from "node:crypto";
14299
+ import { execFileSync as execFileSync2 } from "node:child_process";
14300
+ var FeedbackError = class extends Error {
14301
+ constructor(status, message) {
14302
+ super(message);
14303
+ this.status = status;
14304
+ }
14305
+ status;
14306
+ };
14307
+ function sourceKey(root, source) {
14308
+ const relative = path6.relative(root, path6.resolve(root, source));
14309
+ if (path6.isAbsolute(source) || relative.startsWith("..") || path6.isAbsolute(relative)) throw new FeedbackError(400, "Model sources must stay inside the project directory.");
14310
+ return relative.split(path6.sep).join("/");
14311
+ }
14312
+ function withinRoot(root, source) {
14313
+ const key = sourceKey(root, source);
14314
+ const resolved = fs6.realpathSync(path6.resolve(root, key));
14315
+ const relative = path6.relative(fs6.realpathSync(root), resolved);
14316
+ if (relative.startsWith("..") || path6.isAbsolute(relative)) throw new FeedbackError(400, "Model sources must stay inside the project directory.");
14317
+ return resolved;
14318
+ }
14319
+ function sourceExists(root, source) {
14320
+ try {
14321
+ fs6.lstatSync(path6.resolve(root, sourceKey(root, source)));
14322
+ return true;
14323
+ } catch (error) {
14324
+ if (error.code === "ENOENT") return false;
14325
+ throw error;
14326
+ }
14327
+ }
14328
+ function normalizedConfig(root, text) {
14329
+ const config = parseConfig(text);
14330
+ return { ...config, paths: {
14331
+ ...config.paths,
14332
+ eventModelDir: sourceKey(root, config.paths.eventModelDir),
14333
+ featuresDir: sourceKey(root, config.paths.featuresDir),
14334
+ eventsFile: sourceKey(root, config.paths.eventsFile),
14335
+ actorsFile: sourceKey(root, config.paths.actorsFile ?? path6.posix.join(config.paths.eventModelDir, "actors.yaml")),
14336
+ storiesDir: sourceKey(root, config.paths.storiesDir)
14337
+ } };
14338
+ }
14339
+ function parseFiles(root, files, config) {
14340
+ const paths = config.paths;
14341
+ const normalized = JSON.stringify({ language: config.language, paths: {
14342
+ event_model_dir: paths.eventModelDir,
14343
+ features_dir: paths.featuresDir,
14344
+ events_file: paths.eventsFile,
14345
+ actors_file: paths.actorsFile,
14346
+ stories_dir: paths.storiesDir,
14347
+ slice_extension: paths.sliceExtension
14348
+ } });
14349
+ return loadEventModelProjectFromFiles([...files].map(([name, content]) => ({
14350
+ path: name,
14351
+ content: name === ".event-modeling/config.yaml" ? normalized : content
14352
+ })), { root });
14353
+ }
14354
+ function readSnapshot(target) {
14355
+ const root = findProjectRoot(target);
14356
+ const files = /* @__PURE__ */ new Map();
14357
+ let bytes = 0;
14358
+ const read = (source) => {
14359
+ const key = sourceKey(root, source);
14360
+ if (files.has(key)) return;
14361
+ const file = withinRoot(root, key);
14362
+ if (files.size >= 512 || fs6.statSync(file).size + bytes > 8 * 1024 * 1024) throw new FeedbackError(413, "Feedback supports at most 512 files and 8 MiB.");
14363
+ const content = fs6.readFileSync(file, "utf8");
14364
+ bytes += Buffer.byteLength(content);
14365
+ if (bytes > 8 * 1024 * 1024) throw new FeedbackError(413, "Model grew beyond 8 MiB while reading.");
14366
+ files.set(key, content);
14367
+ };
14368
+ read(".event-modeling/config.yaml");
14369
+ const config = normalizedConfig(root, files.get(".event-modeling/config.yaml"));
14370
+ read(config.paths.eventsFile);
14371
+ if (config.paths.actorsFile && sourceExists(root, config.paths.actorsFile)) read(config.paths.actorsFile);
14372
+ let visitedEntries = 0;
14373
+ const walk = (directory, recursive, extension, visited = /* @__PURE__ */ new Set()) => {
14374
+ const key = sourceKey(root, directory);
14375
+ if (!sourceExists(root, key)) return;
14376
+ const resolved = withinRoot(root, key);
14377
+ if (visited.has(resolved)) return;
14378
+ visited.add(resolved);
14379
+ for (const entry of fs6.readdirSync(resolved, { withFileTypes: true })) {
14380
+ if (++visitedEntries > 1e4) throw new FeedbackError(413, "Model discovery exceeds 10000 directory entries.");
14381
+ if (entry.name.startsWith(".") || key === "" && ["node_modules", "dist", "build"].includes(entry.name)) continue;
14382
+ const relative = path6.posix.join(key, entry.name);
14383
+ const actual = withinRoot(root, relative);
14384
+ const stat = fs6.statSync(actual);
14385
+ if (stat.isDirectory() && recursive) walk(relative, true, extension, visited);
14386
+ else if (stat.isFile() && entry.name.endsWith(extension)) read(relative);
14387
+ }
14388
+ };
14389
+ walk(config.paths.storiesDir, false, ".yaml");
14390
+ walk(config.paths.featuresDir, true, config.paths.sliceExtension);
14391
+ const preliminary = parseFiles(root, files, config);
14392
+ for (const source of preliminary.stories.flatMap((story) => story.slices)) {
14393
+ const key = sourceKey(root, source);
14394
+ if (sourceExists(root, key)) read(key);
14395
+ }
14396
+ if (sourceExists(root, ".event-modeling/graph.json")) read(".event-modeling/graph.json");
14397
+ const project = parseFiles(root, files, config);
14398
+ const sidecarText = files.get(".event-modeling/graph.json");
14399
+ const graphSidecar = sidecarText === void 0 ? void 0 : JSON.parse(sidecarText);
14400
+ if (graphSidecar !== void 0 && (!graphSidecar || typeof graphSidecar !== "object" || typeof graphSidecar.model?.id !== "string" || !graphSidecar.nodes || typeof graphSidecar.nodes !== "object" || Array.isArray(graphSidecar.nodes) || Object.values(graphSidecar.nodes).some((node) => !node || typeof node.type !== "string" || !node.selector || typeof node.selector !== "object" || Object.values(node.selector).some((value) => typeof value !== "string")))) throw new FeedbackError(422, "Invalid .event-modeling/graph.json.");
14401
+ const validation = validateEventModelProject(project, { sourcePaths: new Set(files.keys()), sidecar: graphSidecar });
14402
+ const hash = createHash("sha256");
14403
+ for (const [source, content] of [...files].sort(([a], [b]) => a.localeCompare(b))) {
14404
+ const actual = withinRoot(root, source);
14405
+ if (fs6.statSync(actual).size > 8 * 1024 * 1024 || fs6.readFileSync(actual, "utf8") !== content) throw new FeedbackError(409, "Model changed while reading. Try again.");
14406
+ hash.update(JSON.stringify([source, content]));
14407
+ }
14408
+ return { project, revision: hash.digest("hex"), files, graphSidecar, validation };
14409
+ }
14410
+ function gitBaseline(snapshot) {
14411
+ const root = snapshot.project.root;
14412
+ try {
14413
+ const git = (args2) => execFileSync2("git", ["-C", root, ...args2], { encoding: "utf8", maxBuffer: 8 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
14414
+ const commit = git(["rev-parse", "--verify", "HEAD^{commit}"]).trim();
14415
+ const repoRoot = git(["rev-parse", "--show-toplevel"]).trim();
14416
+ const prefix = path6.relative(fs6.realpathSync(repoRoot), fs6.realpathSync(root)).split(path6.sep).join("/");
14417
+ const names = git(["-C", repoRoot, "ls-tree", "--full-tree", "-r", "-z", "--name-only", commit, "--", prefix || "."]).split("\0").filter(Boolean);
14418
+ const tracked = new Set(names.map((name) => prefix ? name.slice(prefix.length + 1) : name));
14419
+ const files = /* @__PURE__ */ new Map();
14420
+ let bytes = 0;
14421
+ const read = (source) => {
14422
+ const key = sourceKey(root, source);
14423
+ if (files.has(key) || !tracked.has(key)) return;
14424
+ if (files.size >= 512) throw new Error("Git baseline exceeds 512 files.");
14425
+ const content = git(["show", commit + ":" + (prefix ? prefix + "/" : "") + key]);
14426
+ bytes += Buffer.byteLength(content);
14427
+ if (bytes > 8 * 1024 * 1024) throw new Error("Git baseline exceeds 8 MiB.");
14428
+ files.set(key, content);
14429
+ };
14430
+ read(".event-modeling/config.yaml");
14431
+ const rawConfig = files.get(".event-modeling/config.yaml");
14432
+ if (rawConfig === void 0) throw new Error("No model configuration at the baseline commit.");
14433
+ const config = normalizedConfig(root, rawConfig);
14434
+ read(config.paths.eventsFile);
14435
+ if (config.paths.actorsFile) read(config.paths.actorsFile);
14436
+ for (const key of tracked) {
14437
+ const isStory = (path6.posix.dirname(key) === "." ? "" : path6.posix.dirname(key)) === config.paths.storiesDir && !path6.posix.basename(key).startsWith(".") && key.endsWith(".yaml");
14438
+ const relative = config.paths.featuresDir ? key.slice(config.paths.featuresDir.length + 1) : key;
14439
+ const ignored = relative.split("/").some((part) => part.startsWith(".")) || ["node_modules/", "dist/", "build/"].some((directory) => key.startsWith(directory));
14440
+ const isSlice = !ignored && (config.paths.featuresDir === "" || key.startsWith(config.paths.featuresDir + "/")) && key.endsWith(config.paths.sliceExtension);
14441
+ if (isStory || isSlice) read(key);
14442
+ }
14443
+ const preliminary = parseFiles(root, files, config);
14444
+ for (const source of preliminary.stories.flatMap((story) => story.slices)) read(source);
14445
+ return { project: parseFiles(root, files, config), label: commit, kind: "git" };
14446
+ } catch (error) {
14447
+ return { project: structuredClone(snapshot.project), label: "Startup snapshot (Git baseline unavailable: " + (error instanceof Error ? error.message.split("\n")[0] : "unknown error") + ")", kind: "startup" };
14448
+ }
14449
+ }
14450
+ function textField(value, name, max) {
14451
+ if (typeof value !== "string" || !value.trim() || value.length > max) throw new FeedbackError(400, name + " must contain 1 to " + max + " characters.");
14452
+ return value;
14453
+ }
14454
+ var FeedbackSession = class {
14455
+ constructor(target) {
14456
+ this.target = target;
14457
+ this.current = readSnapshot(target);
14458
+ this.baseline = gitBaseline(this.current);
14459
+ }
14460
+ target;
14461
+ id = randomUUID();
14462
+ token = randomUUID();
14463
+ current;
14464
+ baseline;
14465
+ state = { status: "idle" };
14466
+ history = [];
14467
+ lastSeen;
14468
+ error;
14469
+ waiter;
14470
+ polling = false;
14471
+ generation = 0;
14472
+ refresh() {
14473
+ try {
14474
+ this.current = readSnapshot(this.target);
14475
+ this.error = void 0;
14476
+ return this.current;
14477
+ } catch (error) {
14478
+ this.error = error instanceof Error ? error.message : String(error);
14479
+ throw new FeedbackError(422, this.error);
14480
+ }
14481
+ }
14482
+ archive(request) {
14483
+ this.history = [...this.history.filter((entry) => entry.id !== request.id), { ...request }].slice(-20);
14484
+ }
14485
+ snapshot(view) {
14486
+ try {
14487
+ this.refresh();
14488
+ } catch {
14489
+ }
14490
+ let displayed = this.current;
14491
+ let project = displayed.project;
14492
+ let diff;
14493
+ if (view === "session") {
14494
+ const result = diffEventModelProjects(this.baseline.project, project, { base: this.baseline.label, target: "Working tree (all edits)" });
14495
+ project = result.project;
14496
+ diff = result.diff;
14497
+ } else if (view === "turn" && (this.state.status === "working" || this.state.status === "completed")) {
14498
+ const after = this.state.status === "completed" ? this.state.after : this.current;
14499
+ displayed = after;
14500
+ const result = diffEventModelProjects(this.state.before.project, after.project, { base: "Request " + this.state.context.request.id + " start", target: this.state.status === "completed" ? "Request reply (all edits)" : "Working tree (all edits)" });
14501
+ project = result.project;
14502
+ diff = result.diff;
14503
+ }
14504
+ return {
14505
+ sessionId: this.id,
14506
+ token: this.token,
14507
+ revision: this.current.revision,
14508
+ project: { ...project, graphSidecar: displayed.graphSidecar },
14509
+ validation: displayed.validation,
14510
+ diff,
14511
+ baseline: { kind: this.baseline.kind, label: this.baseline.label },
14512
+ error: this.error,
14513
+ stale: Boolean(this.error),
14514
+ feedback: {
14515
+ status: this.state.status,
14516
+ request: "context" in this.state ? this.state.context?.request : void 0,
14517
+ history: this.history,
14518
+ agent: { connected: this.lastSeen !== void 0 && Date.now() - this.lastSeen < 6e4, lastSeen: this.lastSeen }
14519
+ }
14520
+ };
14521
+ }
14522
+ submit(body) {
14523
+ const clientRequestId = textField(body.clientRequestId, "clientRequestId", 100);
14524
+ const message = textField(body.message, "message", 4e3);
14525
+ const nodeId = textField(body.nodeId, "nodeId", 500);
14526
+ const revision = textField(body.revision, "revision", 100);
14527
+ const active = "context" in this.state ? this.state.context?.request : void 0;
14528
+ const known = active?.clientRequestId === clientRequestId ? active : this.history.find((item) => item.clientRequestId === clientRequestId);
14529
+ if (known?.clientRequestId === clientRequestId) {
14530
+ if (known.message !== message || known.nodeId !== nodeId) throw new FeedbackError(409, "Request ID already used with different content.");
14531
+ return known;
14532
+ }
14533
+ if (this.state.status === "stopped") throw new FeedbackError(409, "Feedback is stopped.");
14534
+ if (this.state.status === "working" || this.state.status === "queued") throw new FeedbackError(409, "Finish or stop the active request first.");
14535
+ const snapshot = this.refresh();
14536
+ if (revision !== snapshot.revision) throw new FeedbackError(409, "Model changed. Refresh and select the element again.");
14537
+ const node = snapshot.project.nodes.find((item) => item.id === nodeId);
14538
+ if (!node) throw new FeedbackError(409, "This element is no longer in the current model.");
14539
+ const request = {
14540
+ id: randomUUID(),
14541
+ clientRequestId,
14542
+ message,
14543
+ nodeId,
14544
+ createdAt: Date.now(),
14545
+ reference: "em://" + (snapshot.graphSidecar?.model.id ?? "event_model") + "/" + nodeId
14546
+ };
14547
+ const yaml = node.sourcePath && snapshot.files.get(node.sourcePath) || node.raw || node.fields || node.description || node.label;
14548
+ if (yaml.length > 64e3) throw new FeedbackError(413, "Selected source exceeds 64000 characters.");
14549
+ const related = snapshot.project.edges.filter((edge) => edge.source === nodeId || edge.target === nodeId);
14550
+ const context = JSON.stringify({ node, validationFindings: snapshot.validation.findings.filter((finding2) => finding2.nodeId === nodeId || finding2.path === node.sourcePath), connections: related.map((edge) => ({ ...edge, sourceNode: snapshot.project.nodes.find((item) => item.id === edge.source), targetNode: snapshot.project.nodes.find((item) => item.id === edge.target) })) });
14551
+ if (context.length > 128e3) throw new FeedbackError(413, "Connected context exceeds 128000 characters.");
14552
+ this.state = { status: "queued", context: { request, revision, sourcePath: node.sourcePath, yaml, context } };
14553
+ this.waiter?.();
14554
+ return request;
14555
+ }
14556
+ async poll(agent, signal, waitMs = 25e3) {
14557
+ const agentId = textField(agent, "agent", 100);
14558
+ if (this.polling) throw new FeedbackError(409, "Only one poll may wait at a time.");
14559
+ if (this.state.status === "working" && this.state.agentId !== agentId) throw new FeedbackError(409, "Another agent owns the active request.");
14560
+ this.polling = true;
14561
+ const generation = this.generation;
14562
+ this.lastSeen = Date.now();
14563
+ try {
14564
+ if (this.state.status !== "queued" && this.state.status !== "working" && this.state.status !== "stopped") {
14565
+ await new Promise((resolve) => {
14566
+ const finish = () => {
14567
+ clearTimeout(timer);
14568
+ signal?.removeEventListener("abort", finish);
14569
+ this.waiter = void 0;
14570
+ resolve();
14571
+ };
14572
+ const timer = setTimeout(finish, Math.min(25e3, Math.max(0, waitMs)));
14573
+ this.waiter = finish;
14574
+ signal?.addEventListener("abort", finish, { once: true });
14575
+ if (signal?.aborted) finish();
14576
+ });
14577
+ }
14578
+ if (signal?.aborted) return { status: "disconnected", next_step: "Reconnect only if this session is still wanted." };
14579
+ this.lastSeen = Date.now();
14580
+ if (generation !== this.generation || this.state.status === "stopped") return { status: "stopped", next_step: "Stop polling and stop editing. The server cannot stop your process." };
14581
+ if (this.state.status === "queued") {
14582
+ const before = this.refresh();
14583
+ if (before.revision !== this.state.context.revision) {
14584
+ this.archive({ ...this.state.context.request, reply: "Model changed before the agent started. Select the element and send again." });
14585
+ this.state = { status: "idle" };
14586
+ throw new FeedbackError(409, "Model changed before claim. Request cancelled.");
14587
+ }
14588
+ this.state.context.request.agentId = agentId;
14589
+ this.state = { status: "working", context: this.state.context, agentId, before };
14590
+ }
14591
+ if (this.state.status === "working") {
14592
+ return { status: "request", request: { ...this.state.context.request, sourcePath: this.state.context.sourcePath, yaml: this.state.context.yaml, context: this.state.context.context, projectRoot: this.current.project.root, revision: this.state.context.revision }, next_step: "Edit canonical YAML directly, validate it, then run emviz reply with this request ID and the same --url, --token, and --agent. Do not start a second request or commit/reset files automatically." };
14593
+ }
14594
+ return { status: "timeout", next_step: "Run emviz poll again with the same --url, --token, and --agent. Wait in the foreground." };
14595
+ } finally {
14596
+ this.polling = false;
14597
+ }
14598
+ }
14599
+ reply(body) {
14600
+ const id = textField(body.id, "id", 100);
14601
+ const agentId = textField(body.agent, "agent", 100);
14602
+ const reply = textField(body.reply, "reply", 8e3);
14603
+ const recorded = this.history.find((entry) => entry.id === id && entry.agentId === agentId && entry.reply !== void 0);
14604
+ if (recorded) {
14605
+ if (recorded.reply !== reply) throw new FeedbackError(409, "Reply already recorded with different content.");
14606
+ return recorded;
14607
+ }
14608
+ if (this.state.status !== "working" || this.state.context.request.id !== id || this.state.agentId !== agentId) throw new FeedbackError(409, "No matching request owned by this agent.");
14609
+ const after = this.refresh();
14610
+ const request = { ...this.state.context.request, reply };
14611
+ this.state = { ...this.state, status: "completed", context: { ...this.state.context, request }, after };
14612
+ this.lastSeen = Date.now();
14613
+ this.archive(request);
14614
+ return request;
14615
+ }
14616
+ stop() {
14617
+ this.generation += 1;
14618
+ const context = "context" in this.state ? this.state.context : void 0;
14619
+ if (context) this.archive(context.request);
14620
+ this.state = { status: "stopped", context };
14621
+ this.lastSeen = void 0;
14622
+ this.waiter?.();
14623
+ }
14624
+ start() {
14625
+ if (this.state.status !== "stopped") throw new FeedbackError(409, "Session is already running.");
14626
+ this.state = { status: "idle" };
14627
+ }
14628
+ };
14629
+ function trustedRequest(req, port) {
14630
+ const allowed = /* @__PURE__ */ new Set(["localhost:" + port, "127.0.0.1:" + port]);
14631
+ const host = req.headers.host;
14632
+ if (!host || !allowed.has(host)) return false;
14633
+ const origin = req.headers.origin;
14634
+ return origin === void 0 || origin === "http://" + host;
14635
+ }
14636
+ function validToken(req, expected) {
14637
+ const token = req.headers["x-emviz-token"];
14638
+ if (typeof token !== "string") return false;
14639
+ const actual = Buffer.from(token);
14640
+ const wanted = Buffer.from(expected);
14641
+ return actual.length === wanted.length && timingSafeEqual(actual, wanted);
14642
+ }
14643
+ async function readJson(req) {
14644
+ if (req.headers["content-type"]?.split(";")[0] !== "application/json") throw new FeedbackError(415, "Use application/json.");
14645
+ const content = await new Promise((resolve, reject) => {
14646
+ let size = 0;
14647
+ let failed = false;
14648
+ const parts = [];
14649
+ req.on("data", (chunk) => {
14650
+ if (failed) return;
14651
+ size += chunk.length;
14652
+ if (size > 32768) {
14653
+ failed = true;
14654
+ parts.length = 0;
14655
+ reject(new FeedbackError(413, "Request exceeds 32 KiB."));
14656
+ } else parts.push(chunk);
14657
+ });
14658
+ req.once("end", () => {
14659
+ if (!failed) resolve(Buffer.concat(parts));
14660
+ });
14661
+ req.once("error", reject);
14662
+ req.once("aborted", () => reject(new FeedbackError(400, "Request disconnected.")));
14663
+ });
14664
+ try {
14665
+ const value = JSON.parse(content.toString("utf8"));
14666
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error();
14667
+ return value;
14668
+ } catch {
14669
+ throw new FeedbackError(400, "Expected a JSON object.");
14670
+ }
14671
+ }
14672
+ async function handleFeedback(req, res, session, close) {
14673
+ const url = new URL(req.url ?? "/", "http://localhost");
14674
+ if (url.pathname !== "/api/session" && !url.pathname.startsWith("/api/feedback/")) return false;
14675
+ const send = (value) => {
14676
+ res.setHeader("content-type", "application/json; charset=utf-8");
14677
+ res.setHeader("cache-control", "no-store");
14678
+ res.end(JSON.stringify(value));
14679
+ };
14680
+ try {
14681
+ if (url.pathname === "/api/session" && req.method === "GET") {
14682
+ const view = url.searchParams.get("view") ?? "current";
14683
+ if (!["current", "session", "turn"].includes(view)) throw new FeedbackError(400, "Unknown view.");
14684
+ send(session.snapshot(view));
14685
+ return true;
14686
+ }
14687
+ if (!validToken(req, session.token)) throw new FeedbackError(403, "Invalid session token.");
14688
+ if (url.pathname === "/api/feedback/poll" && req.method === "GET") {
14689
+ const controller = new AbortController();
14690
+ res.on("close", () => controller.abort());
14691
+ const result = await session.poll(url.searchParams.get("agent"), controller.signal);
14692
+ if (!res.destroyed) send(result);
14693
+ return true;
14694
+ }
14695
+ if (req.method !== "POST") throw new FeedbackError(405, "Method not allowed.");
14696
+ const body = await readJson(req);
14697
+ switch (url.pathname) {
14698
+ case "/api/feedback/request":
14699
+ send(session.submit(body));
14700
+ break;
14701
+ case "/api/feedback/reply":
14702
+ send({ request: session.reply(body), next_step: "Run emviz poll with the same connection options." });
14703
+ break;
14704
+ case "/api/feedback/stop":
14705
+ session.stop();
14706
+ send({ status: "stopped" });
14707
+ break;
14708
+ case "/api/feedback/start":
14709
+ session.start();
14710
+ send({ status: "idle" });
14711
+ break;
14712
+ case "/api/feedback/close":
14713
+ session.stop();
14714
+ send({ status: "closed" });
14715
+ close();
14716
+ break;
14717
+ default:
14718
+ throw new FeedbackError(404, "Unknown feedback endpoint.");
14719
+ }
14720
+ } catch (error) {
14721
+ if (!res.destroyed) {
14722
+ res.statusCode = error instanceof FeedbackError ? error.status : 500;
14723
+ send({ error: error instanceof Error ? error.message : String(error) });
14724
+ }
14725
+ }
14726
+ return true;
14727
+ }
14728
+
14729
+ // src/agent-cli.ts
14730
+ import { spawn } from "node:child_process";
14731
+ function parseConnection(values) {
14732
+ const options = /* @__PURE__ */ new Map();
14733
+ const positional = [];
14734
+ for (let index = 0; index < values.length; index++) {
14735
+ const value = values[index];
14736
+ if (value.startsWith("--")) {
14737
+ if (!["--url", "--token", "--agent"].includes(value) || !values[index + 1]) throw new Error("Unknown or incomplete option: " + value);
14738
+ options.set(value, values[++index]);
14739
+ } else positional.push(value);
14740
+ }
14741
+ const url = new URL(options.get("--url") ?? "");
14742
+ if (url.protocol !== "http:" || !["localhost", "127.0.0.1"].includes(url.hostname) || url.username || url.password || url.pathname !== "/" || url.search || url.hash) throw new Error("--url must be a loopback HTTP origin.");
14743
+ const token = options.get("--token");
14744
+ if (!token) throw new Error("--token is required. Use the token printed by emviz open.");
14745
+ return { url, token, agent: options.get("--agent"), positional };
14746
+ }
14747
+ async function runAgentCommand(command2, values) {
14748
+ const connection = parseConnection(values);
14749
+ if ((command2 === "poll" || command2 === "reply") && !connection.agent) throw new Error("--agent is required. Reuse one unique ID throughout the session.");
14750
+ const route = command2 === "poll" ? "/api/feedback/poll?agent=" + encodeURIComponent(connection.agent) : "/api/feedback/" + command2;
14751
+ const body = command2 === "reply" ? { id: connection.positional[0], reply: connection.positional[1], agent: connection.agent } : {};
14752
+ if (command2 === "reply" && connection.positional.length !== 2) throw new Error("Usage: emviz reply <request-id> <text> --url <url> --token <token> --agent <id>");
14753
+ if (command2 !== "reply" && connection.positional.length) throw new Error("Unexpected positional argument.");
14754
+ const response = await fetch(new URL(route, connection.url), {
14755
+ method: command2 === "poll" ? "GET" : "POST",
14756
+ headers: { "X-Emviz-Token": connection.token, "Content-Type": "application/json" },
14757
+ body: command2 === "poll" ? void 0 : JSON.stringify(body),
14758
+ signal: AbortSignal.timeout(3e4),
14759
+ redirect: "error"
14760
+ });
14761
+ const result = await response.json();
14762
+ console.log(JSON.stringify(result));
14763
+ if (!response.ok) process.exitCode = 1;
14764
+ }
14765
+ async function openProject(entry, target) {
14766
+ const child = spawn(process.execPath, [entry, "serve", target], { detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"] });
14767
+ await new Promise((resolve, reject) => {
14768
+ const timer = setTimeout(() => {
14769
+ child.kill();
14770
+ reject(new Error("Project server did not become ready within 15 seconds."));
14771
+ }, 15e3);
14772
+ child.once("error", (error) => {
14773
+ clearTimeout(timer);
14774
+ reject(error);
14775
+ });
14776
+ child.once("exit", (code) => {
14777
+ clearTimeout(timer);
14778
+ reject(new Error("Project server exited before readiness (" + code + "). Run emviz <project> in the foreground for diagnostics."));
14779
+ });
14780
+ child.once("message", (message) => {
14781
+ if (!message || typeof message !== "object" || !("url" in message) || !("token" in message)) return;
14782
+ clearTimeout(timer);
14783
+ console.log(JSON.stringify(message));
14784
+ child.disconnect();
14785
+ child.unref();
14786
+ resolve();
14787
+ });
14788
+ });
14789
+ }
14790
+
14004
14791
  // src/index.ts
14005
14792
  var args = process.argv.slice(2);
14006
14793
  var command = args[0];
14007
14794
  function resolveTarget(value) {
14008
- return path5.resolve(process.cwd(), value ?? ".");
14795
+ return path7.resolve(process.cwd(), value ?? ".");
14009
14796
  }
14010
14797
  function sendJson(res, value) {
14011
14798
  res.setHeader("content-type", "application/json; charset=utf-8");
@@ -14016,16 +14803,9 @@ function sendText(res, statusCode, body) {
14016
14803
  res.setHeader("content-type", "text/plain; charset=utf-8");
14017
14804
  res.end(body);
14018
14805
  }
14019
- function loadApiModel(targetDir) {
14020
- const project = loadEventModelProject(targetDir);
14021
- return {
14022
- ...project,
14023
- graphSidecar: readGraphSidecar(project.root)
14024
- };
14025
- }
14026
14806
  function isGitRef(value) {
14027
14807
  try {
14028
- execFileSync("git", ["rev-parse", "--verify", `${value}^{commit}`], {
14808
+ execFileSync3("git", ["rev-parse", "--verify", `${value}^{commit}`], {
14029
14809
  cwd: process.cwd(),
14030
14810
  stdio: "ignore"
14031
14811
  });
@@ -14034,35 +14814,16 @@ function isGitRef(value) {
14034
14814
  return false;
14035
14815
  }
14036
14816
  }
14037
- function materializeGitRef(ref) {
14038
- const tempRoot = fs5.mkdtempSync(path5.join(os.tmpdir(), "emviz-diff-"));
14039
- const files = execFileSync("git", ["ls-tree", "-r", "--name-only", ref, "--", ".event-modeling", "event-model"], {
14040
- cwd: process.cwd(),
14041
- encoding: "utf8"
14042
- }).split("\n").filter(Boolean);
14043
- if (files.length === 0) throw new Error(`Git ref "${ref}" does not contain .event-modeling or event-model files.`);
14044
- for (const file of files) {
14045
- const content = execFileSync("git", ["show", `${ref}:${file}`], {
14046
- cwd: process.cwd(),
14047
- encoding: "utf8",
14048
- maxBuffer: 20 * 1024 * 1024
14049
- });
14050
- const outputPath = path5.join(tempRoot, file);
14051
- fs5.mkdirSync(path5.dirname(outputPath), { recursive: true });
14052
- fs5.writeFileSync(outputPath, content);
14053
- }
14054
- return tempRoot;
14055
- }
14056
14817
  function loadDiffSource(value, fallback) {
14057
14818
  const raw = value ?? fallback;
14058
- const resolved = path5.resolve(process.cwd(), raw);
14059
- if (fs5.existsSync(resolved)) {
14060
- if (fs5.statSync(resolved).isFile()) {
14819
+ const resolved = path7.resolve(process.cwd(), raw);
14820
+ if (fs7.existsSync(resolved)) {
14821
+ if (fs7.statSync(resolved).isFile()) {
14061
14822
  throw new Error(`Diff source must be an event-modeling project directory, not a file: ${raw}`);
14062
14823
  }
14063
14824
  return {
14064
14825
  project: loadEventModelProject(resolved),
14065
- label: path5.relative(process.cwd(), resolved) || "."
14826
+ label: path7.relative(process.cwd(), resolved) || "."
14066
14827
  };
14067
14828
  }
14068
14829
  if (isGitRef(raw)) {
@@ -14114,7 +14875,7 @@ function loadDiffServerState(baseValue, targetValue) {
14114
14875
  };
14115
14876
  }
14116
14877
  function printSyncResult(result) {
14117
- console.log(`Wrote ${path5.relative(process.cwd(), result.path)}`);
14878
+ console.log(`Wrote ${path7.relative(process.cwd(), result.path)}`);
14118
14879
  console.log(`Added: ${result.added.length}`);
14119
14880
  console.log(`Preserved: ${result.preserved.length}`);
14120
14881
  console.log(`Stale: ${result.stale.length}`);
@@ -14124,12 +14885,6 @@ async function runSync(targetDir) {
14124
14885
  const result = writeGraphSidecar(project);
14125
14886
  printSyncResult(result);
14126
14887
  }
14127
- function syncMissingGraphSidecar(targetDir) {
14128
- const project = loadEventModelProject(targetDir);
14129
- if (readGraphSidecar(project.root)) return;
14130
- console.log("Missing .event-modeling/graph.json; running initial sync...");
14131
- printSyncResult(writeGraphSidecar(project));
14132
- }
14133
14888
  var contentTypes = {
14134
14889
  ".css": "text/css; charset=utf-8",
14135
14890
  ".html": "text/html; charset=utf-8",
@@ -14140,15 +14895,15 @@ var contentTypes = {
14140
14895
  };
14141
14896
  function safeResolve(root, requestPath) {
14142
14897
  const decodedPath = decodeURIComponent(requestPath);
14143
- const resolved = path5.resolve(root, `.${decodedPath}`);
14144
- const relative = path5.relative(root, resolved);
14145
- if (relative.startsWith("..") || path5.isAbsolute(relative)) return void 0;
14898
+ const resolved = path7.resolve(root, `.${decodedPath}`);
14899
+ const relative = path7.relative(root, resolved);
14900
+ if (relative.startsWith("..") || path7.isAbsolute(relative)) return void 0;
14146
14901
  return resolved;
14147
14902
  }
14148
14903
  function serveFile(res, filePath) {
14149
- const stream = fs5.createReadStream(filePath);
14904
+ const stream = fs7.createReadStream(filePath);
14150
14905
  stream.on("error", () => sendText(res, 500, "Failed to read file"));
14151
- res.setHeader("content-type", contentTypes[path5.extname(filePath)] ?? "application/octet-stream");
14906
+ res.setHeader("content-type", contentTypes[path7.extname(filePath)] ?? "application/octet-stream");
14152
14907
  stream.pipe(res);
14153
14908
  }
14154
14909
  function serveApp(req, res, appRoot) {
@@ -14159,7 +14914,7 @@ function serveApp(req, res, appRoot) {
14159
14914
  sendText(res, 403, "Forbidden");
14160
14915
  return;
14161
14916
  }
14162
- if (fs5.existsSync(filePath) && fs5.statSync(filePath).isFile()) {
14917
+ if (fs7.existsSync(filePath) && fs7.statSync(filePath).isFile()) {
14163
14918
  serveFile(res, filePath);
14164
14919
  return;
14165
14920
  }
@@ -14167,7 +14922,7 @@ function serveApp(req, res, appRoot) {
14167
14922
  sendText(res, 404, "Not found");
14168
14923
  return;
14169
14924
  }
14170
- serveFile(res, path5.join(appRoot, "index.html"));
14925
+ serveFile(res, path7.join(appRoot, "index.html"));
14171
14926
  }
14172
14927
  function listenWithFallback(server, port) {
14173
14928
  return new Promise((resolve, reject) => {
@@ -14188,44 +14943,92 @@ function listenWithFallback(server, port) {
14188
14943
  });
14189
14944
  }
14190
14945
  async function runServer(targetDir, diffState) {
14191
- if (targetDir) syncMissingGraphSidecar(targetDir);
14192
- const appRoot = path5.resolve(path5.dirname(fileURLToPath(import.meta.url)), "app");
14946
+ if (targetDir) {
14947
+ const initial = readSnapshot(targetDir);
14948
+ if (!initial.graphSidecar) {
14949
+ console.log("Missing .event-modeling/graph.json; running initial sync...");
14950
+ printSyncResult(writeGraphSidecar(initial.project));
14951
+ }
14952
+ }
14953
+ const appRoot = path7.resolve(path7.dirname(fileURLToPath(import.meta.url)), "app");
14954
+ const feedback = targetDir ? new FeedbackSession(targetDir) : void 0;
14955
+ let listeningPort = 0;
14193
14956
  const server = http.createServer((req, res) => {
14194
- const url = new URL(req.url ?? "/", "http://localhost");
14195
- if (diffState && url.pathname === "/api/model") {
14957
+ void respond(req, res).catch((error) => {
14958
+ if (!res.headersSent) sendText(res, 500, error instanceof Error ? error.message : String(error));
14959
+ else res.end();
14960
+ });
14961
+ });
14962
+ server.requestTimeout = 1e4;
14963
+ const close = () => {
14964
+ feedback?.stop();
14965
+ server.close();
14966
+ server.closeIdleConnections();
14967
+ const timer = setTimeout(() => server.closeAllConnections(), 1e3);
14968
+ timer.unref();
14969
+ };
14970
+ const respond = async (req, res) => {
14971
+ if (!trustedRequest(req, listeningPort)) {
14972
+ sendText(res, 403, "Forbidden Host or Origin");
14973
+ return;
14974
+ }
14975
+ res.setHeader("cache-control", "no-store");
14976
+ if (feedback && await handleFeedback(req, res, feedback, close)) return;
14977
+ const url2 = new URL(req.url ?? "/", "http://localhost");
14978
+ if (req.method !== "GET" && req.method !== "HEAD") {
14979
+ sendText(res, 405, "Method not allowed");
14980
+ return;
14981
+ }
14982
+ if (diffState && url2.pathname === "/api/model") {
14196
14983
  sendJson(res, diffState.model);
14197
14984
  return;
14198
14985
  }
14199
- if (diffState && url.pathname === "/api/diff") {
14986
+ if (diffState && url2.pathname === "/api/diff") {
14200
14987
  sendJson(res, diffState.diff);
14201
14988
  return;
14202
14989
  }
14203
- if (diffState && url.pathname === "/api/validation") {
14990
+ if (diffState && url2.pathname === "/api/validation") {
14204
14991
  sendJson(res, diffState.validation);
14205
14992
  return;
14206
14993
  }
14207
- if (targetDir && url.pathname === "/api/model") {
14994
+ if (targetDir && url2.pathname === "/api/model") {
14208
14995
  try {
14209
- sendJson(res, loadApiModel(targetDir));
14996
+ const snapshot = feedback.snapshot("current");
14997
+ if (snapshot.stale) res.statusCode = 422;
14998
+ sendJson(res, snapshot.project);
14210
14999
  } catch (error) {
14211
15000
  res.statusCode = 500;
14212
15001
  sendJson(res, { error: error instanceof Error ? error.message : String(error) });
14213
15002
  }
14214
15003
  return;
14215
15004
  }
14216
- if (targetDir && url.pathname === "/api/validation") {
15005
+ if (targetDir && url2.pathname === "/api/validation") {
14217
15006
  try {
14218
- const project = loadEventModelProject(targetDir);
14219
- sendJson(res, validateEventModelProject(project));
15007
+ const snapshot = feedback.snapshot("current");
15008
+ if (snapshot.stale) res.statusCode = 422;
15009
+ sendJson(res, snapshot.validation);
14220
15010
  } catch (error) {
14221
15011
  res.statusCode = 500;
14222
15012
  sendJson(res, { error: error instanceof Error ? error.message : String(error) });
14223
15013
  }
14224
15014
  return;
14225
15015
  }
15016
+ if (url2.pathname.startsWith("/api/")) {
15017
+ sendText(res, 404, "Not found");
15018
+ return;
15019
+ }
14226
15020
  serveApp(req, res, appRoot);
14227
- });
15021
+ };
14228
15022
  const port = await listenWithFallback(server, 5173);
15023
+ listeningPort = port;
15024
+ const url = `http://127.0.0.1:${port}/`;
15025
+ if (feedback) {
15026
+ const ready = { url, token: feedback.token, pid: process.pid, next_step: `Run emviz poll --url ${url} --token ${feedback.token} --agent <unique-agent-id> in your external agent.` };
15027
+ if (process.send) process.send(ready);
15028
+ else console.log(JSON.stringify(ready));
15029
+ }
15030
+ process.once("SIGTERM", close);
15031
+ process.once("SIGINT", close);
14229
15032
  console.log(` \u279C Local: http://localhost:${port}/`);
14230
15033
  if (diffState) {
14231
15034
  console.log(`Diff: ${diffState.diff.base.label} -> ${diffState.diff.target.label}`);
@@ -14234,6 +15037,19 @@ async function runServer(targetDir, diffState) {
14234
15037
  }
14235
15038
  }
14236
15039
  async function main() {
15040
+ if (command === "open") {
15041
+ if (args.length > 2) throw new Error("Usage: emviz open [project-dir]");
15042
+ await openProject(fileURLToPath(import.meta.url), resolveTarget(args[1]));
15043
+ return;
15044
+ }
15045
+ if (command === "serve") {
15046
+ await runServer(resolveTarget(args[1]));
15047
+ return;
15048
+ }
15049
+ if (["poll", "reply", "stop", "close"].includes(command)) {
15050
+ await runAgentCommand(command, args.slice(1));
15051
+ return;
15052
+ }
14237
15053
  if (command === "sync") {
14238
15054
  await runSync(resolveTarget(args[1]));
14239
15055
  return;
@@ -14251,6 +15067,10 @@ async function main() {
14251
15067
  }
14252
15068
  if (command === "--help" || command === "-h") {
14253
15069
  console.log("Usage: emviz [project-dir]");
15070
+ console.log(" emviz open [project-dir]");
15071
+ console.log(" emviz poll --url <url> --token <token> --agent <id>");
15072
+ console.log(" emviz reply <request-id> <text> --url <url> --token <token> --agent <id>");
15073
+ console.log(" emviz stop|close --url <url> --token <token>");
14254
15074
  console.log(" emviz sync [project-dir]");
14255
15075
  console.log(" emviz diff [base-ref-or-dir] [project-dir]");
14256
15076
  console.log(" emviz diff --from <base-ref-or-dir> --to <project-dir>");