emviz 0.4.0 → 0.5.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
@@ -389,7 +389,7 @@ var require_utils = __commonJS({
389
389
  if (node.type === "range") node.type = "text";
390
390
  return acc;
391
391
  }, []);
392
- exports.flatten = (...args2) => {
392
+ exports.flatten = (...args) => {
393
393
  const result = [];
394
394
  const flat = (arr) => {
395
395
  for (let i = 0; i < arr.length; i++) {
@@ -404,7 +404,7 @@ var require_utils = __commonJS({
404
404
  }
405
405
  return result;
406
406
  };
407
- flat(args2);
407
+ flat(args);
408
408
  return result;
409
409
  };
410
410
  }
@@ -756,8 +756,8 @@ var require_fill_range = __commonJS({
756
756
  }
757
757
  return toRegexRange(start, end, options);
758
758
  };
759
- var rangeError = (...args2) => {
760
- return new RangeError("Invalid range arguments: " + util.inspect(...args2));
759
+ var rangeError = (...args) => {
760
+ return new RangeError("Invalid range arguments: " + util.inspect(...args));
761
761
  };
762
762
  var invalidRange = (start, end, options) => {
763
763
  if (options.strictRanges === true) throw rangeError([start, end]);
@@ -895,10 +895,10 @@ var require_compile = __commonJS({
895
895
  return node.value;
896
896
  }
897
897
  if (node.nodes && node.ranges > 0) {
898
- const args2 = utils.reduce(node.nodes);
899
- const range = fill(...args2, { ...options, wrap: false, toRegex: true, strictZeros: true });
898
+ const args = utils.reduce(node.nodes);
899
+ const range = fill(...args, { ...options, wrap: false, toRegex: true, strictZeros: true });
900
900
  if (range.length !== 0) {
901
- return args2.length > 1 && range.length > 1 ? `(${range})` : range;
901
+ return args.length > 1 && range.length > 1 ? `(${range})` : range;
902
902
  }
903
903
  }
904
904
  if (node.nodes) {
@@ -962,11 +962,11 @@ var require_expand = __commonJS({
962
962
  return;
963
963
  }
964
964
  if (node.nodes && node.ranges > 0) {
965
- const args2 = utils.reduce(node.nodes);
966
- if (utils.exceedsLimit(...args2, options.step, rangeLimit)) {
965
+ const args = utils.reduce(node.nodes);
966
+ if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
967
967
  throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");
968
968
  }
969
- let range = fill(...args2, options);
969
+ let range = fill(...args, options);
970
970
  if (range.length === 0) {
971
971
  range = stringify(node, options);
972
972
  }
@@ -2015,16 +2015,16 @@ var require_parse2 = __commonJS({
2015
2015
  REGEX_SPECIAL_CHARS_BACKREF,
2016
2016
  REPLACEMENTS
2017
2017
  } = constants;
2018
- var expandRange = (args2, options) => {
2018
+ var expandRange = (args, options) => {
2019
2019
  if (typeof options.expandRange === "function") {
2020
- return options.expandRange(...args2, options);
2020
+ return options.expandRange(...args, options);
2021
2021
  }
2022
- args2.sort();
2023
- const value = `[${args2.join("-")}]`;
2022
+ args.sort();
2023
+ const value = `[${args.join("-")}]`;
2024
2024
  try {
2025
2025
  new RegExp(value);
2026
2026
  } catch (ex) {
2027
- return args2.map((v) => utils.escapeRegex(v)).join("..");
2027
+ return args.map((v) => utils.escapeRegex(v)).join("..");
2028
2028
  }
2029
2029
  return value;
2030
2030
  };
@@ -3287,8 +3287,8 @@ var require_micromatch = __commonJS({
3287
3287
  return match.slice(1).map((v) => v === void 0 ? "" : v);
3288
3288
  }
3289
3289
  };
3290
- micromatch.makeRe = (...args2) => picomatch.makeRe(...args2);
3291
- micromatch.scan = (...args2) => picomatch.scan(...args2);
3290
+ micromatch.makeRe = (...args) => picomatch.makeRe(...args);
3291
+ micromatch.scan = (...args) => picomatch.scan(...args);
3292
3292
  micromatch.parse = (patterns, options) => {
3293
3293
  let res = [];
3294
3294
  for (let pattern of [].concat(patterns || [])) {
@@ -3489,11 +3489,11 @@ var require_merge2 = __commonJS({
3489
3489
  module.exports = merge2;
3490
3490
  function merge2() {
3491
3491
  const streamsQueue = [];
3492
- const args2 = slice.call(arguments);
3492
+ const args = slice.call(arguments);
3493
3493
  let merging = false;
3494
- let options = args2[args2.length - 1];
3494
+ let options = args[args.length - 1];
3495
3495
  if (options && !Array.isArray(options) && options.pipe == null) {
3496
- args2.pop();
3496
+ args.pop();
3497
3497
  } else {
3498
3498
  options = {};
3499
3499
  }
@@ -3574,8 +3574,8 @@ var require_merge2 = __commonJS({
3574
3574
  mergedStream.on("unpipe", function(stream) {
3575
3575
  stream.emit("merge2UnpipeEnd");
3576
3576
  });
3577
- if (args2.length) {
3578
- addStream.apply(null, args2);
3577
+ if (args.length) {
3578
+ addStream.apply(null, args);
3579
3579
  }
3580
3580
  return mergedStream;
3581
3581
  }
@@ -13108,6 +13108,7 @@ var require_dist = __commonJS({
13108
13108
  // src/index.ts
13109
13109
  import fs7 from "node:fs";
13110
13110
  import http from "node:http";
13111
+ import { randomUUID as randomUUID2 } from "node:crypto";
13111
13112
  import path7 from "node:path";
13112
13113
  import { execFileSync as execFileSync3 } from "node:child_process";
13113
13114
  import { fileURLToPath } from "node:url";
@@ -13249,9 +13250,9 @@ function graphIds(project) {
13249
13250
  for (const slice of project.slices) {
13250
13251
  register(sliceId(slice.path), [slice.path]);
13251
13252
  register(screenId(slice.path), [slice.path]);
13252
- slice.commands.forEach((command2, index) => {
13253
- register(commandId(command2.name), localIdentity(slice.path, slice.commands, index));
13254
- for (const name of command2.produces)
13253
+ slice.commands.forEach((command, index) => {
13254
+ register(commandId(command.name), localIdentity(slice.path, slice.commands, index));
13255
+ for (const name of command.produces)
13255
13256
  register(eventId(name), [name]);
13256
13257
  });
13257
13258
  slice.queries.forEach((query, index) => {
@@ -13318,12 +13319,12 @@ function buildGraph(project) {
13318
13319
  for (const name of query.fromEvents)
13319
13320
  connect("event-query", eventNodeId(name), currentId, name);
13320
13321
  });
13321
- slice.commands.forEach((command2, index) => {
13322
- const currentId = id(commandId(command2.name), localIdentity(slice.path, slice.commands, index));
13323
- nodes.push({ ...shared, id: currentId, type: "command", label: command2.name, sourceName: command2.name, fields: command2.fields });
13324
- if (slice.screen.executes.includes(command2.name))
13322
+ slice.commands.forEach((command, index) => {
13323
+ const currentId = id(commandId(command.name), localIdentity(slice.path, slice.commands, index));
13324
+ nodes.push({ ...shared, id: currentId, type: "command", label: command.name, sourceName: command.name, fields: command.fields });
13325
+ if (slice.screen.executes.includes(command.name))
13325
13326
  connect("screen-command", currentScreenId, currentId);
13326
- for (const name of command2.produces)
13327
+ for (const name of command.produces)
13327
13328
  connect("command-event", currentId, eventNodeId(name), name);
13328
13329
  });
13329
13330
  slice.gwt.forEach((scenario, index) => {
@@ -13802,7 +13803,7 @@ function cloneProject(project) {
13802
13803
  slices: project.slices.map((slice) => ({
13803
13804
  ...slice,
13804
13805
  screen: { ...slice.screen, actors: [...slice.screen.actors], reads: [...slice.screen.reads], executes: [...slice.screen.executes] },
13805
- commands: slice.commands.map((command2) => ({ ...command2, produces: [...command2.produces] })),
13806
+ commands: slice.commands.map((command) => ({ ...command, produces: [...command.produces] })),
13806
13807
  queries: slice.queries.map((query) => ({ ...query, fromEvents: [...query.fromEvents] })),
13807
13808
  gwt: slice.gwt.map((scenario) => ({
13808
13809
  ...scenario,
@@ -13859,7 +13860,7 @@ function mergeRemovedModelContainers(merged, base) {
13859
13860
  merged.slices.push({
13860
13861
  ...slice,
13861
13862
  screen: { ...slice.screen, actors: [...slice.screen.actors], reads: [...slice.screen.reads], executes: [...slice.screen.executes] },
13862
- commands: slice.commands.map((command2) => ({ ...command2, produces: [...command2.produces] })),
13863
+ commands: slice.commands.map((command) => ({ ...command, produces: [...command.produces] })),
13863
13864
  queries: slice.queries.map((query) => ({ ...query, fromEvents: [...query.fromEvents] })),
13864
13865
  gwt: slice.gwt.map((scenario) => ({
13865
13866
  ...scenario,
@@ -14172,7 +14173,7 @@ function validateEventModelProject(project, snapshot) {
14172
14173
  }
14173
14174
  }
14174
14175
  for (const slice of project.slices) {
14175
- const commandNames = slice.commands.map((command2) => command2.name);
14176
+ const commandNames = slice.commands.map((command) => command.name);
14176
14177
  const queryNames = slice.queries.map((query) => query.name);
14177
14178
  for (const name of duplicates(commandNames)) {
14178
14179
  findings.push(finding("error", "L9", `Command "${name}" is duplicated within slice "${slice.title}".`, slice.path));
@@ -14205,15 +14206,15 @@ function validateEventModelProject(project, snapshot) {
14205
14206
  if (slice.commands.length > 0 && slice.gwt.length === 0) {
14206
14207
  findings.push(finding("warning", "M1", `Command slice "${slice.title}" has no GWT scenarios.`, slice.path));
14207
14208
  }
14208
- for (const command2 of slice.commands) {
14209
- if (!command2.fields?.trim()) {
14210
- findings.push(finding("warning", "L6", `Command "${command2.name}" has no fields block.`, slice.path));
14209
+ for (const command of slice.commands) {
14210
+ if (!command.fields?.trim()) {
14211
+ findings.push(finding("warning", "L6", `Command "${command.name}" has no fields block.`, slice.path));
14211
14212
  }
14212
- for (const eventName of command2.produces) {
14213
+ for (const eventName of command.produces) {
14213
14214
  if (!eventNames.has(eventName)) {
14214
- findings.push(finding("error", "G1", `Command "${command2.name}" produces unregistered event "${eventName}".`, slice.path));
14215
+ findings.push(finding("error", "G1", `Command "${command.name}" produces unregistered event "${eventName}".`, slice.path));
14215
14216
  }
14216
- produced.set(eventName, [...produced.get(eventName) ?? [], `${slice.title}.${command2.name}`]);
14217
+ produced.set(eventName, [...produced.get(eventName) ?? [], `${slice.title}.${command.name}`]);
14217
14218
  }
14218
14219
  }
14219
14220
  for (const query of slice.queries) {
@@ -14259,7 +14260,7 @@ function validateEventModelProject(project, snapshot) {
14259
14260
  findings.push(finding("error", "G3", `Event "${eventName}" is read by ${consumers.join(", ")} but no command produces it.`));
14260
14261
  }
14261
14262
  }
14262
- for (const name of duplicates(project.slices.flatMap((slice) => slice.commands.map((command2) => command2.name)))) {
14263
+ for (const name of duplicates(project.slices.flatMap((slice) => slice.commands.map((command) => command.name)))) {
14263
14264
  findings.push(finding("warning", "M5", `Command name "${name}" is used in multiple slices; command names should be globally unique.`));
14264
14265
  }
14265
14266
  for (const name of duplicates(project.slices.flatMap((slice) => slice.queries.map((query) => query.name)))) {
@@ -14295,8 +14296,66 @@ function validateEventModelProject(project, snapshot) {
14295
14296
  // src/feedback.ts
14296
14297
  import fs6 from "node:fs";
14297
14298
  import path6 from "node:path";
14298
- import { randomUUID, createHash, timingSafeEqual } from "node:crypto";
14299
+ import { randomUUID, createHash } from "node:crypto";
14299
14300
  import { execFileSync as execFileSync2 } from "node:child_process";
14301
+
14302
+ // src/network.ts
14303
+ import { isIP } from "node:net";
14304
+ import { timingSafeEqual } from "node:crypto";
14305
+ function parseHost(value = "127.0.0.1") {
14306
+ const host = value.startsWith("[") && value.endsWith("]") ? value.slice(1, -1) : value;
14307
+ const family = isIP(host);
14308
+ if (!family || value.startsWith("[") && family !== 6 || host.includes("%")) throw new Error("--host must be a concrete IPv4 or IPv6 address. DNS names and wildcard addresses are not supported.");
14309
+ const normalized = family === 6 ? new URL("http://[" + host + "]/").hostname.slice(1, -1) : host;
14310
+ if (normalized === "0.0.0.0" || normalized === "::" || normalized === "::ffff:0:0") {
14311
+ throw new Error("--host must select one interface address. Wildcard addresses are not supported.");
14312
+ }
14313
+ return normalized;
14314
+ }
14315
+ function parseHostArgs(values) {
14316
+ let host = "127.0.0.1";
14317
+ let provided = false;
14318
+ const args = [];
14319
+ for (let index = 0; index < values.length; index++) {
14320
+ const value = values[index];
14321
+ if (value !== "--host" && !value.startsWith("--host=")) {
14322
+ args.push(value);
14323
+ continue;
14324
+ }
14325
+ if (provided) throw new Error("--host may be specified only once.");
14326
+ const address = value === "--host" ? values[++index] : value.slice("--host=".length);
14327
+ if (!address || address.startsWith("--")) throw new Error("--host requires an IPv4 or IPv6 address.");
14328
+ host = parseHost(address);
14329
+ provided = true;
14330
+ }
14331
+ return { host, args, provided };
14332
+ }
14333
+ function isLoopbackHost(host) {
14334
+ return host === "::1" || host.startsWith("127.");
14335
+ }
14336
+ function serverOrigin(host, port) {
14337
+ return "http://" + (host.includes(":") ? "[" + host + "]" : host) + ":" + port;
14338
+ }
14339
+ function trustedRequest(req, port, host = "127.0.0.1") {
14340
+ const authority = new URL(serverOrigin(host, port)).host;
14341
+ const allowed = host === "127.0.0.1" ? [authority, "localhost:" + port] : [authority];
14342
+ const requestHost = req.headers.host;
14343
+ if (!requestHost || !allowed.includes(requestHost)) return false;
14344
+ const origin = req.headers.origin;
14345
+ return origin === void 0 || origin === "http://" + requestHost;
14346
+ }
14347
+ function validToken(req, expected) {
14348
+ const token = req.headers["x-emviz-token"];
14349
+ if (typeof token !== "string") return false;
14350
+ const actual = Buffer.from(token);
14351
+ const wanted = Buffer.from(expected);
14352
+ return actual.length === wanted.length && timingSafeEqual(actual, wanted);
14353
+ }
14354
+ function apiRequestAuthorized(req, pathname, host, token) {
14355
+ return isLoopbackHost(host) || pathname !== "/api" && !pathname.startsWith("/api/") || validToken(req, token);
14356
+ }
14357
+
14358
+ // src/feedback.ts
14300
14359
  var FeedbackError = class extends Error {
14301
14360
  constructor(status, message) {
14302
14361
  super(message);
@@ -14410,7 +14469,7 @@ function readSnapshot(target) {
14410
14469
  function gitBaseline(snapshot) {
14411
14470
  const root = snapshot.project.root;
14412
14471
  try {
14413
- const git = (args2) => execFileSync2("git", ["-C", root, ...args2], { encoding: "utf8", maxBuffer: 8 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
14472
+ const git = (args) => execFileSync2("git", ["-C", root, ...args], { encoding: "utf8", maxBuffer: 8 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
14414
14473
  const commit = git(["rev-parse", "--verify", "HEAD^{commit}"]).trim();
14415
14474
  const repoRoot = git(["rev-parse", "--show-toplevel"]).trim();
14416
14475
  const prefix = path6.relative(fs6.realpathSync(repoRoot), fs6.realpathSync(root)).split(path6.sep).join("/");
@@ -14451,6 +14510,67 @@ function textField(value, name, max) {
14451
14510
  if (typeof value !== "string" || !value.trim() || value.length > max) throw new FeedbackError(400, name + " must contain 1 to " + max + " characters.");
14452
14511
  return value;
14453
14512
  }
14513
+ function parseBatch(body) {
14514
+ const clientBatchId = textField(body.clientBatchId, "clientBatchId", 100);
14515
+ if (!Array.isArray(body.items) || body.items.length < 1 || body.items.length > 20) {
14516
+ throw new FeedbackError(400, "A batch must contain 1 to 20 items.");
14517
+ }
14518
+ const ids = /* @__PURE__ */ new Set();
14519
+ let messageLength = 0;
14520
+ const items = body.items.map((value) => {
14521
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new FeedbackError(400, "Expected a feedback item.");
14522
+ const item = value;
14523
+ const parsed = {
14524
+ id: textField(item.id, "item id", 100),
14525
+ nodeId: textField(item.nodeId, "nodeId", 500),
14526
+ reference: textField(item.reference, "reference", 1e3),
14527
+ revision: textField(item.revision, "revision", 100),
14528
+ message: textField(item.message, "message", 4e3)
14529
+ };
14530
+ if (ids.has(parsed.id)) throw new FeedbackError(400, "Batch item IDs must be unique.");
14531
+ ids.add(parsed.id);
14532
+ messageLength += parsed.message.length;
14533
+ return parsed;
14534
+ });
14535
+ if (messageLength > 16e3) throw new FeedbackError(413, "Batch messages exceed 16000 characters.");
14536
+ return { clientBatchId, items };
14537
+ }
14538
+ function nodeIdentity(node) {
14539
+ return JSON.stringify([node.type, node.sourcePath, node.sourceName, node.label, node.sliceTitle]);
14540
+ }
14541
+ function uniqueNodeIds(project) {
14542
+ const ids = /* @__PURE__ */ new Map();
14543
+ for (const node of project.nodes) {
14544
+ const key = nodeIdentity(node);
14545
+ ids.set(key, ids.has(key) ? void 0 : node.id);
14546
+ }
14547
+ return ids;
14548
+ }
14549
+ function captureNode(snapshot, nodeId) {
14550
+ const node = snapshot.project.nodes.find((item) => item.id === nodeId);
14551
+ if (!node) throw new FeedbackError(409, "This element is no longer in the current model.");
14552
+ const reference = "em://" + (snapshot.graphSidecar?.model.id ?? "event_model") + "/" + nodeId;
14553
+ const yaml = node.sourcePath && snapshot.files.get(node.sourcePath) || node.raw || node.fields || node.description || node.label;
14554
+ if (yaml.length > 64e3) throw new FeedbackError(413, "Selected source exceeds 64000 characters.");
14555
+ const related = snapshot.project.edges.filter((edge) => edge.source === nodeId || edge.target === nodeId);
14556
+ 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) })) });
14557
+ if (context.length > 128e3) throw new FeedbackError(413, "Connected context exceeds 128000 characters.");
14558
+ return { reference, sourcePath: node.sourcePath, yaml, context };
14559
+ }
14560
+ function batchRequest(input, receipt) {
14561
+ const first = input.items[0];
14562
+ const message = "Batch feedback for " + input.items.length + " nodes. Address every item below before replying once.\n\n" + input.items.map((item, index) => index + 1 + ". " + item.reference + "\n" + item.message).join("\n\n");
14563
+ return {
14564
+ id: receipt.id,
14565
+ clientRequestId: input.clientBatchId,
14566
+ clientBatchId: input.clientBatchId,
14567
+ items: input.items,
14568
+ message,
14569
+ nodeId: first.nodeId,
14570
+ reference: first.reference,
14571
+ createdAt: receipt.createdAt
14572
+ };
14573
+ }
14454
14574
  var FeedbackSession = class {
14455
14575
  constructor(target) {
14456
14576
  this.target = target;
@@ -14464,6 +14584,7 @@ var FeedbackSession = class {
14464
14584
  baseline;
14465
14585
  state = { status: "idle" };
14466
14586
  history = [];
14587
+ batchReceipts = /* @__PURE__ */ new Map();
14467
14588
  lastSeen;
14468
14589
  error;
14469
14590
  waiter;
@@ -14501,10 +14622,16 @@ var FeedbackSession = class {
14501
14622
  project = result.project;
14502
14623
  diff = result.diff;
14503
14624
  }
14625
+ const currentIds = uniqueNodeIds(this.current.project);
14626
+ const currentNodeIds = Object.fromEntries(project.nodes.flatMap((node) => {
14627
+ const id = currentIds.get(nodeIdentity(node));
14628
+ return id === void 0 || diff?.nodeStatus[node.id] === "removed" ? [] : [[node.id, id]];
14629
+ }));
14504
14630
  return {
14505
14631
  sessionId: this.id,
14506
14632
  token: this.token,
14507
14633
  revision: this.current.revision,
14634
+ currentNodeIds,
14508
14635
  project: { ...project, graphSidecar: displayed.graphSidecar },
14509
14636
  validation: displayed.validation,
14510
14637
  diff,
@@ -14524,6 +14651,7 @@ var FeedbackSession = class {
14524
14651
  const message = textField(body.message, "message", 4e3);
14525
14652
  const nodeId = textField(body.nodeId, "nodeId", 500);
14526
14653
  const revision = textField(body.revision, "revision", 100);
14654
+ if (this.batchReceipts.has(clientRequestId)) throw new FeedbackError(409, "Request ID already belongs to a batch.");
14527
14655
  const active = "context" in this.state ? this.state.context?.request : void 0;
14528
14656
  const known = active?.clientRequestId === clientRequestId ? active : this.history.find((item) => item.clientRequestId === clientRequestId);
14529
14657
  if (known?.clientRequestId === clientRequestId) {
@@ -14534,22 +14662,51 @@ var FeedbackSession = class {
14534
14662
  if (this.state.status === "working" || this.state.status === "queued") throw new FeedbackError(409, "Finish or stop the active request first.");
14535
14663
  const snapshot = this.refresh();
14536
14664
  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.");
14665
+ const captured = captureNode(snapshot, nodeId);
14539
14666
  const request = {
14540
14667
  id: randomUUID(),
14541
14668
  clientRequestId,
14542
14669
  message,
14543
14670
  nodeId,
14544
14671
  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 } };
14672
+ reference: captured.reference
14673
+ };
14674
+ this.state = { status: "queued", context: { request, revision, ...captured } };
14675
+ this.waiter?.();
14676
+ return request;
14677
+ }
14678
+ submitBatch(body) {
14679
+ const input = parseBatch(body);
14680
+ const fingerprint = createHash("sha256").update(JSON.stringify(input)).digest("hex");
14681
+ const active = "context" in this.state ? this.state.context?.request : void 0;
14682
+ const receipt = this.batchReceipts.get(input.clientBatchId);
14683
+ if (receipt) {
14684
+ if (receipt.fingerprint !== fingerprint) throw new FeedbackError(409, "Batch ID already used with different content.");
14685
+ return active?.id === receipt.id ? active : this.history.find((item) => item.id === receipt.id) ?? batchRequest(input, receipt);
14686
+ }
14687
+ if (active?.clientRequestId === input.clientBatchId || this.history.some((item) => item.clientRequestId === input.clientBatchId)) {
14688
+ throw new FeedbackError(409, "Batch ID already belongs to a request.");
14689
+ }
14690
+ if (this.state.status === "stopped") throw new FeedbackError(409, "Feedback is stopped.");
14691
+ if (this.state.status === "working" || this.state.status === "queued") throw new FeedbackError(409, "Finish or stop the active request first.");
14692
+ if (this.batchReceipts.size >= 1e3) throw new FeedbackError(429, "This session has accepted 1000 batches. Restart the project server before sending another batch.");
14693
+ const snapshot = this.refresh();
14694
+ const currentIds = uniqueNodeIds(snapshot.project);
14695
+ const items = input.items.map((item) => {
14696
+ if (item.revision !== snapshot.revision) throw new FeedbackError(409, "Model changed. Review and queue each element again.");
14697
+ const captured = captureNode(snapshot, item.nodeId);
14698
+ if (item.reference !== captured.reference) throw new FeedbackError(409, "An item reference does not match its current node.");
14699
+ const node = snapshot.project.nodes.find((candidate) => candidate.id === item.nodeId);
14700
+ if (currentIds.get(nodeIdentity(node)) !== node.id) throw new FeedbackError(409, "An item is ambiguous. Select a uniquely named current node.");
14701
+ return { ...item, ...captured };
14702
+ });
14703
+ const context = JSON.stringify({ kind: "batch", revision: snapshot.revision, items });
14704
+ if (Buffer.byteLength(context) > 1024 * 1024) throw new FeedbackError(413, "Batch captured context exceeds 1 MiB.");
14705
+ const accepted = { fingerprint, id: randomUUID(), createdAt: Date.now() };
14706
+ const request = batchRequest(input, accepted);
14707
+ const yaml = items.map((item, index) => "# Item " + (index + 1) + " " + item.reference + "\n" + item.yaml).join("\n\n");
14708
+ this.batchReceipts.set(input.clientBatchId, accepted);
14709
+ this.state = { status: "queued", context: { request, items, revision: snapshot.revision, yaml, context } };
14553
14710
  this.waiter?.();
14554
14711
  return request;
14555
14712
  }
@@ -14581,7 +14738,7 @@ var FeedbackSession = class {
14581
14738
  if (this.state.status === "queued") {
14582
14739
  const before = this.refresh();
14583
14740
  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." });
14741
+ this.archive({ ...this.state.context.request, reply: this.state.context.items ? "Model changed before the agent started. Review every item and send a new batch." : "Model changed before the agent started. Select the element and send again." });
14585
14742
  this.state = { status: "idle" };
14586
14743
  throw new FeedbackError(409, "Model changed before claim. Request cancelled.");
14587
14744
  }
@@ -14589,7 +14746,7 @@ var FeedbackSession = class {
14589
14746
  this.state = { status: "working", context: this.state.context, agentId, before };
14590
14747
  }
14591
14748
  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." };
14749
+ return { status: "request", request: { ...this.state.context.request, ...this.state.context.items ? { items: this.state.context.items } : {}, 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: (this.state.context.items ? "Apply all feedback items as one batch using their captured node references and context. Re-read current files before each edit without retargeting an item. Reply once after the whole batch. " : "") + "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
14750
  }
14594
14751
  return { status: "timeout", next_step: "Run emviz poll again with the same --url, --token, and --agent. Wait in the foreground." };
14595
14752
  } finally {
@@ -14626,21 +14783,7 @@ var FeedbackSession = class {
14626
14783
  this.state = { status: "idle" };
14627
14784
  }
14628
14785
  };
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) {
14786
+ async function readJson(req, maxBytes = 32768) {
14644
14787
  if (req.headers["content-type"]?.split(";")[0] !== "application/json") throw new FeedbackError(415, "Use application/json.");
14645
14788
  const content = await new Promise((resolve, reject) => {
14646
14789
  let size = 0;
@@ -14649,10 +14792,10 @@ async function readJson(req) {
14649
14792
  req.on("data", (chunk) => {
14650
14793
  if (failed) return;
14651
14794
  size += chunk.length;
14652
- if (size > 32768) {
14795
+ if (size > maxBytes) {
14653
14796
  failed = true;
14654
14797
  parts.length = 0;
14655
- reject(new FeedbackError(413, "Request exceeds 32 KiB."));
14798
+ reject(new FeedbackError(413, "Request exceeds " + maxBytes / 1024 + " KiB."));
14656
14799
  } else parts.push(chunk);
14657
14800
  });
14658
14801
  req.once("end", () => {
@@ -14693,11 +14836,14 @@ async function handleFeedback(req, res, session, close) {
14693
14836
  return true;
14694
14837
  }
14695
14838
  if (req.method !== "POST") throw new FeedbackError(405, "Method not allowed.");
14696
- const body = await readJson(req);
14839
+ const body = await readJson(req, url.pathname === "/api/feedback/batch" ? 128 * 1024 : 32768);
14697
14840
  switch (url.pathname) {
14698
14841
  case "/api/feedback/request":
14699
14842
  send(session.submit(body));
14700
14843
  break;
14844
+ case "/api/feedback/batch":
14845
+ send(session.submitBatch(body));
14846
+ break;
14701
14847
  case "/api/feedback/reply":
14702
14848
  send({ request: session.reply(body), next_step: "Run emviz poll with the same connection options." });
14703
14849
  break;
@@ -14739,22 +14885,23 @@ function parseConnection(values) {
14739
14885
  } else positional.push(value);
14740
14886
  }
14741
14887
  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.");
14888
+ if (url.protocol !== "http:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) throw new Error("--url must be an HTTP origin without credentials, path, query, or fragment. Use url, not viewerUrl.");
14889
+ if (url.hostname !== "localhost") parseHost(url.hostname);
14743
14890
  const token = options.get("--token");
14744
14891
  if (!token) throw new Error("--token is required. Use the token printed by emviz open.");
14745
14892
  return { url, token, agent: options.get("--agent"), positional };
14746
14893
  }
14747
- async function runAgentCommand(command2, values) {
14894
+ async function runAgentCommand(command, values) {
14748
14895
  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.");
14896
+ if ((command === "poll" || command === "reply") && !connection.agent) throw new Error("--agent is required. Reuse one unique ID throughout the session.");
14897
+ const route = command === "poll" ? "/api/feedback/poll?agent=" + encodeURIComponent(connection.agent) : "/api/feedback/" + command;
14898
+ const body = command === "reply" ? { id: connection.positional[0], reply: connection.positional[1], agent: connection.agent } : {};
14899
+ if (command === "reply" && connection.positional.length !== 2) throw new Error("Usage: emviz reply <request-id> <text> --url <url> --token <token> --agent <id>");
14900
+ if (command !== "reply" && connection.positional.length) throw new Error("Unexpected positional argument.");
14754
14901
  const response = await fetch(new URL(route, connection.url), {
14755
- method: command2 === "poll" ? "GET" : "POST",
14902
+ method: command === "poll" ? "GET" : "POST",
14756
14903
  headers: { "X-Emviz-Token": connection.token, "Content-Type": "application/json" },
14757
- body: command2 === "poll" ? void 0 : JSON.stringify(body),
14904
+ body: command === "poll" ? void 0 : JSON.stringify(body),
14758
14905
  signal: AbortSignal.timeout(3e4),
14759
14906
  redirect: "error"
14760
14907
  });
@@ -14762,8 +14909,9 @@ async function runAgentCommand(command2, values) {
14762
14909
  console.log(JSON.stringify(result));
14763
14910
  if (!response.ok) process.exitCode = 1;
14764
14911
  }
14765
- async function openProject(entry, target) {
14766
- const child = spawn(process.execPath, [entry, "serve", target], { detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"] });
14912
+ async function openProject(entry, target, host = "127.0.0.1") {
14913
+ const address = parseHost(host);
14914
+ const child = spawn(process.execPath, [entry, "serve", target, "--host", address], { detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"] });
14767
14915
  await new Promise((resolve, reject) => {
14768
14916
  const timer = setTimeout(() => {
14769
14917
  child.kill();
@@ -14789,8 +14937,6 @@ async function openProject(entry, target) {
14789
14937
  }
14790
14938
 
14791
14939
  // src/index.ts
14792
- var args = process.argv.slice(2);
14793
- var command = args[0];
14794
14940
  function resolveTarget(value) {
14795
14941
  return path7.resolve(process.cwd(), value ?? ".");
14796
14942
  }
@@ -14924,7 +15070,7 @@ function serveApp(req, res, appRoot) {
14924
15070
  }
14925
15071
  serveFile(res, path7.join(appRoot, "index.html"));
14926
15072
  }
14927
- function listenWithFallback(server, port) {
15073
+ function listenWithFallback(server, port, host) {
14928
15074
  return new Promise((resolve, reject) => {
14929
15075
  const tryListen = (nextPort) => {
14930
15076
  server.once("error", (error) => {
@@ -14935,14 +15081,14 @@ function listenWithFallback(server, port) {
14935
15081
  }
14936
15082
  reject(error);
14937
15083
  });
14938
- server.listen(nextPort, "127.0.0.1", () => {
15084
+ server.listen(nextPort, host, () => {
14939
15085
  resolve(server.address().port);
14940
15086
  });
14941
15087
  };
14942
15088
  tryListen(port);
14943
15089
  });
14944
15090
  }
14945
- async function runServer(targetDir, diffState) {
15091
+ async function runServer(host, targetDir, diffState) {
14946
15092
  if (targetDir) {
14947
15093
  const initial = readSnapshot(targetDir);
14948
15094
  if (!initial.graphSidecar) {
@@ -14952,6 +15098,7 @@ async function runServer(targetDir, diffState) {
14952
15098
  }
14953
15099
  const appRoot = path7.resolve(path7.dirname(fileURLToPath(import.meta.url)), "app");
14954
15100
  const feedback = targetDir ? new FeedbackSession(targetDir) : void 0;
15101
+ const token = feedback?.token ?? randomUUID2();
14955
15102
  let listeningPort = 0;
14956
15103
  const server = http.createServer((req, res) => {
14957
15104
  void respond(req, res).catch((error) => {
@@ -14968,13 +15115,19 @@ async function runServer(targetDir, diffState) {
14968
15115
  timer.unref();
14969
15116
  };
14970
15117
  const respond = async (req, res) => {
14971
- if (!trustedRequest(req, listeningPort)) {
15118
+ res.setHeader("cache-control", "no-store");
15119
+ res.setHeader("referrer-policy", "no-referrer");
15120
+ if (!trustedRequest(req, listeningPort, host)) {
14972
15121
  sendText(res, 403, "Forbidden Host or Origin");
14973
15122
  return;
14974
15123
  }
14975
- res.setHeader("cache-control", "no-store");
15124
+ const url2 = new URL(req.url ?? "/", serverOrigin(host, listeningPort));
15125
+ if (!apiRequestAuthorized(req, url2.pathname, host, token)) {
15126
+ res.statusCode = 403;
15127
+ sendJson(res, { error: "Invalid session token. Open the complete viewerUrl printed by emviz in this browser." });
15128
+ return;
15129
+ }
14976
15130
  if (feedback && await handleFeedback(req, res, feedback, close)) return;
14977
- const url2 = new URL(req.url ?? "/", "http://localhost");
14978
15131
  if (req.method !== "GET" && req.method !== "HEAD") {
14979
15132
  sendText(res, 405, "Method not allowed");
14980
15133
  return;
@@ -15019,17 +15172,19 @@ async function runServer(targetDir, diffState) {
15019
15172
  }
15020
15173
  serveApp(req, res, appRoot);
15021
15174
  };
15022
- const port = await listenWithFallback(server, 5173);
15175
+ const port = await listenWithFallback(server, 5173, host);
15023
15176
  listeningPort = port;
15024
- const url = `http://127.0.0.1:${port}/`;
15177
+ const url = serverOrigin(host, port) + "/";
15178
+ const viewerUrl = isLoopbackHost(host) ? url : url + "#token=" + encodeURIComponent(token);
15025
15179
  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.` };
15180
+ const ready = { url, viewerUrl, token, pid: process.pid, next_step: `Run emviz poll --url ${url} --token ${token} --agent <unique-agent-id> in your external agent.` };
15027
15181
  if (process.send) process.send(ready);
15028
15182
  else console.log(JSON.stringify(ready));
15029
15183
  }
15030
15184
  process.once("SIGTERM", close);
15031
15185
  process.once("SIGINT", close);
15032
- console.log(` \u279C Local: http://localhost:${port}/`);
15186
+ console.log(` \u279C ${isLoopbackHost(host) ? "Local" : "Remote"}: ${viewerUrl}`);
15187
+ if (!isLoopbackHost(host)) console.warn("Remote access requires the complete viewerUrl. Treat that link and the token as secrets. HTTP is unencrypted; use a trusted private network such as Tailscale.");
15033
15188
  if (diffState) {
15034
15189
  console.log(`Diff: ${diffState.diff.base.label} -> ${diffState.diff.target.label}`);
15035
15190
  } else {
@@ -15037,17 +15192,22 @@ async function runServer(targetDir, diffState) {
15037
15192
  }
15038
15193
  }
15039
15194
  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]));
15195
+ const rawArgs = process.argv.slice(2);
15196
+ if (["poll", "reply", "stop", "close"].includes(rawArgs[0])) {
15197
+ await runAgentCommand(rawArgs[0], rawArgs.slice(1));
15043
15198
  return;
15044
15199
  }
15045
- if (command === "serve") {
15046
- await runServer(resolveTarget(args[1]));
15200
+ const { host, args, provided } = parseHostArgs(rawArgs);
15201
+ const command = args[0];
15202
+ if (provided && ["sync", "init", "poll", "reply", "stop", "close"].includes(command)) throw new Error("--host is only supported by server commands.");
15203
+ if (command === "open") {
15204
+ if (args.length > 2) throw new Error("Usage: emviz open [project-dir] [--host <ip>]");
15205
+ await openProject(fileURLToPath(import.meta.url), resolveTarget(args[1]), host);
15047
15206
  return;
15048
15207
  }
15049
- if (["poll", "reply", "stop", "close"].includes(command)) {
15050
- await runAgentCommand(command, args.slice(1));
15208
+ if (command === "serve") {
15209
+ if (args.length > 2) throw new Error("Usage: emviz serve [project-dir] [--host <ip>]");
15210
+ await runServer(host, resolveTarget(args[1]));
15051
15211
  return;
15052
15212
  }
15053
15213
  if (command === "sync") {
@@ -15062,22 +15222,26 @@ async function main() {
15062
15222
  if (command === "diff") {
15063
15223
  const diffArgs = parseDiffArgs(args.slice(1));
15064
15224
  const diffState = loadDiffServerState(diffArgs.base, diffArgs.target);
15065
- await runServer(void 0, diffState);
15225
+ await runServer(host, void 0, diffState);
15066
15226
  return;
15067
15227
  }
15068
15228
  if (command === "--help" || command === "-h") {
15069
- console.log("Usage: emviz [project-dir]");
15070
- console.log(" emviz open [project-dir]");
15229
+ console.log("Usage: emviz [project-dir] [--host <ip>]");
15230
+ console.log(" emviz open [project-dir] [--host <ip>]");
15231
+ console.log(" emviz serve [project-dir] [--host <ip>]");
15071
15232
  console.log(" emviz poll --url <url> --token <token> --agent <id>");
15072
15233
  console.log(" emviz reply <request-id> <text> --url <url> --token <token> --agent <id>");
15073
15234
  console.log(" emviz stop|close --url <url> --token <token>");
15074
15235
  console.log(" emviz sync [project-dir]");
15075
- console.log(" emviz diff [base-ref-or-dir] [project-dir]");
15076
- console.log(" emviz diff --from <base-ref-or-dir> --to <project-dir>");
15236
+ console.log(" emviz diff [base-ref-or-dir] [project-dir] [--host <ip>]");
15237
+ console.log(" emviz diff --from <base-ref-or-dir> --to <project-dir> [--host <ip>]");
15077
15238
  console.log(" emviz init [project-dir] (deprecated alias for sync)");
15239
+ console.log("Default host: 127.0.0.1. Use a concrete IPv4 or IPv6 interface address. DNS names and wildcard binds are rejected.");
15240
+ console.log("Remote browser access uses the printed viewerUrl. Agent commands use url and --token.");
15078
15241
  return;
15079
15242
  }
15080
- await runServer(command ? resolveTarget(command) : void 0);
15243
+ if (args.length > 1 || command?.startsWith("-")) throw new Error("Usage: emviz [project-dir] [--host <ip>]");
15244
+ await runServer(host, command ? resolveTarget(command) : void 0);
15081
15245
  }
15082
15246
  main().catch((error) => {
15083
15247
  console.error(error instanceof Error ? error.message : error);