meshy-node 0.3.3 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/main.cjs CHANGED
@@ -6629,8 +6629,8 @@ var require_node2 = __commonJS({
6629
6629
  }
6630
6630
  break;
6631
6631
  case "FILE":
6632
- var fs21 = require("fs");
6633
- stream2 = new fs21.SyncWriteStream(fd2, { autoClose: false });
6632
+ var fs22 = require("fs");
6633
+ stream2 = new fs22.SyncWriteStream(fd2, { autoClose: false });
6634
6634
  stream2._type = "fs";
6635
6635
  break;
6636
6636
  case "PIPE":
@@ -10057,13 +10057,13 @@ var require_extend_node = __commonJS({
10057
10057
  return length;
10058
10058
  };
10059
10059
  if (iconv.supportsStreams) {
10060
- var Readable = require("stream").Readable;
10061
- original.ReadableSetEncoding = Readable.prototype.setEncoding;
10062
- Readable.prototype.setEncoding = function setEncoding(enc, options) {
10060
+ var Readable3 = require("stream").Readable;
10061
+ original.ReadableSetEncoding = Readable3.prototype.setEncoding;
10062
+ Readable3.prototype.setEncoding = function setEncoding(enc, options) {
10063
10063
  this._readableState.decoder = iconv.getDecoder(enc, options);
10064
10064
  this._readableState.encoding = enc;
10065
10065
  };
10066
- Readable.prototype.collect = iconv._collect;
10066
+ Readable3.prototype.collect = iconv._collect;
10067
10067
  }
10068
10068
  };
10069
10069
  iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() {
@@ -10080,9 +10080,9 @@ var require_extend_node = __commonJS({
10080
10080
  Buffer2.prototype.toString = original.BufferToString;
10081
10081
  Buffer2.prototype.write = original.BufferWrite;
10082
10082
  if (iconv.supportsStreams) {
10083
- var Readable = require("stream").Readable;
10084
- Readable.prototype.setEncoding = original.ReadableSetEncoding;
10085
- delete Readable.prototype.collect;
10083
+ var Readable3 = require("stream").Readable;
10084
+ Readable3.prototype.setEncoding = original.ReadableSetEncoding;
10085
+ delete Readable3.prototype.collect;
10086
10086
  }
10087
10087
  original = void 0;
10088
10088
  };
@@ -19420,11 +19420,11 @@ var require_mime_types = __commonJS({
19420
19420
  }
19421
19421
  return exts[0];
19422
19422
  }
19423
- function lookup(path22) {
19424
- if (!path22 || typeof path22 !== "string") {
19423
+ function lookup(path23) {
19424
+ if (!path23 || typeof path23 !== "string") {
19425
19425
  return false;
19426
19426
  }
19427
- var extension2 = extname3("x." + path22).toLowerCase().substr(1);
19427
+ var extension2 = extname3("x." + path23).toLowerCase().substr(1);
19428
19428
  if (!extension2) {
19429
19429
  return false;
19430
19430
  }
@@ -22624,8 +22624,8 @@ var require_escape_html = __commonJS({
22624
22624
  "../../node_modules/.pnpm/escape-html@1.0.3/node_modules/escape-html/index.js"(exports2, module2) {
22625
22625
  "use strict";
22626
22626
  var matchHtmlRegExp = /["'&<>]/;
22627
- module2.exports = escapeHtml;
22628
- function escapeHtml(string) {
22627
+ module2.exports = escapeHtml2;
22628
+ function escapeHtml2(string) {
22629
22629
  var str = "" + string;
22630
22630
  var match = matchHtmlRegExp.exec(str);
22631
22631
  if (!match) {
@@ -22756,7 +22756,7 @@ var require_finalhandler = __commonJS({
22756
22756
  "use strict";
22757
22757
  var debug = require_src2()("finalhandler");
22758
22758
  var encodeUrl = require_encodeurl();
22759
- var escapeHtml = require_escape_html();
22759
+ var escapeHtml2 = require_escape_html();
22760
22760
  var onFinished = require_on_finished();
22761
22761
  var parseUrl = require_parseurl();
22762
22762
  var statuses = require_statuses();
@@ -22768,7 +22768,7 @@ var require_finalhandler = __commonJS({
22768
22768
  };
22769
22769
  var isFinished = onFinished.isFinished;
22770
22770
  function createHtmlDocument(message) {
22771
- var body = escapeHtml(message).replace(NEWLINE_REGEXP, "<br>").replace(DOUBLE_SPACE_REGEXP, " &nbsp;");
22771
+ var body = escapeHtml2(message).replace(NEWLINE_REGEXP, "<br>").replace(DOUBLE_SPACE_REGEXP, " &nbsp;");
22772
22772
  return '<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<title>Error</title>\n</head>\n<body>\n<pre>' + body + "</pre>\n</body>\n</html>\n";
22773
22773
  }
22774
22774
  module2.exports = finalhandler;
@@ -22942,7 +22942,7 @@ var require_path_to_regexp = __commonJS({
22942
22942
  "use strict";
22943
22943
  module2.exports = pathToRegexp;
22944
22944
  var MATCHING_GROUP_REGEXP = /\\.|\((?:\?<(.*?)>)?(?!\?)/g;
22945
- function pathToRegexp(path22, keys, options) {
22945
+ function pathToRegexp(path23, keys, options) {
22946
22946
  options = options || {};
22947
22947
  keys = keys || [];
22948
22948
  var strict = options.strict;
@@ -22956,8 +22956,8 @@ var require_path_to_regexp = __commonJS({
22956
22956
  var pos = 0;
22957
22957
  var backtrack = "";
22958
22958
  var m;
22959
- if (path22 instanceof RegExp) {
22960
- while (m = MATCHING_GROUP_REGEXP.exec(path22.source)) {
22959
+ if (path23 instanceof RegExp) {
22960
+ while (m = MATCHING_GROUP_REGEXP.exec(path23.source)) {
22961
22961
  if (m[0][0] === "\\") continue;
22962
22962
  keys.push({
22963
22963
  name: m[1] || name2++,
@@ -22965,18 +22965,18 @@ var require_path_to_regexp = __commonJS({
22965
22965
  offset: m.index
22966
22966
  });
22967
22967
  }
22968
- return path22;
22968
+ return path23;
22969
22969
  }
22970
- if (Array.isArray(path22)) {
22971
- path22 = path22.map(function(value) {
22970
+ if (Array.isArray(path23)) {
22971
+ path23 = path23.map(function(value) {
22972
22972
  return pathToRegexp(value, keys, options).source;
22973
22973
  });
22974
- return new RegExp(path22.join("|"), flags);
22974
+ return new RegExp(path23.join("|"), flags);
22975
22975
  }
22976
- if (typeof path22 !== "string") {
22976
+ if (typeof path23 !== "string") {
22977
22977
  throw new TypeError("path must be a string, array of strings, or regular expression");
22978
22978
  }
22979
- path22 = path22.replace(
22979
+ path23 = path23.replace(
22980
22980
  /\\.|(\/)?(\.)?:(\w+)(\(.*?\))?(\*)?(\?)?|[.*]|\/\(/g,
22981
22981
  function(match, slash, format, key, capture, star, optional, offset) {
22982
22982
  if (match[0] === "\\") {
@@ -22993,7 +22993,7 @@ var require_path_to_regexp = __commonJS({
22993
22993
  if (slash || format) {
22994
22994
  backtrack = "";
22995
22995
  } else {
22996
- backtrack += path22.slice(pos, offset);
22996
+ backtrack += path23.slice(pos, offset);
22997
22997
  }
22998
22998
  pos = offset + match.length;
22999
22999
  if (match === "*") {
@@ -23023,7 +23023,7 @@ var require_path_to_regexp = __commonJS({
23023
23023
  return result;
23024
23024
  }
23025
23025
  );
23026
- while (m = MATCHING_GROUP_REGEXP.exec(path22)) {
23026
+ while (m = MATCHING_GROUP_REGEXP.exec(path23)) {
23027
23027
  if (m[0][0] === "\\") continue;
23028
23028
  if (keysOffset + i === keys.length || keys[keysOffset + i].offset > m.index) {
23029
23029
  keys.splice(keysOffset + i, 0, {
@@ -23035,13 +23035,13 @@ var require_path_to_regexp = __commonJS({
23035
23035
  }
23036
23036
  i++;
23037
23037
  }
23038
- path22 += strict ? "" : path22[path22.length - 1] === "/" ? "?" : "/?";
23038
+ path23 += strict ? "" : path23[path23.length - 1] === "/" ? "?" : "/?";
23039
23039
  if (end) {
23040
- path22 += "$";
23041
- } else if (path22[path22.length - 1] !== "/") {
23042
- path22 += lookahead ? "(?=/|$)" : "(?:/|$)";
23040
+ path23 += "$";
23041
+ } else if (path23[path23.length - 1] !== "/") {
23042
+ path23 += lookahead ? "(?=/|$)" : "(?:/|$)";
23043
23043
  }
23044
- return new RegExp("^" + path22, flags);
23044
+ return new RegExp("^" + path23, flags);
23045
23045
  }
23046
23046
  }
23047
23047
  });
@@ -23054,19 +23054,19 @@ var require_layer = __commonJS({
23054
23054
  var debug = require_src2()("express:router:layer");
23055
23055
  var hasOwnProperty = Object.prototype.hasOwnProperty;
23056
23056
  module2.exports = Layer;
23057
- function Layer(path22, options, fn) {
23057
+ function Layer(path23, options, fn) {
23058
23058
  if (!(this instanceof Layer)) {
23059
- return new Layer(path22, options, fn);
23059
+ return new Layer(path23, options, fn);
23060
23060
  }
23061
- debug("new %o", path22);
23061
+ debug("new %o", path23);
23062
23062
  var opts = options || {};
23063
23063
  this.handle = fn;
23064
23064
  this.name = fn.name || "<anonymous>";
23065
23065
  this.params = void 0;
23066
23066
  this.path = void 0;
23067
- this.regexp = pathRegexp(path22, this.keys = [], opts);
23068
- this.regexp.fast_star = path22 === "*";
23069
- this.regexp.fast_slash = path22 === "/" && opts.end === false;
23067
+ this.regexp = pathRegexp(path23, this.keys = [], opts);
23068
+ this.regexp.fast_star = path23 === "*";
23069
+ this.regexp.fast_slash = path23 === "/" && opts.end === false;
23070
23070
  }
23071
23071
  Layer.prototype.handle_error = function handle_error(error, req, res, next) {
23072
23072
  var fn = this.handle;
@@ -23090,20 +23090,20 @@ var require_layer = __commonJS({
23090
23090
  next(err);
23091
23091
  }
23092
23092
  };
23093
- Layer.prototype.match = function match(path22) {
23093
+ Layer.prototype.match = function match(path23) {
23094
23094
  var match2;
23095
- if (path22 != null) {
23095
+ if (path23 != null) {
23096
23096
  if (this.regexp.fast_slash) {
23097
23097
  this.params = {};
23098
23098
  this.path = "";
23099
23099
  return true;
23100
23100
  }
23101
23101
  if (this.regexp.fast_star) {
23102
- this.params = { "0": decode_param(path22) };
23103
- this.path = path22;
23102
+ this.params = { "0": decode_param(path23) };
23103
+ this.path = path23;
23104
23104
  return true;
23105
23105
  }
23106
- match2 = this.regexp.exec(path22);
23106
+ match2 = this.regexp.exec(path23);
23107
23107
  }
23108
23108
  if (!match2) {
23109
23109
  this.params = void 0;
@@ -23196,10 +23196,10 @@ var require_route = __commonJS({
23196
23196
  var slice = Array.prototype.slice;
23197
23197
  var toString = Object.prototype.toString;
23198
23198
  module2.exports = Route;
23199
- function Route(path22) {
23200
- this.path = path22;
23199
+ function Route(path23) {
23200
+ this.path = path23;
23201
23201
  this.stack = [];
23202
- debug("new %o", path22);
23202
+ debug("new %o", path23);
23203
23203
  this.methods = {};
23204
23204
  }
23205
23205
  Route.prototype._handles_method = function _handles_method(method) {
@@ -23412,8 +23412,8 @@ var require_router = __commonJS({
23412
23412
  if (++sync > 100) {
23413
23413
  return setImmediate(next, err);
23414
23414
  }
23415
- var path22 = getPathname(req);
23416
- if (path22 == null) {
23415
+ var path23 = getPathname(req);
23416
+ if (path23 == null) {
23417
23417
  return done(layerError);
23418
23418
  }
23419
23419
  var layer;
@@ -23421,7 +23421,7 @@ var require_router = __commonJS({
23421
23421
  var route;
23422
23422
  while (match !== true && idx < stack.length) {
23423
23423
  layer = stack[idx++];
23424
- match = matchLayer(layer, path22);
23424
+ match = matchLayer(layer, path23);
23425
23425
  route = layer.route;
23426
23426
  if (typeof match !== "boolean") {
23427
23427
  layerError = layerError || match;
@@ -23459,18 +23459,18 @@ var require_router = __commonJS({
23459
23459
  } else if (route) {
23460
23460
  layer.handle_request(req, res, next);
23461
23461
  } else {
23462
- trim_prefix(layer, layerError, layerPath, path22);
23462
+ trim_prefix(layer, layerError, layerPath, path23);
23463
23463
  }
23464
23464
  sync = 0;
23465
23465
  });
23466
23466
  }
23467
- function trim_prefix(layer, layerError, layerPath, path22) {
23467
+ function trim_prefix(layer, layerError, layerPath, path23) {
23468
23468
  if (layerPath.length !== 0) {
23469
- if (layerPath !== path22.slice(0, layerPath.length)) {
23469
+ if (layerPath !== path23.slice(0, layerPath.length)) {
23470
23470
  next(layerError);
23471
23471
  return;
23472
23472
  }
23473
- var c = path22[layerPath.length];
23473
+ var c = path23[layerPath.length];
23474
23474
  if (c && c !== "/" && c !== ".") return next(layerError);
23475
23475
  debug("trim prefix (%s) from url %s", layerPath, req.url);
23476
23476
  removed = layerPath;
@@ -23548,7 +23548,7 @@ var require_router = __commonJS({
23548
23548
  };
23549
23549
  proto.use = function use(fn) {
23550
23550
  var offset = 0;
23551
- var path22 = "/";
23551
+ var path23 = "/";
23552
23552
  if (typeof fn !== "function") {
23553
23553
  var arg = fn;
23554
23554
  while (Array.isArray(arg) && arg.length !== 0) {
@@ -23556,7 +23556,7 @@ var require_router = __commonJS({
23556
23556
  }
23557
23557
  if (typeof arg !== "function") {
23558
23558
  offset = 1;
23559
- path22 = fn;
23559
+ path23 = fn;
23560
23560
  }
23561
23561
  }
23562
23562
  var callbacks = flatten(slice.call(arguments, offset));
@@ -23568,8 +23568,8 @@ var require_router = __commonJS({
23568
23568
  if (typeof fn !== "function") {
23569
23569
  throw new TypeError("Router.use() requires a middleware function but got a " + gettype(fn));
23570
23570
  }
23571
- debug("use %o %s", path22, fn.name || "<anonymous>");
23572
- var layer = new Layer(path22, {
23571
+ debug("use %o %s", path23, fn.name || "<anonymous>");
23572
+ var layer = new Layer(path23, {
23573
23573
  sensitive: this.caseSensitive,
23574
23574
  strict: false,
23575
23575
  end: false
@@ -23579,9 +23579,9 @@ var require_router = __commonJS({
23579
23579
  }
23580
23580
  return this;
23581
23581
  };
23582
- proto.route = function route(path22) {
23583
- var route2 = new Route(path22);
23584
- var layer = new Layer(path22, {
23582
+ proto.route = function route(path23) {
23583
+ var route2 = new Route(path23);
23584
+ var layer = new Layer(path23, {
23585
23585
  sensitive: this.caseSensitive,
23586
23586
  strict: this.strict,
23587
23587
  end: true
@@ -23591,8 +23591,8 @@ var require_router = __commonJS({
23591
23591
  return route2;
23592
23592
  };
23593
23593
  methods.concat("all").forEach(function(method) {
23594
- proto[method] = function(path22) {
23595
- var route = this.route(path22);
23594
+ proto[method] = function(path23) {
23595
+ var route = this.route(path23);
23596
23596
  route[method].apply(route, slice.call(arguments, 1));
23597
23597
  return this;
23598
23598
  };
@@ -23628,9 +23628,9 @@ var require_router = __commonJS({
23628
23628
  }
23629
23629
  return toString.call(obj).replace(objectRegExp, "$1");
23630
23630
  }
23631
- function matchLayer(layer, path22) {
23631
+ function matchLayer(layer, path23) {
23632
23632
  try {
23633
- return layer.match(path22);
23633
+ return layer.match(path23);
23634
23634
  } catch (err) {
23635
23635
  return err;
23636
23636
  }
@@ -23748,13 +23748,13 @@ var require_view = __commonJS({
23748
23748
  "../../node_modules/.pnpm/express@4.22.1/node_modules/express/lib/view.js"(exports2, module2) {
23749
23749
  "use strict";
23750
23750
  var debug = require_src2()("express:view");
23751
- var path22 = require("path");
23752
- var fs21 = require("fs");
23753
- var dirname7 = path22.dirname;
23754
- var basename4 = path22.basename;
23755
- var extname3 = path22.extname;
23756
- var join17 = path22.join;
23757
- var resolve14 = path22.resolve;
23751
+ var path23 = require("path");
23752
+ var fs22 = require("fs");
23753
+ var dirname7 = path23.dirname;
23754
+ var basename5 = path23.basename;
23755
+ var extname3 = path23.extname;
23756
+ var join18 = path23.join;
23757
+ var resolve14 = path23.resolve;
23758
23758
  module2.exports = View;
23759
23759
  function View(name2, options) {
23760
23760
  var opts = options || {};
@@ -23783,17 +23783,17 @@ var require_view = __commonJS({
23783
23783
  this.path = this.lookup(fileName);
23784
23784
  }
23785
23785
  View.prototype.lookup = function lookup(name2) {
23786
- var path23;
23786
+ var path24;
23787
23787
  var roots = [].concat(this.root);
23788
23788
  debug('lookup "%s"', name2);
23789
- for (var i = 0; i < roots.length && !path23; i++) {
23789
+ for (var i = 0; i < roots.length && !path24; i++) {
23790
23790
  var root = roots[i];
23791
23791
  var loc = resolve14(root, name2);
23792
23792
  var dir = dirname7(loc);
23793
- var file = basename4(loc);
23794
- path23 = this.resolve(dir, file);
23793
+ var file = basename5(loc);
23794
+ path24 = this.resolve(dir, file);
23795
23795
  }
23796
- return path23;
23796
+ return path24;
23797
23797
  };
23798
23798
  View.prototype.render = function render(options, callback) {
23799
23799
  debug('render "%s"', this.path);
@@ -23801,21 +23801,21 @@ var require_view = __commonJS({
23801
23801
  };
23802
23802
  View.prototype.resolve = function resolve15(dir, file) {
23803
23803
  var ext = this.ext;
23804
- var path23 = join17(dir, file);
23805
- var stat = tryStat(path23);
23804
+ var path24 = join18(dir, file);
23805
+ var stat = tryStat(path24);
23806
23806
  if (stat && stat.isFile()) {
23807
- return path23;
23807
+ return path24;
23808
23808
  }
23809
- path23 = join17(dir, basename4(file, ext), "index" + ext);
23810
- stat = tryStat(path23);
23809
+ path24 = join18(dir, basename5(file, ext), "index" + ext);
23810
+ stat = tryStat(path24);
23811
23811
  if (stat && stat.isFile()) {
23812
- return path23;
23812
+ return path24;
23813
23813
  }
23814
23814
  };
23815
- function tryStat(path23) {
23816
- debug('stat "%s"', path23);
23815
+ function tryStat(path24) {
23816
+ debug('stat "%s"', path24);
23817
23817
  try {
23818
- return fs21.statSync(path23);
23818
+ return fs22.statSync(path24);
23819
23819
  } catch (e) {
23820
23820
  return void 0;
23821
23821
  }
@@ -23829,7 +23829,7 @@ var require_content_disposition = __commonJS({
23829
23829
  "use strict";
23830
23830
  module2.exports = contentDisposition;
23831
23831
  module2.exports.parse = parse;
23832
- var basename4 = require("path").basename;
23832
+ var basename5 = require("path").basename;
23833
23833
  var Buffer2 = require_safe_buffer().Buffer;
23834
23834
  var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g;
23835
23835
  var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/;
@@ -23865,9 +23865,9 @@ var require_content_disposition = __commonJS({
23865
23865
  if (typeof fallback === "string" && NON_LATIN1_REGEXP.test(fallback)) {
23866
23866
  throw new TypeError("fallback must be ISO-8859-1 string");
23867
23867
  }
23868
- var name2 = basename4(filename);
23868
+ var name2 = basename5(filename);
23869
23869
  var isQuotedString = TEXT_REGEXP.test(name2);
23870
- var fallbackName = typeof fallback !== "string" ? fallback && getlatin1(name2) : basename4(fallback);
23870
+ var fallbackName = typeof fallback !== "string" ? fallback && getlatin1(name2) : basename5(fallback);
23871
23871
  var hasFallback = typeof fallbackName === "string" && fallbackName !== name2;
23872
23872
  if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name2)) {
23873
23873
  params["filename*"] = name2;
@@ -24112,8 +24112,8 @@ var require_types = __commonJS({
24112
24112
  var require_mime = __commonJS({
24113
24113
  "../../node_modules/.pnpm/mime@1.6.0/node_modules/mime/mime.js"(exports2, module2) {
24114
24114
  "use strict";
24115
- var path22 = require("path");
24116
- var fs21 = require("fs");
24115
+ var path23 = require("path");
24116
+ var fs22 = require("fs");
24117
24117
  function Mime() {
24118
24118
  this.types = /* @__PURE__ */ Object.create(null);
24119
24119
  this.extensions = /* @__PURE__ */ Object.create(null);
@@ -24134,7 +24134,7 @@ var require_mime = __commonJS({
24134
24134
  };
24135
24135
  Mime.prototype.load = function(file) {
24136
24136
  this._loading = file;
24137
- var map = {}, content = fs21.readFileSync(file, "ascii"), lines = content.split(/[\r\n]+/);
24137
+ var map = {}, content = fs22.readFileSync(file, "ascii"), lines = content.split(/[\r\n]+/);
24138
24138
  lines.forEach(function(line) {
24139
24139
  var fields = line.replace(/\s*#.*|^\s*|\s*$/g, "").split(/\s+/);
24140
24140
  map[fields.shift()] = fields;
@@ -24142,8 +24142,8 @@ var require_mime = __commonJS({
24142
24142
  this.define(map);
24143
24143
  this._loading = null;
24144
24144
  };
24145
- Mime.prototype.lookup = function(path23, fallback) {
24146
- var ext = path23.replace(/^.*[\.\/\\]/, "").toLowerCase();
24145
+ Mime.prototype.lookup = function(path24, fallback) {
24146
+ var ext = path24.replace(/^.*[\.\/\\]/, "").toLowerCase();
24147
24147
  return this.types[ext] || fallback || this.default_type;
24148
24148
  };
24149
24149
  Mime.prototype.extension = function(mimeType) {
@@ -24253,36 +24253,36 @@ var require_send = __commonJS({
24253
24253
  var deprecate = require_depd()("send");
24254
24254
  var destroy2 = require_destroy();
24255
24255
  var encodeUrl = require_encodeurl();
24256
- var escapeHtml = require_escape_html();
24256
+ var escapeHtml2 = require_escape_html();
24257
24257
  var etag = require_etag();
24258
24258
  var fresh = require_fresh();
24259
- var fs21 = require("fs");
24259
+ var fs22 = require("fs");
24260
24260
  var mime = require_mime();
24261
24261
  var ms = require_ms();
24262
24262
  var onFinished = require_on_finished();
24263
24263
  var parseRange = require_range_parser();
24264
- var path22 = require("path");
24264
+ var path23 = require("path");
24265
24265
  var statuses = require_statuses();
24266
24266
  var Stream = require("stream");
24267
24267
  var util3 = require("util");
24268
- var extname3 = path22.extname;
24269
- var join17 = path22.join;
24270
- var normalize = path22.normalize;
24271
- var resolve14 = path22.resolve;
24272
- var sep4 = path22.sep;
24268
+ var extname3 = path23.extname;
24269
+ var join18 = path23.join;
24270
+ var normalize = path23.normalize;
24271
+ var resolve14 = path23.resolve;
24272
+ var sep4 = path23.sep;
24273
24273
  var BYTES_RANGE_REGEXP = /^ *bytes=/;
24274
24274
  var MAX_MAXAGE = 60 * 60 * 24 * 365 * 1e3;
24275
24275
  var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
24276
24276
  module2.exports = send;
24277
24277
  module2.exports.mime = mime;
24278
- function send(req, path23, options) {
24279
- return new SendStream(req, path23, options);
24278
+ function send(req, path24, options) {
24279
+ return new SendStream(req, path24, options);
24280
24280
  }
24281
- function SendStream(req, path23, options) {
24281
+ function SendStream(req, path24, options) {
24282
24282
  Stream.call(this);
24283
24283
  var opts = options || {};
24284
24284
  this.options = opts;
24285
- this.path = path23;
24285
+ this.path = path24;
24286
24286
  this.req = req;
24287
24287
  this._acceptRanges = opts.acceptRanges !== void 0 ? Boolean(opts.acceptRanges) : true;
24288
24288
  this._cacheControl = opts.cacheControl !== void 0 ? Boolean(opts.cacheControl) : true;
@@ -24328,8 +24328,8 @@ var require_send = __commonJS({
24328
24328
  this._index = index2;
24329
24329
  return this;
24330
24330
  }, "send.index: pass index as option");
24331
- SendStream.prototype.root = function root(path23) {
24332
- this._root = resolve14(String(path23));
24331
+ SendStream.prototype.root = function root(path24) {
24332
+ this._root = resolve14(String(path24));
24333
24333
  debug("root %s", this._root);
24334
24334
  return this;
24335
24335
  };
@@ -24353,7 +24353,7 @@ var require_send = __commonJS({
24353
24353
  }
24354
24354
  var res = this.res;
24355
24355
  var msg = statuses.message[status] || String(status);
24356
- var doc = createHtmlDocument("Error", escapeHtml(msg));
24356
+ var doc = createHtmlDocument("Error", escapeHtml2(msg));
24357
24357
  clearHeaders(res);
24358
24358
  if (err && err.headers) {
24359
24359
  setHeaders(res, err.headers);
@@ -24442,10 +24442,10 @@ var require_send = __commonJS({
24442
24442
  var lastModified = this.res.getHeader("Last-Modified");
24443
24443
  return parseHttpDate(lastModified) <= parseHttpDate(ifRange);
24444
24444
  };
24445
- SendStream.prototype.redirect = function redirect(path23) {
24445
+ SendStream.prototype.redirect = function redirect(path24) {
24446
24446
  var res = this.res;
24447
24447
  if (hasListeners(this, "directory")) {
24448
- this.emit("directory", res, path23);
24448
+ this.emit("directory", res, path24);
24449
24449
  return;
24450
24450
  }
24451
24451
  if (this.hasTrailingSlash()) {
@@ -24453,7 +24453,7 @@ var require_send = __commonJS({
24453
24453
  return;
24454
24454
  }
24455
24455
  var loc = encodeUrl(collapseLeadingSlashes(this.path + "/"));
24456
- var doc = createHtmlDocument("Redirecting", "Redirecting to " + escapeHtml(loc));
24456
+ var doc = createHtmlDocument("Redirecting", "Redirecting to " + escapeHtml2(loc));
24457
24457
  res.statusCode = 301;
24458
24458
  res.setHeader("Content-Type", "text/html; charset=UTF-8");
24459
24459
  res.setHeader("Content-Length", Buffer.byteLength(doc));
@@ -24465,42 +24465,42 @@ var require_send = __commonJS({
24465
24465
  SendStream.prototype.pipe = function pipe(res) {
24466
24466
  var root = this._root;
24467
24467
  this.res = res;
24468
- var path23 = decode(this.path);
24469
- if (path23 === -1) {
24468
+ var path24 = decode(this.path);
24469
+ if (path24 === -1) {
24470
24470
  this.error(400);
24471
24471
  return res;
24472
24472
  }
24473
- if (~path23.indexOf("\0")) {
24473
+ if (~path24.indexOf("\0")) {
24474
24474
  this.error(400);
24475
24475
  return res;
24476
24476
  }
24477
24477
  var parts;
24478
24478
  if (root !== null) {
24479
- if (path23) {
24480
- path23 = normalize("." + sep4 + path23);
24479
+ if (path24) {
24480
+ path24 = normalize("." + sep4 + path24);
24481
24481
  }
24482
- if (UP_PATH_REGEXP.test(path23)) {
24483
- debug('malicious path "%s"', path23);
24482
+ if (UP_PATH_REGEXP.test(path24)) {
24483
+ debug('malicious path "%s"', path24);
24484
24484
  this.error(403);
24485
24485
  return res;
24486
24486
  }
24487
- parts = path23.split(sep4);
24488
- path23 = normalize(join17(root, path23));
24487
+ parts = path24.split(sep4);
24488
+ path24 = normalize(join18(root, path24));
24489
24489
  } else {
24490
- if (UP_PATH_REGEXP.test(path23)) {
24491
- debug('malicious path "%s"', path23);
24490
+ if (UP_PATH_REGEXP.test(path24)) {
24491
+ debug('malicious path "%s"', path24);
24492
24492
  this.error(403);
24493
24493
  return res;
24494
24494
  }
24495
- parts = normalize(path23).split(sep4);
24496
- path23 = resolve14(path23);
24495
+ parts = normalize(path24).split(sep4);
24496
+ path24 = resolve14(path24);
24497
24497
  }
24498
24498
  if (containsDotFile(parts)) {
24499
24499
  var access = this._dotfiles;
24500
24500
  if (access === void 0) {
24501
24501
  access = parts[parts.length - 1][0] === "." ? this._hidden ? "allow" : "ignore" : "allow";
24502
24502
  }
24503
- debug('%s dotfile "%s"', access, path23);
24503
+ debug('%s dotfile "%s"', access, path24);
24504
24504
  switch (access) {
24505
24505
  case "allow":
24506
24506
  break;
@@ -24514,13 +24514,13 @@ var require_send = __commonJS({
24514
24514
  }
24515
24515
  }
24516
24516
  if (this._index.length && this.hasTrailingSlash()) {
24517
- this.sendIndex(path23);
24517
+ this.sendIndex(path24);
24518
24518
  return res;
24519
24519
  }
24520
- this.sendFile(path23);
24520
+ this.sendFile(path24);
24521
24521
  return res;
24522
24522
  };
24523
- SendStream.prototype.send = function send2(path23, stat) {
24523
+ SendStream.prototype.send = function send2(path24, stat) {
24524
24524
  var len = stat.size;
24525
24525
  var options = this.options;
24526
24526
  var opts = {};
@@ -24532,9 +24532,9 @@ var require_send = __commonJS({
24532
24532
  this.headersAlreadySent();
24533
24533
  return;
24534
24534
  }
24535
- debug('pipe "%s"', path23);
24536
- this.setHeader(path23, stat);
24537
- this.type(path23);
24535
+ debug('pipe "%s"', path24);
24536
+ this.setHeader(path24, stat);
24537
+ this.type(path24);
24538
24538
  if (this.isConditionalGET()) {
24539
24539
  if (this.isPreconditionFailure()) {
24540
24540
  this.error(412);
@@ -24583,28 +24583,28 @@ var require_send = __commonJS({
24583
24583
  res.end();
24584
24584
  return;
24585
24585
  }
24586
- this.stream(path23, opts);
24586
+ this.stream(path24, opts);
24587
24587
  };
24588
- SendStream.prototype.sendFile = function sendFile(path23) {
24588
+ SendStream.prototype.sendFile = function sendFile(path24) {
24589
24589
  var i = 0;
24590
24590
  var self2 = this;
24591
- debug('stat "%s"', path23);
24592
- fs21.stat(path23, function onstat(err, stat) {
24593
- if (err && err.code === "ENOENT" && !extname3(path23) && path23[path23.length - 1] !== sep4) {
24591
+ debug('stat "%s"', path24);
24592
+ fs22.stat(path24, function onstat(err, stat) {
24593
+ if (err && err.code === "ENOENT" && !extname3(path24) && path24[path24.length - 1] !== sep4) {
24594
24594
  return next(err);
24595
24595
  }
24596
24596
  if (err) return self2.onStatError(err);
24597
- if (stat.isDirectory()) return self2.redirect(path23);
24598
- self2.emit("file", path23, stat);
24599
- self2.send(path23, stat);
24597
+ if (stat.isDirectory()) return self2.redirect(path24);
24598
+ self2.emit("file", path24, stat);
24599
+ self2.send(path24, stat);
24600
24600
  });
24601
24601
  function next(err) {
24602
24602
  if (self2._extensions.length <= i) {
24603
24603
  return err ? self2.onStatError(err) : self2.error(404);
24604
24604
  }
24605
- var p = path23 + "." + self2._extensions[i++];
24605
+ var p = path24 + "." + self2._extensions[i++];
24606
24606
  debug('stat "%s"', p);
24607
- fs21.stat(p, function(err2, stat) {
24607
+ fs22.stat(p, function(err2, stat) {
24608
24608
  if (err2) return next(err2);
24609
24609
  if (stat.isDirectory()) return next();
24610
24610
  self2.emit("file", p, stat);
@@ -24612,7 +24612,7 @@ var require_send = __commonJS({
24612
24612
  });
24613
24613
  }
24614
24614
  };
24615
- SendStream.prototype.sendIndex = function sendIndex(path23) {
24615
+ SendStream.prototype.sendIndex = function sendIndex(path24) {
24616
24616
  var i = -1;
24617
24617
  var self2 = this;
24618
24618
  function next(err) {
@@ -24620,9 +24620,9 @@ var require_send = __commonJS({
24620
24620
  if (err) return self2.onStatError(err);
24621
24621
  return self2.error(404);
24622
24622
  }
24623
- var p = join17(path23, self2._index[i]);
24623
+ var p = join18(path24, self2._index[i]);
24624
24624
  debug('stat "%s"', p);
24625
- fs21.stat(p, function(err2, stat) {
24625
+ fs22.stat(p, function(err2, stat) {
24626
24626
  if (err2) return next(err2);
24627
24627
  if (stat.isDirectory()) return next();
24628
24628
  self2.emit("file", p, stat);
@@ -24631,10 +24631,10 @@ var require_send = __commonJS({
24631
24631
  }
24632
24632
  next();
24633
24633
  };
24634
- SendStream.prototype.stream = function stream(path23, options) {
24634
+ SendStream.prototype.stream = function stream(path24, options) {
24635
24635
  var self2 = this;
24636
24636
  var res = this.res;
24637
- var stream2 = fs21.createReadStream(path23, options);
24637
+ var stream2 = fs22.createReadStream(path24, options);
24638
24638
  this.emit("stream", stream2);
24639
24639
  stream2.pipe(res);
24640
24640
  function cleanup() {
@@ -24649,10 +24649,10 @@ var require_send = __commonJS({
24649
24649
  self2.emit("end");
24650
24650
  });
24651
24651
  };
24652
- SendStream.prototype.type = function type(path23) {
24652
+ SendStream.prototype.type = function type(path24) {
24653
24653
  var res = this.res;
24654
24654
  if (res.getHeader("Content-Type")) return;
24655
- var type2 = mime.lookup(path23);
24655
+ var type2 = mime.lookup(path24);
24656
24656
  if (!type2) {
24657
24657
  debug("no content-type");
24658
24658
  return;
@@ -24661,9 +24661,9 @@ var require_send = __commonJS({
24661
24661
  debug("content-type %s", type2);
24662
24662
  res.setHeader("Content-Type", type2 + (charset ? "; charset=" + charset : ""));
24663
24663
  };
24664
- SendStream.prototype.setHeader = function setHeader(path23, stat) {
24664
+ SendStream.prototype.setHeader = function setHeader(path24, stat) {
24665
24665
  var res = this.res;
24666
- this.emit("headers", res, path23, stat);
24666
+ this.emit("headers", res, path24, stat);
24667
24667
  if (this._acceptRanges && !res.getHeader("Accept-Ranges")) {
24668
24668
  debug("accept ranges");
24669
24669
  res.setHeader("Accept-Ranges", "bytes");
@@ -24722,9 +24722,9 @@ var require_send = __commonJS({
24722
24722
  }
24723
24723
  return err instanceof Error ? createError(status, err, { expose: false }) : createError(status, err);
24724
24724
  }
24725
- function decode(path23) {
24725
+ function decode(path24) {
24726
24726
  try {
24727
- return decodeURIComponent(path23);
24727
+ return decodeURIComponent(path24);
24728
24728
  } catch (err) {
24729
24729
  return -1;
24730
24730
  }
@@ -25634,10 +25634,10 @@ var require_utils2 = __commonJS({
25634
25634
  var querystring = require("querystring");
25635
25635
  exports2.etag = createETagGenerator({ weak: false });
25636
25636
  exports2.wetag = createETagGenerator({ weak: true });
25637
- exports2.isAbsolute = function(path22) {
25638
- if ("/" === path22[0]) return true;
25639
- if (":" === path22[1] && ("\\" === path22[2] || "/" === path22[2])) return true;
25640
- if ("\\\\" === path22.substring(0, 2)) return true;
25637
+ exports2.isAbsolute = function(path23) {
25638
+ if ("/" === path23[0]) return true;
25639
+ if (":" === path23[1] && ("\\" === path23[2] || "/" === path23[2])) return true;
25640
+ if ("\\\\" === path23.substring(0, 2)) return true;
25641
25641
  };
25642
25642
  exports2.flatten = deprecate.function(
25643
25643
  flatten,
@@ -25760,7 +25760,7 @@ var require_application = __commonJS({
25760
25760
  "../../node_modules/.pnpm/express@4.22.1/node_modules/express/lib/application.js"(exports2, module2) {
25761
25761
  "use strict";
25762
25762
  var finalhandler = require_finalhandler();
25763
- var Router13 = require_router();
25763
+ var Router14 = require_router();
25764
25764
  var methods = require_methods();
25765
25765
  var middleware = require_init();
25766
25766
  var query = require_query();
@@ -25825,7 +25825,7 @@ var require_application = __commonJS({
25825
25825
  };
25826
25826
  app.lazyrouter = function lazyrouter() {
25827
25827
  if (!this._router) {
25828
- this._router = new Router13({
25828
+ this._router = new Router14({
25829
25829
  caseSensitive: this.enabled("case sensitive routing"),
25830
25830
  strict: this.enabled("strict routing")
25831
25831
  });
@@ -25848,7 +25848,7 @@ var require_application = __commonJS({
25848
25848
  };
25849
25849
  app.use = function use(fn) {
25850
25850
  var offset = 0;
25851
- var path22 = "/";
25851
+ var path23 = "/";
25852
25852
  if (typeof fn !== "function") {
25853
25853
  var arg = fn;
25854
25854
  while (Array.isArray(arg) && arg.length !== 0) {
@@ -25856,7 +25856,7 @@ var require_application = __commonJS({
25856
25856
  }
25857
25857
  if (typeof arg !== "function") {
25858
25858
  offset = 1;
25859
- path22 = fn;
25859
+ path23 = fn;
25860
25860
  }
25861
25861
  }
25862
25862
  var fns = flatten(slice.call(arguments, offset));
@@ -25867,12 +25867,12 @@ var require_application = __commonJS({
25867
25867
  var router = this._router;
25868
25868
  fns.forEach(function(fn2) {
25869
25869
  if (!fn2 || !fn2.handle || !fn2.set) {
25870
- return router.use(path22, fn2);
25870
+ return router.use(path23, fn2);
25871
25871
  }
25872
- debug(".use app under %s", path22);
25873
- fn2.mountpath = path22;
25872
+ debug(".use app under %s", path23);
25873
+ fn2.mountpath = path23;
25874
25874
  fn2.parent = this;
25875
- router.use(path22, function mounted_app(req, res, next) {
25875
+ router.use(path23, function mounted_app(req, res, next) {
25876
25876
  var orig = req.app;
25877
25877
  fn2.handle(req, res, function(err) {
25878
25878
  setPrototypeOf(req, orig.request);
@@ -25884,9 +25884,9 @@ var require_application = __commonJS({
25884
25884
  }, this);
25885
25885
  return this;
25886
25886
  };
25887
- app.route = function route(path22) {
25887
+ app.route = function route(path23) {
25888
25888
  this.lazyrouter();
25889
- return this._router.route(path22);
25889
+ return this._router.route(path23);
25890
25890
  };
25891
25891
  app.engine = function engine(ext, fn) {
25892
25892
  if (typeof fn !== "function") {
@@ -25937,7 +25937,7 @@ var require_application = __commonJS({
25937
25937
  }
25938
25938
  return this;
25939
25939
  };
25940
- app.path = function path22() {
25940
+ app.path = function path23() {
25941
25941
  return this.parent ? this.parent.path() + this.mountpath : "";
25942
25942
  };
25943
25943
  app.enabled = function enabled2(setting) {
@@ -25953,19 +25953,19 @@ var require_application = __commonJS({
25953
25953
  return this.set(setting, false);
25954
25954
  };
25955
25955
  methods.forEach(function(method) {
25956
- app[method] = function(path22) {
25956
+ app[method] = function(path23) {
25957
25957
  if (method === "get" && arguments.length === 1) {
25958
- return this.set(path22);
25958
+ return this.set(path23);
25959
25959
  }
25960
25960
  this.lazyrouter();
25961
- var route = this._router.route(path22);
25961
+ var route = this._router.route(path23);
25962
25962
  route[method].apply(route, slice.call(arguments, 1));
25963
25963
  return this;
25964
25964
  };
25965
25965
  });
25966
- app.all = function all(path22) {
25966
+ app.all = function all(path23) {
25967
25967
  this.lazyrouter();
25968
- var route = this._router.route(path22);
25968
+ var route = this._router.route(path23);
25969
25969
  var args = slice.call(arguments, 1);
25970
25970
  for (var i = 0; i < methods.length; i++) {
25971
25971
  route[methods[i]].apply(route, args);
@@ -26724,7 +26724,7 @@ var require_request = __commonJS({
26724
26724
  var subdomains2 = !isIP(hostname3) ? hostname3.split(".").reverse() : [hostname3];
26725
26725
  return subdomains2.slice(offset);
26726
26726
  });
26727
- defineGetter(req, "path", function path22() {
26727
+ defineGetter(req, "path", function path23() {
26728
26728
  return parse(this).pathname;
26729
26729
  });
26730
26730
  defineGetter(req, "hostname", function hostname3() {
@@ -27043,11 +27043,11 @@ var require_response = __commonJS({
27043
27043
  var createError = require_http_errors();
27044
27044
  var deprecate = require_depd()("express");
27045
27045
  var encodeUrl = require_encodeurl();
27046
- var escapeHtml = require_escape_html();
27046
+ var escapeHtml2 = require_escape_html();
27047
27047
  var http3 = require("http");
27048
27048
  var isAbsolute4 = require_utils2().isAbsolute;
27049
27049
  var onFinished = require_on_finished();
27050
- var path22 = require("path");
27050
+ var path23 = require("path");
27051
27051
  var statuses = require_statuses();
27052
27052
  var merge = require_utils_merge();
27053
27053
  var sign = require_cookie_signature().sign;
@@ -27056,9 +27056,9 @@ var require_response = __commonJS({
27056
27056
  var setCharset = require_utils2().setCharset;
27057
27057
  var cookie = require_cookie();
27058
27058
  var send = require_send();
27059
- var extname3 = path22.extname;
27059
+ var extname3 = path23.extname;
27060
27060
  var mime = send.mime;
27061
- var resolve14 = path22.resolve;
27061
+ var resolve14 = path23.resolve;
27062
27062
  var vary = require_vary();
27063
27063
  var res = Object.create(http3.ServerResponse.prototype);
27064
27064
  module2.exports = res;
@@ -27235,26 +27235,26 @@ var require_response = __commonJS({
27235
27235
  this.type("txt");
27236
27236
  return this.send(body);
27237
27237
  };
27238
- res.sendFile = function sendFile(path23, options, callback) {
27238
+ res.sendFile = function sendFile(path24, options, callback) {
27239
27239
  var done = callback;
27240
27240
  var req = this.req;
27241
27241
  var res2 = this;
27242
27242
  var next = req.next;
27243
27243
  var opts = options || {};
27244
- if (!path23) {
27244
+ if (!path24) {
27245
27245
  throw new TypeError("path argument is required to res.sendFile");
27246
27246
  }
27247
- if (typeof path23 !== "string") {
27247
+ if (typeof path24 !== "string") {
27248
27248
  throw new TypeError("path must be a string to res.sendFile");
27249
27249
  }
27250
27250
  if (typeof options === "function") {
27251
27251
  done = options;
27252
27252
  opts = {};
27253
27253
  }
27254
- if (!opts.root && !isAbsolute4(path23)) {
27254
+ if (!opts.root && !isAbsolute4(path24)) {
27255
27255
  throw new TypeError("path must be absolute or specify root to res.sendFile");
27256
27256
  }
27257
- var pathname = encodeURI(path23);
27257
+ var pathname = encodeURI(path24);
27258
27258
  var file = send(req, pathname, opts);
27259
27259
  sendfile(res2, file, opts, function(err) {
27260
27260
  if (done) return done(err);
@@ -27264,7 +27264,7 @@ var require_response = __commonJS({
27264
27264
  }
27265
27265
  });
27266
27266
  };
27267
- res.sendfile = function(path23, options, callback) {
27267
+ res.sendfile = function(path24, options, callback) {
27268
27268
  var done = callback;
27269
27269
  var req = this.req;
27270
27270
  var res2 = this;
@@ -27274,7 +27274,7 @@ var require_response = __commonJS({
27274
27274
  done = options;
27275
27275
  opts = {};
27276
27276
  }
27277
- var file = send(req, path23, opts);
27277
+ var file = send(req, path24, opts);
27278
27278
  sendfile(res2, file, opts, function(err) {
27279
27279
  if (done) return done(err);
27280
27280
  if (err && err.code === "EISDIR") return next();
@@ -27287,7 +27287,7 @@ var require_response = __commonJS({
27287
27287
  res.sendfile,
27288
27288
  "res.sendfile: Use res.sendFile instead"
27289
27289
  );
27290
- res.download = function download(path23, filename, options, callback) {
27290
+ res.download = function download(path24, filename, options, callback) {
27291
27291
  var done = callback;
27292
27292
  var name2 = filename;
27293
27293
  var opts = options || null;
@@ -27304,7 +27304,7 @@ var require_response = __commonJS({
27304
27304
  opts = filename;
27305
27305
  }
27306
27306
  var headers = {
27307
- "Content-Disposition": contentDisposition(name2 || path23)
27307
+ "Content-Disposition": contentDisposition(name2 || path24)
27308
27308
  };
27309
27309
  if (opts && opts.headers) {
27310
27310
  var keys = Object.keys(opts.headers);
@@ -27317,7 +27317,7 @@ var require_response = __commonJS({
27317
27317
  }
27318
27318
  opts = Object.create(opts);
27319
27319
  opts.headers = headers;
27320
- var fullPath = !opts.root ? resolve14(path23) : path23;
27320
+ var fullPath = !opts.root ? resolve14(path24) : path24;
27321
27321
  return this.sendFile(fullPath, opts, done);
27322
27322
  };
27323
27323
  res.contentType = res.type = function contentType(type) {
@@ -27449,7 +27449,7 @@ var require_response = __commonJS({
27449
27449
  body = statuses.message[status] + ". Redirecting to " + address;
27450
27450
  },
27451
27451
  html: function() {
27452
- var u = escapeHtml(address);
27452
+ var u = escapeHtml2(address);
27453
27453
  body = "<p>" + statuses.message[status] + ". Redirecting to " + u + "</p>";
27454
27454
  },
27455
27455
  default: function() {
@@ -27581,7 +27581,7 @@ var require_serve_static = __commonJS({
27581
27581
  "../../node_modules/.pnpm/serve-static@1.16.3/node_modules/serve-static/index.js"(exports2, module2) {
27582
27582
  "use strict";
27583
27583
  var encodeUrl = require_encodeurl();
27584
- var escapeHtml = require_escape_html();
27584
+ var escapeHtml2 = require_escape_html();
27585
27585
  var parseUrl = require_parseurl();
27586
27586
  var resolve14 = require("path").resolve;
27587
27587
  var send = require_send();
@@ -27618,11 +27618,11 @@ var require_serve_static = __commonJS({
27618
27618
  }
27619
27619
  var forwardError = !fallthrough;
27620
27620
  var originalUrl = parseUrl.original(req);
27621
- var path22 = parseUrl(req).pathname;
27622
- if (path22 === "/" && originalUrl.pathname.substr(-1) !== "/") {
27623
- path22 = "";
27621
+ var path23 = parseUrl(req).pathname;
27622
+ if (path23 === "/" && originalUrl.pathname.substr(-1) !== "/") {
27623
+ path23 = "";
27624
27624
  }
27625
- var stream = send(req, path22, opts);
27625
+ var stream = send(req, path23, opts);
27626
27626
  stream.on("directory", onDirectory);
27627
27627
  if (setHeaders) {
27628
27628
  stream.on("headers", setHeaders);
@@ -27668,7 +27668,7 @@ var require_serve_static = __commonJS({
27668
27668
  originalUrl.path = null;
27669
27669
  originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + "/");
27670
27670
  var loc = encodeUrl(url.format(originalUrl));
27671
- var doc = createHtmlDocument("Redirecting", "Redirecting to " + escapeHtml(loc));
27671
+ var doc = createHtmlDocument("Redirecting", "Redirecting to " + escapeHtml2(loc));
27672
27672
  res.statusCode = 301;
27673
27673
  res.setHeader("Content-Type", "text/html; charset=UTF-8");
27674
27674
  res.setHeader("Content-Length", Buffer.byteLength(doc));
@@ -27690,7 +27690,7 @@ var require_express = __commonJS({
27690
27690
  var mixin = require_merge_descriptors();
27691
27691
  var proto = require_application();
27692
27692
  var Route = require_route();
27693
- var Router13 = require_router();
27693
+ var Router14 = require_router();
27694
27694
  var req = require_request();
27695
27695
  var res = require_response();
27696
27696
  exports2 = module2.exports = createApplication;
@@ -27713,7 +27713,7 @@ var require_express = __commonJS({
27713
27713
  exports2.request = req;
27714
27714
  exports2.response = res;
27715
27715
  exports2.Route = Route;
27716
- exports2.Router = Router13;
27716
+ exports2.Router = Router14;
27717
27717
  exports2.json = bodyParser.json;
27718
27718
  exports2.query = require_query();
27719
27719
  exports2.raw = bodyParser.raw;
@@ -32265,11 +32265,11 @@ function persistNodeStartupTransport(storagePath, transport) {
32265
32265
  transport
32266
32266
  });
32267
32267
  }
32268
- function persistNodeStartupJoin(storagePath, join17) {
32268
+ function persistNodeStartupJoin(storagePath, join18) {
32269
32269
  const startup = resolveNodeStartupMetadata(storagePath);
32270
32270
  persistNodeStartupMetadata(storagePath, {
32271
32271
  ...startup,
32272
- join: join17
32272
+ join: join18
32273
32273
  });
32274
32274
  }
32275
32275
  function resolvePersistedDevTunnelId(storagePath, kind) {
@@ -33266,19 +33266,19 @@ async function fetchWithTimeout(url, init, timeoutMs = DEFAULT_NODE_REQUEST_TIME
33266
33266
  cleanup();
33267
33267
  }
33268
33268
  }
33269
- async function fetchNodeWithFallback(node, path22, init, timeoutMs = DEFAULT_NODE_REQUEST_TIMEOUT_MS, trace, options) {
33269
+ async function fetchNodeWithFallback(node, path23, init, timeoutMs = DEFAULT_NODE_REQUEST_TIMEOUT_MS, trace, options) {
33270
33270
  let lastError;
33271
33271
  const endpoints = getNodeRequestEndpoints(node, options);
33272
33272
  for (const [index, endpoint] of endpoints.entries()) {
33273
33273
  const attempt = index + 1;
33274
- trace?.onAttempt?.({ attempt, endpoint, path: path22, timeoutMs, totalEndpoints: endpoints.length });
33274
+ trace?.onAttempt?.({ attempt, endpoint, path: path23, timeoutMs, totalEndpoints: endpoints.length });
33275
33275
  try {
33276
- const response = await fetchWithTimeout(`${endpoint}${path22}`, init, timeoutMs);
33277
- trace?.onResponse?.({ attempt, endpoint, path: path22, response, timeoutMs, totalEndpoints: endpoints.length });
33276
+ const response = await fetchWithTimeout(`${endpoint}${path23}`, init, timeoutMs);
33277
+ trace?.onResponse?.({ attempt, endpoint, path: path23, response, timeoutMs, totalEndpoints: endpoints.length });
33278
33278
  return { endpoint, response };
33279
33279
  } catch (error) {
33280
33280
  lastError = error;
33281
- trace?.onError?.({ attempt, endpoint, error, path: path22, timeoutMs, totalEndpoints: endpoints.length });
33281
+ trace?.onError?.({ attempt, endpoint, error, path: path23, timeoutMs, totalEndpoints: endpoints.length });
33282
33282
  }
33283
33283
  }
33284
33284
  throw lastError instanceof Error ? lastError : new Error("No reachable node endpoint");
@@ -35321,9 +35321,9 @@ var DataRouter = class {
35321
35321
  /**
35322
35322
  * Returns true if the request should be proxied to the leader.
35323
35323
  */
35324
- shouldProxy(method, path22) {
35324
+ shouldProxy(method, path23) {
35325
35325
  if (this.election.isLeader()) return false;
35326
- if (this.isExcludedPath(path22)) return false;
35326
+ if (this.isExcludedPath(path23)) return false;
35327
35327
  if (method.toUpperCase() === "GET") return false;
35328
35328
  return WRITE_METHODS.has(method.toUpperCase());
35329
35329
  }
@@ -35427,8 +35427,8 @@ var DataRouter = class {
35427
35427
  };
35428
35428
  }
35429
35429
  // ── Helpers ───────────────────────────────────────────────────────────
35430
- isExcludedPath(path22) {
35431
- return EXCLUDED_PATH_PREFIXES.some((prefix) => path22.startsWith(prefix)) || EXCLUDED_PATH_SUFFIXES.some((suffix) => path22.endsWith(suffix));
35430
+ isExcludedPath(path23) {
35431
+ return EXCLUDED_PATH_PREFIXES.some((prefix) => path23.startsWith(prefix)) || EXCLUDED_PATH_SUFFIXES.some((suffix) => path23.endsWith(suffix));
35432
35432
  }
35433
35433
  };
35434
35434
 
@@ -37107,6 +37107,7 @@ var LEGACY_FILES = [
37107
37107
  "nodes.json",
37108
37108
  "tasks.json",
37109
37109
  "shares.json",
37110
+ "node-operations.json",
37110
37111
  "election.json"
37111
37112
  ];
37112
37113
  var LEGACY_DIRS = ["logs", "task-logs"];
@@ -39205,8 +39206,8 @@ function getErrorMap() {
39205
39206
 
39206
39207
  // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
39207
39208
  var makeIssue = (params) => {
39208
- const { data, path: path22, errorMaps, issueData } = params;
39209
- const fullPath = [...path22, ...issueData.path || []];
39209
+ const { data, path: path23, errorMaps, issueData } = params;
39210
+ const fullPath = [...path23, ...issueData.path || []];
39210
39211
  const fullIssue = {
39211
39212
  ...issueData,
39212
39213
  path: fullPath
@@ -39322,11 +39323,11 @@ var errorUtil;
39322
39323
 
39323
39324
  // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js
39324
39325
  var ParseInputLazyPath = class {
39325
- constructor(parent, value, path22, key) {
39326
+ constructor(parent, value, path23, key) {
39326
39327
  this._cachedPath = [];
39327
39328
  this.parent = parent;
39328
39329
  this.data = value;
39329
- this._path = path22;
39330
+ this._path = path23;
39330
39331
  this._key = key;
39331
39332
  }
39332
39333
  get path() {
@@ -43219,16 +43220,17 @@ var TaskOutputContentQuery = external_exports.object({
43219
43220
  });
43220
43221
  var TaskOutputDownloadQuery = TaskOutputContentQuery;
43221
43222
  var TaskPreviewSessionBody = external_exports.object({
43222
- path: external_exports.string().min(1).optional()
43223
+ path: external_exports.string().min(1).optional(),
43224
+ port: external_exports.coerce.number().int().min(1).max(65535).optional()
43223
43225
  });
43224
43226
  var BatchTaskIdsBody = external_exports.object({
43225
43227
  ids: external_exports.array(external_exports.string().min(1)).min(1).max(50)
43226
43228
  });
43227
43229
 
43228
43230
  // ../../packages/api/src/app/server.ts
43229
- var path19 = __toESM(require("path"), 1);
43230
- var fs18 = __toESM(require("fs"), 1);
43231
- var import_express13 = __toESM(require_express2(), 1);
43231
+ var path20 = __toESM(require("path"), 1);
43232
+ var fs19 = __toESM(require("fs"), 1);
43233
+ var import_express14 = __toESM(require_express2(), 1);
43232
43234
 
43233
43235
  // ../../packages/api/src/middleware/auth.ts
43234
43236
  var SKIP_AUTH_PATHS = ["/api/system/health"];
@@ -43354,8 +43356,91 @@ function createAuthMiddleware(config) {
43354
43356
  }
43355
43357
 
43356
43358
  // ../../packages/api/src/middleware/routing.ts
43357
- function createRoutingMiddleware(dataRouter) {
43358
- return dataRouter.createMiddleware();
43359
+ function isRoutingMiddlewareDeps(input) {
43360
+ return "dataRouter" in input;
43361
+ }
43362
+ function decodePathSegment(value) {
43363
+ try {
43364
+ return decodeURIComponent(value);
43365
+ } catch {
43366
+ return value;
43367
+ }
43368
+ }
43369
+ function getSingleTaskDeleteId(path23) {
43370
+ const match = /^\/api\/tasks\/([^/]+)$/.exec(path23);
43371
+ return match ? decodePathSegment(match[1]) : null;
43372
+ }
43373
+ function getSuccessfulBatchDeleteIds(body) {
43374
+ if (!body || typeof body !== "object" || !Array.isArray(body.results)) {
43375
+ return [];
43376
+ }
43377
+ return body.results.flatMap((result) => {
43378
+ if (!result || typeof result !== "object") return [];
43379
+ const item = result;
43380
+ return item.ok === true && typeof item.id === "string" ? [item.id] : [];
43381
+ });
43382
+ }
43383
+ function getProxiedDeleteIds(req, result) {
43384
+ if (result.status < 200 || result.status >= 300) {
43385
+ return [];
43386
+ }
43387
+ const method = req.method.toUpperCase();
43388
+ if (method === "DELETE") {
43389
+ const taskId = getSingleTaskDeleteId(req.path);
43390
+ return taskId ? [taskId] : [];
43391
+ }
43392
+ if (method === "POST" && req.path === "/api/tasks/batch/delete") {
43393
+ return getSuccessfulBatchDeleteIds(result.body);
43394
+ }
43395
+ return [];
43396
+ }
43397
+ function evictLocalTaskMirrors(taskEngine, logger27, taskIds) {
43398
+ if (!taskEngine || taskIds.length === 0) return;
43399
+ for (const taskId of taskIds) {
43400
+ try {
43401
+ taskEngine.deleteTask(taskId);
43402
+ } catch (err) {
43403
+ logger27?.child("routing")?.warn("failed to evict follower-local task mirror after proxied delete", {
43404
+ taskId,
43405
+ error: err instanceof Error ? err.message : String(err)
43406
+ });
43407
+ }
43408
+ }
43409
+ }
43410
+ function createRoutingMiddleware(input) {
43411
+ const deps = isRoutingMiddlewareDeps(input) ? input : { dataRouter: input };
43412
+ const { dataRouter, taskEngine, logger: logger27 } = deps;
43413
+ return async (req, res, next) => {
43414
+ if (!dataRouter.shouldProxy(req.method, req.path)) {
43415
+ next();
43416
+ return;
43417
+ }
43418
+ const leaderEndpoint = dataRouter.getLeaderEndpoint();
43419
+ if (!leaderEndpoint) {
43420
+ res.status(503).json({
43421
+ error: { code: "NO_LEADER", message: "No leader available" }
43422
+ });
43423
+ return;
43424
+ }
43425
+ try {
43426
+ const result = await dataRouter.proxyToLeader(req);
43427
+ evictLocalTaskMirrors(taskEngine, logger27, getProxiedDeleteIds(req, result));
43428
+ for (const [key, value] of Object.entries(result.headers)) {
43429
+ res.setHeader(key, value);
43430
+ }
43431
+ res.status(result.status).json(result.body);
43432
+ } catch (err) {
43433
+ if (err instanceof MeshyError) {
43434
+ res.status(err.statusCode).json({
43435
+ error: { code: err.code, message: err.message }
43436
+ });
43437
+ return;
43438
+ }
43439
+ res.status(502).json({
43440
+ error: { code: "NODE_OFFLINE", message: "Leader unreachable" }
43441
+ });
43442
+ }
43443
+ };
43359
43444
  }
43360
43445
 
43361
43446
  // ../../packages/api/src/middleware/error.ts
@@ -43906,9 +43991,33 @@ function detectHtmlEntries(root) {
43906
43991
  }
43907
43992
  return entries;
43908
43993
  }
43994
+ function detectMarkdownEntries(root) {
43995
+ const entries = [];
43996
+ try {
43997
+ const topLevel = fs14.readdirSync(root, { withFileTypes: true });
43998
+ for (const f of topLevel) {
43999
+ if (f.isFile() && !f.name.startsWith(".") && /\.mdx?$/i.test(f.name)) {
44000
+ entries.push({ path: f.name, label: f.name });
44001
+ }
44002
+ }
44003
+ const subdirs = topLevel.filter((e) => e.isDirectory() && !e.name.startsWith("."));
44004
+ for (const dir of subdirs) {
44005
+ for (const fileName of ["README.md", "readme.md"]) {
44006
+ const readmePath = path15.join(root, dir.name, fileName);
44007
+ if (fs14.existsSync(readmePath)) {
44008
+ entries.push({ path: `${dir.name}/${fileName}`, label: `${dir.name}/${fileName}` });
44009
+ break;
44010
+ }
44011
+ }
44012
+ }
44013
+ } catch {
44014
+ }
44015
+ return entries;
44016
+ }
43909
44017
  function getOutputSummary(root) {
43910
44018
  const rootName = path15.basename(root);
43911
44019
  const htmlEntries = detectHtmlEntries(root);
44020
+ const markdownEntries = detectMarkdownEntries(root);
43912
44021
  let fileCount;
43913
44022
  try {
43914
44023
  const entries = fs14.readdirSync(root, { withFileTypes: true });
@@ -43921,6 +44030,7 @@ function getOutputSummary(root) {
43921
44030
  rootName,
43922
44031
  fileCount,
43923
44032
  htmlEntries,
44033
+ markdownEntries,
43924
44034
  git: null
43925
44035
  // filled in by Git diff API later
43926
44036
  };
@@ -44389,6 +44499,8 @@ function sendLocalNodeWorkDirBranchCreate(req, res, nodeId, options = {}) {
44389
44499
 
44390
44500
  // ../../packages/api/src/tasks/task-route-utils.ts
44391
44501
  var fs15 = __toESM(require("fs"), 1);
44502
+ var import_node_stream2 = require("stream");
44503
+ var import_promises5 = require("stream/promises");
44392
44504
 
44393
44505
  // ../../packages/api/src/node/node-message-compat.ts
44394
44506
  var LEGACY_KIND_BY_NODE_MESSAGE = {
@@ -44621,10 +44733,27 @@ async function sendProxyResponse(res, proxyRes) {
44621
44733
  const contentType = proxyRes.headers.get("content-type");
44622
44734
  const contentDisposition = proxyRes.headers.get("content-disposition");
44623
44735
  const cacheControl = proxyRes.headers.get("cache-control");
44624
- const body = Buffer.from(await proxyRes.arrayBuffer());
44625
44736
  if (contentType) res.setHeader("Content-Type", contentType);
44626
44737
  if (contentDisposition) res.setHeader("Content-Disposition", contentDisposition);
44627
44738
  if (cacheControl) res.setHeader("Cache-Control", cacheControl);
44739
+ if (contentType?.split(";")[0]?.trim().toLowerCase() === "text/event-stream") {
44740
+ if (!cacheControl) res.setHeader("Cache-Control", "no-cache");
44741
+ res.status(proxyRes.status);
44742
+ res.flushHeaders();
44743
+ if (!proxyRes.body) {
44744
+ res.end();
44745
+ return;
44746
+ }
44747
+ try {
44748
+ await (0, import_promises5.pipeline)(import_node_stream2.Readable.fromWeb(proxyRes.body), res);
44749
+ } catch (error) {
44750
+ if (!res.destroyed && !res.writableEnded) {
44751
+ throw error;
44752
+ }
44753
+ }
44754
+ return;
44755
+ }
44756
+ const body = Buffer.from(await proxyRes.arrayBuffer());
44628
44757
  res.status(proxyRes.status).send(body);
44629
44758
  }
44630
44759
  async function maybeProxyReadToLeader(req, res, options = {}) {
@@ -44733,6 +44862,114 @@ var crypto3 = __toESM(require("crypto"), 1);
44733
44862
  var fs16 = __toESM(require("fs"), 1);
44734
44863
  var path17 = __toESM(require("path"), 1);
44735
44864
  var http2 = __toESM(require("http"), 1);
44865
+ var import_node_stream3 = require("stream");
44866
+ var import_promises6 = require("stream/promises");
44867
+
44868
+ // ../../packages/api/src/preview/preview-request.ts
44869
+ var PREVIEW_AUTHORIZATION_HEADER = "x-meshy-preview-authorization";
44870
+ var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
44871
+ "connection",
44872
+ "keep-alive",
44873
+ "proxy-authenticate",
44874
+ "proxy-authorization",
44875
+ "te",
44876
+ "trailer",
44877
+ "transfer-encoding",
44878
+ "upgrade"
44879
+ ]);
44880
+ function isReadOnlyPreviewMethod(method) {
44881
+ const normalizedMethod = method?.toUpperCase() ?? "GET";
44882
+ return normalizedMethod === "GET" || normalizedMethod === "HEAD";
44883
+ }
44884
+ function methodAllowsRequestBody(method) {
44885
+ return !isReadOnlyPreviewMethod(method);
44886
+ }
44887
+ function toArrayBuffer(value) {
44888
+ const copy = new Uint8Array(value.byteLength);
44889
+ copy.set(value);
44890
+ return copy.buffer;
44891
+ }
44892
+ function getParsedRequestBody(req) {
44893
+ const body = req.body;
44894
+ if (body === void 0) {
44895
+ return void 0;
44896
+ }
44897
+ if (typeof body === "string" || body instanceof URLSearchParams || body instanceof Blob || body instanceof FormData) {
44898
+ return body;
44899
+ }
44900
+ if (Buffer.isBuffer(body)) {
44901
+ return toArrayBuffer(body);
44902
+ }
44903
+ if (body instanceof Uint8Array) {
44904
+ return toArrayBuffer(body);
44905
+ }
44906
+ return JSON.stringify(body);
44907
+ }
44908
+ async function readPreviewRequestBody(req) {
44909
+ if (!req || !methodAllowsRequestBody(req.method)) {
44910
+ return void 0;
44911
+ }
44912
+ const parsedBody = getParsedRequestBody(req);
44913
+ if (parsedBody !== void 0) {
44914
+ return parsedBody;
44915
+ }
44916
+ const chunks = [];
44917
+ for await (const chunk of req) {
44918
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
44919
+ }
44920
+ return chunks.length > 0 ? toArrayBuffer(Buffer.concat(chunks)) : void 0;
44921
+ }
44922
+ function buildServiceProxyHeaders(req) {
44923
+ const headers = {};
44924
+ if (!req) {
44925
+ return headers;
44926
+ }
44927
+ let previewAuthorization;
44928
+ for (const [key, value] of Object.entries(req.headers)) {
44929
+ const normalizedKey = key.toLowerCase();
44930
+ if (HOP_BY_HOP_HEADERS.has(normalizedKey) || normalizedKey === "host" || normalizedKey === "content-length" || normalizedKey === "forwarded" || normalizedKey === "x-real-ip" || normalizedKey.startsWith("x-forwarded-") || normalizedKey === MESHY_AUTHORIZATION_HEADER) {
44931
+ continue;
44932
+ }
44933
+ if (normalizedKey === PREVIEW_AUTHORIZATION_HEADER) {
44934
+ previewAuthorization = Array.isArray(value) ? value[0] : value;
44935
+ continue;
44936
+ }
44937
+ if (Array.isArray(value)) {
44938
+ headers[key] = value.join(", ");
44939
+ } else if (typeof value === "string") {
44940
+ headers[key] = value;
44941
+ }
44942
+ }
44943
+ if (previewAuthorization && !headers.authorization) {
44944
+ headers.authorization = previewAuthorization;
44945
+ }
44946
+ return headers;
44947
+ }
44948
+ function buildPreviewWorkerProxyHeaders(req) {
44949
+ const headers = {};
44950
+ let previewAuthorization;
44951
+ for (const [key, value] of Object.entries(req.headers)) {
44952
+ const normalizedKey = key.toLowerCase();
44953
+ if (HOP_BY_HOP_HEADERS.has(normalizedKey) || normalizedKey === "host" || normalizedKey === "content-length" || normalizedKey === MESHY_AUTHORIZATION_HEADER || normalizedKey === PREVIEW_AUTHORIZATION_HEADER) {
44954
+ continue;
44955
+ }
44956
+ if (normalizedKey === "authorization") {
44957
+ previewAuthorization = Array.isArray(value) ? value[0] : value;
44958
+ continue;
44959
+ }
44960
+ if (Array.isArray(value)) {
44961
+ headers[key] = value.join(", ");
44962
+ } else if (typeof value === "string") {
44963
+ headers[key] = value;
44964
+ }
44965
+ }
44966
+ if (previewAuthorization) {
44967
+ headers[PREVIEW_AUTHORIZATION_HEADER] = previewAuthorization;
44968
+ }
44969
+ return headers;
44970
+ }
44971
+
44972
+ // ../../packages/api/src/preview/preview-server.ts
44736
44973
  function resolvePreviewPath(rootPath, relativePath) {
44737
44974
  const sanitizedPath = relativePath.replace(/\\/g, "/");
44738
44975
  const resolvedPath = path17.resolve(rootPath, sanitizedPath);
@@ -44752,22 +44989,58 @@ function resolvePreviewEntryPath(rootPath, entryPath) {
44752
44989
  }
44753
44990
  return normalizedPath;
44754
44991
  }
44992
+ function normalizeServiceEntryPath(entryPath) {
44993
+ if (!entryPath || entryPath === "/") {
44994
+ return "";
44995
+ }
44996
+ return entryPath.replace(/\\/g, "/").replace(/^\/+/, "");
44997
+ }
44998
+ function assertPreviewServicePort(port) {
44999
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
45000
+ throw new Error("Invalid preview service port");
45001
+ }
45002
+ return port;
45003
+ }
44755
45004
  function buildPreviewUrl(origin, session) {
45005
+ return buildPreviewRouteUrl(origin, "preview", session);
45006
+ }
45007
+ function buildPreviewOpenUrl(origin, session) {
45008
+ return buildPreviewRouteUrl(origin, "preview-open", session);
45009
+ }
45010
+ function buildPreviewRouteUrl(origin, route, session) {
44756
45011
  const encodedEntryPath = session.entryPath.split("/").filter(Boolean).map((segment) => encodeURIComponent(segment)).join("/");
44757
- return `${origin.replace(/\/+$/, "")}/preview/${session.token}/${encodedEntryPath}`;
45012
+ const suffix = encodedEntryPath.length > 0 ? `/${encodedEntryPath}` : session.kind === "service" ? "/" : "";
45013
+ return `${origin.replace(/\/+$/, "")}/${route}/${session.token}${suffix}`;
44758
45014
  }
44759
45015
  var DEFAULT_TTL_MS = 15 * 60 * 1e3;
44760
45016
  var PreviewSessionManager = class {
44761
45017
  sessions = /* @__PURE__ */ new Map();
44762
45018
  create(options) {
44763
45019
  const token = crypto3.randomBytes(32).toString("hex");
45020
+ const expiresAt = Date.now() + (options.ttlMs ?? DEFAULT_TTL_MS);
45021
+ if (options.port !== void 0) {
45022
+ const session2 = {
45023
+ token,
45024
+ taskId: options.taskId,
45025
+ kind: "service",
45026
+ port: assertPreviewServicePort(options.port),
45027
+ entryPath: normalizeServiceEntryPath(options.entryPath),
45028
+ expiresAt
45029
+ };
45030
+ this.sessions.set(token, session2);
45031
+ return session2;
45032
+ }
45033
+ if (!options.rootPath) {
45034
+ throw new Error("Preview root path is required");
45035
+ }
44764
45036
  const entryPath = resolvePreviewEntryPath(options.rootPath, options.entryPath);
44765
45037
  const session = {
44766
45038
  token,
44767
45039
  taskId: options.taskId,
45040
+ kind: "file",
44768
45041
  rootPath: options.rootPath,
44769
45042
  entryPath,
44770
- expiresAt: Date.now() + (options.ttlMs ?? DEFAULT_TTL_MS)
45043
+ expiresAt
44771
45044
  };
44772
45045
  this.sessions.set(token, session);
44773
45046
  return session;
@@ -44808,19 +45081,353 @@ var MIME_MAP2 = {
44808
45081
  ".woff2": "font/woff2",
44809
45082
  ".ttf": "font/ttf",
44810
45083
  ".eot": "application/vnd.ms-fontobject",
44811
- ".pdf": "application/pdf"
45084
+ ".pdf": "application/pdf",
45085
+ ".md": "text/markdown",
45086
+ ".mdx": "text/markdown"
44812
45087
  };
44813
45088
  function getMime(filePath) {
44814
45089
  return MIME_MAP2[path17.extname(filePath).toLowerCase()] ?? "application/octet-stream";
44815
45090
  }
44816
- function sendPreviewAssetResponse(sessionManager, token, requestedPath, res) {
45091
+ function escapeHtml(value) {
45092
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
45093
+ }
45094
+ function renderInlineMarkdown(value) {
45095
+ let rendered = escapeHtml(value);
45096
+ rendered = rendered.replace(/!\[([^\]]*)]\(([^\s)]+)\)/g, '<img alt="$1" src="$2">');
45097
+ rendered = rendered.replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\[([^\]]+)]\((https?:\/\/[^\s)]+)\)/g, '<a href="$2" rel="noreferrer noopener" target="_blank">$1</a>');
45098
+ return rendered;
45099
+ }
45100
+ function renderMarkdownBody(markdown) {
45101
+ const lines = markdown.replace(/\r\n/g, "\n").split("\n");
45102
+ const blocks = [];
45103
+ let paragraph = [];
45104
+ let listItems = [];
45105
+ let codeLines = null;
45106
+ const flushParagraph = () => {
45107
+ if (paragraph.length === 0) return;
45108
+ blocks.push(`<p>${renderInlineMarkdown(paragraph.join(" "))}</p>`);
45109
+ paragraph = [];
45110
+ };
45111
+ const flushList = () => {
45112
+ if (listItems.length === 0) return;
45113
+ blocks.push(`<ul>${listItems.map((item) => `<li>${renderInlineMarkdown(item)}</li>`).join("")}</ul>`);
45114
+ listItems = [];
45115
+ };
45116
+ for (const line of lines) {
45117
+ if (line.trim().startsWith("```")) {
45118
+ if (codeLines) {
45119
+ blocks.push(`<pre><code>${escapeHtml(codeLines.join("\n"))}</code></pre>`);
45120
+ codeLines = null;
45121
+ } else {
45122
+ flushParagraph();
45123
+ flushList();
45124
+ codeLines = [];
45125
+ }
45126
+ continue;
45127
+ }
45128
+ if (codeLines) {
45129
+ codeLines.push(line);
45130
+ continue;
45131
+ }
45132
+ const trimmed = line.trim();
45133
+ if (!trimmed) {
45134
+ flushParagraph();
45135
+ flushList();
45136
+ continue;
45137
+ }
45138
+ const heading = trimmed.match(/^(#{1,6})\s+(.+)$/);
45139
+ if (heading) {
45140
+ flushParagraph();
45141
+ flushList();
45142
+ const level = heading[1].length;
45143
+ blocks.push(`<h${level}>${renderInlineMarkdown(heading[2])}</h${level}>`);
45144
+ continue;
45145
+ }
45146
+ const listItem = trimmed.match(/^[-*]\s+(.+)$/);
45147
+ if (listItem) {
45148
+ flushParagraph();
45149
+ listItems.push(listItem[1]);
45150
+ continue;
45151
+ }
45152
+ flushList();
45153
+ paragraph.push(trimmed);
45154
+ }
45155
+ if (codeLines) {
45156
+ blocks.push(`<pre><code>${escapeHtml(codeLines.join("\n"))}</code></pre>`);
45157
+ }
45158
+ flushParagraph();
45159
+ flushList();
45160
+ return blocks.join("\n");
45161
+ }
45162
+ function renderMarkdownDocument(markdown, title) {
45163
+ const body = renderMarkdownBody(markdown);
45164
+ return Buffer.from(`<!doctype html>
45165
+ <html>
45166
+ <head>
45167
+ <meta charset="utf-8">
45168
+ <meta name="viewport" content="width=device-width, initial-scale=1">
45169
+ <title>${escapeHtml(title)}</title>
45170
+ <style>
45171
+ body { box-sizing: border-box; max-width: 860px; margin: 0 auto; padding: 32px; color: #111827; font: 16px/1.65 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
45172
+ h1, h2, h3, h4, h5, h6 { line-height: 1.25; margin: 1.5em 0 0.5em; }
45173
+ h1 { border-bottom: 1px solid #e5e7eb; padding-bottom: 0.3em; }
45174
+ pre { overflow: auto; border-radius: 8px; background: #111827; color: #f9fafb; padding: 16px; }
45175
+ code { border-radius: 4px; background: #f3f4f6; padding: 0.1em 0.25em; }
45176
+ pre code { background: transparent; padding: 0; }
45177
+ img { max-width: 100%; }
45178
+ a { color: #2563eb; }
45179
+ </style>
45180
+ </head>
45181
+ <body>
45182
+ ${body}
45183
+ </body>
45184
+ </html>`, "utf8");
45185
+ }
45186
+ function splitPreviewPathAndSearch(value) {
45187
+ const marker = value.indexOf("?");
45188
+ if (marker === -1) {
45189
+ return { pathname: value, search: "" };
45190
+ }
45191
+ return { pathname: value.slice(0, marker), search: value.slice(marker) };
45192
+ }
45193
+ function normalizeServiceRequestPath(pathname) {
45194
+ const normalized = pathname.replace(/\\/g, "/");
45195
+ if (!normalized || normalized === "/") {
45196
+ return "/";
45197
+ }
45198
+ return `/${normalized.replace(/^\/+/, "")}`;
45199
+ }
45200
+ function rewriteServiceRootRelativeUrls(value, token) {
45201
+ const previewRoot = `/preview/${token}/`;
45202
+ return value.replace(/\b(src|href|action)=(['"])\/(?!\/|preview\/)/gi, `$1=$2${previewRoot}`).replace(/url\((['"]?)\/(?!\/|preview\/)/gi, `url($1${previewRoot}`).replace(/\bimport\((['"])\/(?!\/|preview\/)/gi, `import($1${previewRoot}`).replace(/\bfrom\s+(['"])\/(?!\/|preview\/)/gi, `from $1${previewRoot}`).replace(/(['"])\/(assets\/[^'"]+)\1/g, `$1${previewRoot}$2$1`);
45203
+ }
45204
+ function escapeHtmlAttribute(value) {
45205
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
45206
+ }
45207
+ function buildServicePreviewBridge(token) {
45208
+ const previewRoot = `/preview/${token}/`;
45209
+ const previewBase = previewRoot.replace(/\/$/, "");
45210
+ const script = [
45211
+ "(()=>{",
45212
+ "if(window.top===window)return;",
45213
+ `const previewBase=${JSON.stringify(previewBase)};`,
45214
+ `const previewRoot=${JSON.stringify(previewRoot)};`,
45215
+ "const rewritePreviewRequestUrl=(value)=>{",
45216
+ "if(value==null)return value;",
45217
+ "let raw;",
45218
+ 'try{raw=value instanceof URL?value.href:typeof value==="string"?value:value&&typeof value.url==="string"?value.url:undefined;}catch{return value;}',
45219
+ "if(!raw)return value;",
45220
+ "let url;",
45221
+ "try{url=new URL(raw,window.location.href);}catch{return value;}",
45222
+ "if(url.origin!==window.location.origin)return value;",
45223
+ 'if(url.pathname===previewBase||url.pathname.startsWith(previewRoot)||url.pathname.startsWith("/preview-open/"))return value;',
45224
+ 'return previewRoot+url.pathname.replace(/^\\/+/,"")+url.search+url.hash;',
45225
+ "};",
45226
+ "const rewritePreviewRequestInput=(input)=>{",
45227
+ "const next=rewritePreviewRequestUrl(input);",
45228
+ "if(next===input)return input;",
45229
+ 'if(typeof Request==="function"&&input instanceof Request)return new Request(next,input);',
45230
+ "return next;",
45231
+ "};",
45232
+ "const originalFetch=window.fetch;",
45233
+ 'if(typeof originalFetch==="function")window.fetch=(input,init)=>originalFetch.call(window,rewritePreviewRequestInput(input),init);',
45234
+ "const XHR=window.XMLHttpRequest;",
45235
+ "if(XHR&&XHR.prototype){const open=XHR.prototype.open;XMLHttpRequest.prototype.open=function(method,url,...rest){return open.call(this,method,rewritePreviewRequestUrl(url),...rest);};}",
45236
+ "const OriginalEventSource=window.EventSource;",
45237
+ 'if(typeof OriginalEventSource==="function"){window.EventSource=function(url,config){return new OriginalEventSource(rewritePreviewRequestUrl(url),config);};window.EventSource.prototype=OriginalEventSource.prototype;}',
45238
+ "const currentPath=window.location.pathname;",
45239
+ "if(currentPath===previewBase||currentPath.startsWith(previewRoot)){",
45240
+ "const suffix=currentPath===previewBase?'':currentPath.slice(previewRoot.length);",
45241
+ "const servicePath=suffix?'/' + suffix:'/';",
45242
+ "window.history.replaceState(window.history.state,'',servicePath+window.location.search+window.location.hash);",
45243
+ "}",
45244
+ "})();"
45245
+ ].join("");
45246
+ return `<base data-meshy-preview-base href="${escapeHtmlAttribute(previewRoot)}"><script data-meshy-preview-bridge>${script}</script>`;
45247
+ }
45248
+ function injectServicePreviewBridge(value, token) {
45249
+ const bridge = buildServicePreviewBridge(token);
45250
+ const headPattern = /<head(?:\s[^>]*)?>/i;
45251
+ if (headPattern.test(value)) {
45252
+ return value.replace(headPattern, (match) => `${match}${bridge}`);
45253
+ }
45254
+ const htmlPattern = /<html(?:\s[^>]*)?>/i;
45255
+ if (htmlPattern.test(value)) {
45256
+ return value.replace(htmlPattern, (match) => `${match}<head>${bridge}</head>`);
45257
+ }
45258
+ return `${bridge}${value}`;
45259
+ }
45260
+ function normalizeContentType(contentType) {
45261
+ return contentType?.split(";")[0]?.trim().toLowerCase();
45262
+ }
45263
+ function isServiceHtmlContentType(contentType) {
45264
+ return normalizeContentType(contentType) === "text/html";
45265
+ }
45266
+ function isServiceEventStreamContentType(contentType) {
45267
+ return normalizeContentType(contentType) === "text/event-stream";
45268
+ }
45269
+ function isServiceJavaScriptContentType(normalizedType) {
45270
+ return normalizedType === "text/javascript" || normalizedType === "application/javascript" || normalizedType === "application/x-javascript";
45271
+ }
45272
+ function rewriteServiceJavaScriptRuntimeUrls(value, token) {
45273
+ if (!value.includes("__vite__mapDeps")) {
45274
+ return value;
45275
+ }
45276
+ const previewRoot = `/preview/${token}/`;
45277
+ return value.replace(
45278
+ /return\s*(['"])\/\1\s*\+\s*([A-Za-z_$][\w$]*)/g,
45279
+ (_match, quote, argumentName) => `return${quote}${previewRoot}${quote}+${argumentName}`
45280
+ );
45281
+ }
45282
+ function rewriteServiceResponseContent(content, contentType, token) {
45283
+ const normalizedType = normalizeContentType(contentType);
45284
+ if (normalizedType !== "text/html" && normalizedType !== "text/css" && !isServiceJavaScriptContentType(normalizedType)) {
45285
+ return content;
45286
+ }
45287
+ const source = content.toString("utf8");
45288
+ const bridged = normalizedType === "text/html" ? injectServicePreviewBridge(source, token) : source;
45289
+ const rewritten = rewriteServiceRootRelativeUrls(bridged, token);
45290
+ return Buffer.from(
45291
+ isServiceJavaScriptContentType(normalizedType) ? rewriteServiceJavaScriptRuntimeUrls(rewritten, token) : rewritten,
45292
+ "utf8"
45293
+ );
45294
+ }
45295
+ function rewriteServiceRedirectLocation(value, session) {
45296
+ const previewRoot = `/preview/${session.token}`;
45297
+ if (value.startsWith("/preview/")) {
45298
+ return value;
45299
+ }
45300
+ if (value.startsWith("/")) {
45301
+ return `${previewRoot}${value}`;
45302
+ }
45303
+ try {
45304
+ const url = new URL(value);
45305
+ const isLocalService = (url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "[::1]") && url.port === String(session.port);
45306
+ if (isLocalService) {
45307
+ return `${previewRoot}${url.pathname}${url.search}${url.hash}`;
45308
+ }
45309
+ } catch {
45310
+ }
45311
+ return value;
45312
+ }
45313
+ function buildServiceResponseHeaders(upstream, session, isHtml) {
45314
+ const headers = {};
45315
+ upstream.headers.forEach((value, key) => {
45316
+ const normalizedKey = key.toLowerCase();
45317
+ if (HOP_BY_HOP_HEADERS.has(normalizedKey) || normalizedKey === "content-length" || normalizedKey === "content-encoding" || isHtml && normalizedKey === "content-security-policy" || isHtml && normalizedKey === "content-security-policy-report-only" || isHtml && normalizedKey === "x-frame-options") {
45318
+ return;
45319
+ }
45320
+ if (normalizedKey === "location") {
45321
+ headers[key] = rewriteServiceRedirectLocation(value, session);
45322
+ return;
45323
+ }
45324
+ headers[key] = value;
45325
+ });
45326
+ if (typeof headers["cache-control"] !== "string") {
45327
+ headers["cache-control"] = "no-cache";
45328
+ }
45329
+ return headers;
45330
+ }
45331
+ async function pipeServiceResponseBody(upstream, res) {
45332
+ if (!upstream.body) {
45333
+ res.end();
45334
+ return;
45335
+ }
45336
+ try {
45337
+ await (0, import_promises6.pipeline)(import_node_stream3.Readable.fromWeb(upstream.body), res);
45338
+ } catch (error) {
45339
+ if (!res.destroyed && !res.writableEnded) {
45340
+ throw error;
45341
+ }
45342
+ }
45343
+ }
45344
+ async function sendServicePreviewResponse(session, requestedPath, req, res) {
45345
+ const decodedPath = decodeURIComponent(requestedPath ?? session.entryPath);
45346
+ const { pathname, search } = splitPreviewPathAndSearch(decodedPath);
45347
+ const targetPath = normalizeServiceRequestPath(pathname || session.entryPath);
45348
+ const targetUrl = `http://127.0.0.1:${session.port}${targetPath}${search}`;
45349
+ let upstream;
45350
+ try {
45351
+ const body = await readPreviewRequestBody(req);
45352
+ upstream = await fetch(targetUrl, {
45353
+ method: req?.method ?? "GET",
45354
+ headers: buildServiceProxyHeaders(req),
45355
+ ...body !== void 0 ? { body } : {},
45356
+ redirect: "manual"
45357
+ });
45358
+ } catch {
45359
+ res.writeHead(502, { "Content-Type": "text/plain" });
45360
+ res.end("Preview service unavailable");
45361
+ return;
45362
+ }
45363
+ const upstreamContentType = upstream.headers.get("content-type");
45364
+ const isHtml = isServiceHtmlContentType(upstreamContentType);
45365
+ const headers = buildServiceResponseHeaders(upstream, session, isHtml);
45366
+ if (isServiceEventStreamContentType(upstreamContentType)) {
45367
+ res.writeHead(upstream.status, headers);
45368
+ await pipeServiceResponseBody(upstream, res);
45369
+ return;
45370
+ }
45371
+ const content = rewriteServiceResponseContent(Buffer.from(await upstream.arrayBuffer()), upstreamContentType, session.token);
45372
+ headers["content-length"] = content.length;
45373
+ res.writeHead(upstream.status, headers);
45374
+ res.end(content);
45375
+ }
45376
+ function buildPreviewUrlForRequest(token, requestedPath, session) {
45377
+ const { pathname, search } = splitPreviewPathAndSearch(requestedPath ?? session.entryPath);
45378
+ return `${buildPreviewUrl("", { token, entryPath: pathname, kind: session.kind })}${search}`;
45379
+ }
45380
+ function renderPreviewOpenDocument(previewUrl) {
45381
+ const safePreviewUrl = escapeHtmlAttribute(previewUrl);
45382
+ return Buffer.from(`<!doctype html>
45383
+ <html>
45384
+ <head>
45385
+ <meta charset="utf-8">
45386
+ <meta name="viewport" content="width=device-width, initial-scale=1">
45387
+ <title>Preview</title>
45388
+ <style>
45389
+ html, body { width: 100%; height: 100%; margin: 0; background: #fff; }
45390
+ iframe { display: block; width: 100%; height: 100%; border: 0; }
45391
+ </style>
45392
+ </head>
45393
+ <body>
45394
+ <iframe src="${safePreviewUrl}" title="Preview"></iframe>
45395
+ </body>
45396
+ </html>`, "utf8");
45397
+ }
45398
+ function sendPreviewOpenResponse(sessionManager, token, requestedPath, res) {
45399
+ const session = sessionManager.get(token);
45400
+ if (!session) {
45401
+ res.writeHead(403, { "Content-Type": "text/plain" });
45402
+ res.end("Invalid or expired preview token");
45403
+ return;
45404
+ }
45405
+ const content = renderPreviewOpenDocument(buildPreviewUrlForRequest(token, requestedPath, session));
45406
+ res.writeHead(200, {
45407
+ "Content-Type": "text/html",
45408
+ "Content-Length": content.length,
45409
+ "Cache-Control": "no-cache"
45410
+ });
45411
+ res.end(content);
45412
+ }
45413
+ async function sendPreviewAssetResponse(sessionManager, token, requestedPath, res, req) {
44817
45414
  const session = sessionManager.get(token);
44818
45415
  if (!session) {
44819
45416
  res.writeHead(403, { "Content-Type": "text/plain" });
44820
45417
  res.end("Invalid or expired preview token");
44821
45418
  return;
44822
45419
  }
44823
- const resolvedRequestedPath = decodeURIComponent(requestedPath ?? session.entryPath);
45420
+ if (session.kind === "service") {
45421
+ await sendServicePreviewResponse(session, requestedPath, req, res);
45422
+ return;
45423
+ }
45424
+ if (!isReadOnlyPreviewMethod(req?.method)) {
45425
+ res.writeHead(405, { "Content-Type": "text/plain" });
45426
+ res.end("Method not allowed");
45427
+ return;
45428
+ }
45429
+ const { pathname } = splitPreviewPathAndSearch(decodeURIComponent(requestedPath ?? session.entryPath));
45430
+ const resolvedRequestedPath = pathname || session.entryPath;
44824
45431
  let resolved;
44825
45432
  try {
44826
45433
  resolved = resolvePreviewPath(session.rootPath, resolvedRequestedPath).absolutePath;
@@ -44834,8 +45441,9 @@ function sendPreviewAssetResponse(sessionManager, token, requestedPath, res) {
44834
45441
  res.end("File not found");
44835
45442
  return;
44836
45443
  }
44837
- const mime = getMime(resolved);
44838
- const content = fs16.readFileSync(resolved);
45444
+ const ext = path17.extname(resolved).toLowerCase();
45445
+ const mime = ext === ".md" || ext === ".mdx" ? "text/html" : getMime(resolved);
45446
+ const content = ext === ".md" || ext === ".mdx" ? renderMarkdownDocument(fs16.readFileSync(resolved, "utf8"), path17.basename(resolved)) : fs16.readFileSync(resolved);
44839
45447
  res.writeHead(200, {
44840
45448
  "Content-Type": mime,
44841
45449
  "Content-Length": content.length,
@@ -44843,14 +45451,20 @@ function sendPreviewAssetResponse(sessionManager, token, requestedPath, res) {
44843
45451
  });
44844
45452
  res.end(content);
44845
45453
  }
44846
- function handlePreviewRequest(sessionManager, req, res) {
45454
+ async function handlePreviewRequest(sessionManager, req, res) {
44847
45455
  const url = new URL(req.url ?? "/", "http://localhost");
44848
- if (!url.pathname.startsWith("/preview/")) {
45456
+ if (!url.pathname.startsWith("/preview/") && !url.pathname.startsWith("/preview-open/")) {
44849
45457
  return false;
44850
45458
  }
44851
- if (req.method !== "GET") {
44852
- res.writeHead(405, { "Content-Type": "text/plain" });
44853
- res.end("Method not allowed");
45459
+ const openMatch = url.pathname.match(/^\/preview-open\/([a-f0-9]+)(?:\/(.*))?$/i);
45460
+ if (openMatch?.[1]) {
45461
+ if (!isReadOnlyPreviewMethod(req.method)) {
45462
+ res.writeHead(405, { "Content-Type": "text/plain" });
45463
+ res.end("Method not allowed");
45464
+ return true;
45465
+ }
45466
+ const requestedPath2 = openMatch[2];
45467
+ sendPreviewOpenResponse(sessionManager, openMatch[1], requestedPath2 ? `${requestedPath2}${url.search}` : url.search || void 0, res);
44854
45468
  return true;
44855
45469
  }
44856
45470
  const match = url.pathname.match(/^\/preview\/([a-f0-9]+)(?:\/(.*))?$/i);
@@ -44860,7 +45474,8 @@ function handlePreviewRequest(sessionManager, req, res) {
44860
45474
  res.end("Preview not found");
44861
45475
  return true;
44862
45476
  }
44863
- sendPreviewAssetResponse(sessionManager, token, match?.[2], res);
45477
+ const requestedPath = match?.[2];
45478
+ await sendPreviewAssetResponse(sessionManager, token, requestedPath ? `${requestedPath}${url.search}` : url.search || void 0, res, req);
44864
45479
  return true;
44865
45480
  }
44866
45481
 
@@ -44925,15 +45540,30 @@ function createPreviewAssetProxyTrace(log2, token, nodeId, requestPath, proxyPat
44925
45540
  };
44926
45541
  }
44927
45542
  function parsePreviewRequest(previewUrl) {
44928
- const pathname = new URL(previewUrl, "http://localhost").pathname;
44929
- const match = pathname.match(/^\/preview\/([a-f0-9]+)(?:\/(.*))?$/i);
45543
+ const url = new URL(previewUrl, "http://localhost");
45544
+ const match = url.pathname.match(/^\/preview\/([a-f0-9]+)(?:\/(.*))?$/i);
45545
+ const token = match?.[1];
45546
+ if (!token) {
45547
+ return null;
45548
+ }
45549
+ const requestedPath = match?.[2];
45550
+ return {
45551
+ token,
45552
+ requestedPath: requestedPath ? `${requestedPath}${url.search}` : url.search || void 0
45553
+ };
45554
+ }
45555
+ function parsePreviewOpenRequest(previewUrl) {
45556
+ const url = new URL(previewUrl, "http://localhost");
45557
+ const match = url.pathname.match(/^\/preview-open\/([a-f0-9]+)(?:\/(.*))?$/i);
44930
45558
  const token = match?.[1];
44931
45559
  if (!token) {
44932
45560
  return null;
44933
45561
  }
45562
+ const requestedPath = match?.[2];
45563
+ const suffix = requestedPath !== void 0 ? `/${requestedPath}` : "";
44934
45564
  return {
44935
45565
  token,
44936
- requestedPath: match?.[2]
45566
+ previewUrl: `/preview/${token}${suffix}${url.search}`
44937
45567
  };
44938
45568
  }
44939
45569
  function extractPreviewToken(previewUrl) {
@@ -44981,12 +45611,34 @@ function rewritePreviewSessionPayloadForProxy(manager, payload, nodeId) {
44981
45611
  ...payload,
44982
45612
  previewUrl: buildPreviewUrl("", {
44983
45613
  token,
44984
- entryPath: payload.entryPath
44985
- })
45614
+ entryPath: payload.entryPath,
45615
+ kind: payload.kind
45616
+ }),
45617
+ ...payload.kind === "service" || payload.openUrl ? {
45618
+ openUrl: buildPreviewOpenUrl("", {
45619
+ token,
45620
+ entryPath: payload.entryPath,
45621
+ kind: payload.kind
45622
+ })
45623
+ } : {}
44986
45624
  };
44987
45625
  }
44988
45626
  async function handlePreviewProxyRequest(manager, nodeRegistry, logger27, req, res) {
44989
45627
  const requestPath = req.originalUrl ?? req.url;
45628
+ const previewOpenRequest = parsePreviewOpenRequest(requestPath);
45629
+ if (previewOpenRequest) {
45630
+ const session2 = manager.get(previewOpenRequest.token);
45631
+ if (!session2) {
45632
+ return false;
45633
+ }
45634
+ const content = renderPreviewOpenDocument(previewOpenRequest.previewUrl);
45635
+ res.status(200).set({
45636
+ "Content-Type": "text/html",
45637
+ "Content-Length": String(content.length),
45638
+ "Cache-Control": "no-cache"
45639
+ }).send(content);
45640
+ return true;
45641
+ }
44990
45642
  const previewRequest = parsePreviewRequest(requestPath);
44991
45643
  if (!previewRequest) {
44992
45644
  return false;
@@ -45002,10 +45654,15 @@ async function handlePreviewProxyRequest(manager, nodeRegistry, logger27, req, r
45002
45654
  const previewLog = logger27.child("preview-proxy");
45003
45655
  const proxyPath = buildPreviewAssetProxyPath(previewRequest.token, previewRequest.requestedPath);
45004
45656
  try {
45657
+ const body = await readPreviewRequestBody(req);
45005
45658
  const { endpoint, response } = await fetchNodeWithFallback(
45006
45659
  node,
45007
45660
  proxyPath,
45008
- void 0,
45661
+ {
45662
+ method: req.method,
45663
+ headers: buildPreviewWorkerProxyHeaders(req),
45664
+ ...body !== void 0 ? { body } : {}
45665
+ },
45009
45666
  PREVIEW_ASSET_PROXY_TIMEOUT_MS,
45010
45667
  createPreviewAssetProxyTrace(previewLog, previewRequest.token, session.nodeId, requestPath, proxyPath),
45011
45668
  { preferPublicEndpoint: true }
@@ -45135,16 +45792,21 @@ function getLocalTaskOutputDiff(taskEngine, taskId) {
45135
45792
  const rootPath = getTaskOutputRoot(taskEngine, taskId);
45136
45793
  return getGitDiff(rootPath);
45137
45794
  }
45138
- async function createPreviewSessionPayload(deps, taskId, entryPath, requestOrigin) {
45795
+ async function createPreviewSessionPayload(deps, taskId, optionsOrPath, requestOrigin) {
45139
45796
  const previewManager = deps.previewSessionManager;
45140
45797
  if (!previewManager) {
45141
45798
  throw new MeshyError("VALIDATION_ERROR", "Preview not available on this node", 400);
45142
45799
  }
45143
- const rootPath = getTaskOutputRoot(deps.taskEngine, taskId);
45144
- const session = previewManager.create({
45800
+ const options = typeof optionsOrPath === "string" ? { path: optionsOrPath } : optionsOrPath ?? {};
45801
+ getTask(deps.taskEngine, taskId);
45802
+ const session = options.port !== void 0 ? previewManager.create({
45145
45803
  taskId,
45146
- rootPath,
45147
- entryPath
45804
+ port: options.port,
45805
+ entryPath: options.path
45806
+ }) : previewManager.create({
45807
+ taskId,
45808
+ rootPath: getTaskOutputRoot(deps.taskEngine, taskId),
45809
+ entryPath: options.path
45148
45810
  });
45149
45811
  const origin = requestOrigin ?? deps.dashboardOrigin ?? deps.localDashboardOrigin;
45150
45812
  if (!origin) {
@@ -45152,8 +45814,11 @@ async function createPreviewSessionPayload(deps, taskId, entryPath, requestOrigi
45152
45814
  }
45153
45815
  return {
45154
45816
  previewUrl: buildPreviewUrl(origin, session),
45817
+ ...session.kind === "service" ? { openUrl: buildPreviewOpenUrl(origin, session) } : {},
45155
45818
  expiresAt: session.expiresAt,
45156
- entryPath: session.entryPath
45819
+ entryPath: session.entryPath,
45820
+ kind: session.kind,
45821
+ ...session.kind === "service" ? { port: session.port } : {}
45157
45822
  };
45158
45823
  }
45159
45824
 
@@ -45440,6 +46105,264 @@ function upgradeRuntimeAgentForDeps(deps, agent) {
45440
46105
  return result;
45441
46106
  }
45442
46107
 
46108
+ // ../../packages/api/src/node/node-operation-service.ts
46109
+ var fs18 = __toESM(require("fs"), 1);
46110
+ var path19 = __toESM(require("path"), 1);
46111
+ var import_node_crypto7 = require("crypto");
46112
+ var NodeOperationFailure = class extends Error {
46113
+ constructor(message, result) {
46114
+ super(message);
46115
+ this.result = result;
46116
+ }
46117
+ };
46118
+ var InMemoryNodeOperationStore = class {
46119
+ operations = /* @__PURE__ */ new Map();
46120
+ get(id) {
46121
+ const operation = this.operations.get(id);
46122
+ return operation ? clone2(operation) : null;
46123
+ }
46124
+ list(filter = {}) {
46125
+ return Array.from(this.operations.values()).filter((operation) => matchesFilter(operation, filter)).sort((a, b) => b.createdAt - a.createdAt).map((operation) => clone2(operation));
46126
+ }
46127
+ upsert(operation) {
46128
+ const copy = clone2(operation);
46129
+ this.operations.set(copy.id, copy);
46130
+ return clone2(copy);
46131
+ }
46132
+ update(id, updates) {
46133
+ const current = this.operations.get(id);
46134
+ if (!current) return null;
46135
+ const next = { ...current, ...clone2(updates), id, createdAt: current.createdAt };
46136
+ this.operations.set(id, next);
46137
+ return clone2(next);
46138
+ }
46139
+ };
46140
+ var FileNodeOperationStore = class {
46141
+ constructor(storagePath) {
46142
+ this.storagePath = storagePath;
46143
+ }
46144
+ operations = /* @__PURE__ */ new Map();
46145
+ loaded = false;
46146
+ get(id) {
46147
+ this.load();
46148
+ const operation = this.operations.get(id);
46149
+ return operation ? clone2(operation) : null;
46150
+ }
46151
+ list(filter = {}) {
46152
+ this.load();
46153
+ return Array.from(this.operations.values()).filter((operation) => matchesFilter(operation, filter)).sort((a, b) => b.createdAt - a.createdAt).map((operation) => clone2(operation));
46154
+ }
46155
+ upsert(operation) {
46156
+ this.load();
46157
+ const copy = clone2(operation);
46158
+ this.operations.set(copy.id, copy);
46159
+ this.persist();
46160
+ return clone2(copy);
46161
+ }
46162
+ update(id, updates) {
46163
+ this.load();
46164
+ const current = this.operations.get(id);
46165
+ if (!current) return null;
46166
+ const next = { ...current, ...clone2(updates), id, createdAt: current.createdAt };
46167
+ this.operations.set(id, next);
46168
+ this.persist();
46169
+ return clone2(next);
46170
+ }
46171
+ load() {
46172
+ if (this.loaded) return;
46173
+ this.loaded = true;
46174
+ if (!fs18.existsSync(this.filePath)) return;
46175
+ const raw = JSON.parse(fs18.readFileSync(this.filePath, "utf-8"));
46176
+ const entries = Array.isArray(raw) ? raw : Object.values(raw);
46177
+ for (const entry of entries) {
46178
+ if (isNodeOperation(entry)) {
46179
+ this.operations.set(entry.id, clone2(entry));
46180
+ }
46181
+ }
46182
+ }
46183
+ persist() {
46184
+ fs18.mkdirSync(this.storagePath, { recursive: true });
46185
+ const body = JSON.stringify(Object.fromEntries(this.operations), null, 2);
46186
+ const tmpPath = `${this.filePath}.tmp`;
46187
+ fs18.writeFileSync(tmpPath, body, "utf-8");
46188
+ fs18.renameSync(tmpPath, this.filePath);
46189
+ }
46190
+ get filePath() {
46191
+ return path19.join(this.storagePath, "node-operations.json");
46192
+ }
46193
+ };
46194
+ var NodeOperationService = class {
46195
+ constructor(deps, store) {
46196
+ this.deps = deps;
46197
+ this.store = store;
46198
+ this.registerHandler("agent.upgrade", runAgentUpgradeOperation);
46199
+ }
46200
+ handlers = /* @__PURE__ */ new Map();
46201
+ registerHandler(kind, handler) {
46202
+ this.handlers.set(kind, handler);
46203
+ }
46204
+ create(kind, nodeId, payload) {
46205
+ const now = Date.now();
46206
+ const operation = {
46207
+ id: (0, import_node_crypto7.randomUUID)(),
46208
+ kind,
46209
+ nodeId,
46210
+ requestedByNodeId: this.deps.nodeRegistry.getSelf().id,
46211
+ status: "queued",
46212
+ payload,
46213
+ createdAt: now,
46214
+ updatedAt: now
46215
+ };
46216
+ const saved = this.store.upsert(operation);
46217
+ this.deps.eventBus.emit("node.operation.created", { operation: saved });
46218
+ return saved;
46219
+ }
46220
+ get(id) {
46221
+ return this.store.get(id);
46222
+ }
46223
+ list(filter) {
46224
+ return this.store.list(filter);
46225
+ }
46226
+ accept(operation) {
46227
+ const current = this.store.get(operation.id);
46228
+ if (current) {
46229
+ if (current.status === "queued") this.scheduleRun(current.id);
46230
+ return current;
46231
+ }
46232
+ const saved = this.store.upsert({ ...operation, status: "queued", updatedAt: Date.now() });
46233
+ this.deps.eventBus.emit("node.operation.created", { operation: saved });
46234
+ this.scheduleRun(saved.id);
46235
+ return saved;
46236
+ }
46237
+ runLocal(id) {
46238
+ this.scheduleRun(id);
46239
+ }
46240
+ applyRemoteUpdate(operation) {
46241
+ const current = this.store.get(operation.id);
46242
+ const saved = this.store.upsert(current ? { ...current, ...operation } : operation);
46243
+ this.applyOperationSideEffects(saved);
46244
+ this.deps.eventBus.emit("node.operation.updated", { operation: saved });
46245
+ return saved;
46246
+ }
46247
+ markFailed(id, error) {
46248
+ return this.update(id, {
46249
+ status: "failed",
46250
+ error,
46251
+ completedAt: Date.now()
46252
+ });
46253
+ }
46254
+ scheduleRun(id) {
46255
+ setTimeout(() => {
46256
+ void this.run(id);
46257
+ }, 0);
46258
+ }
46259
+ async run(id) {
46260
+ const operation = this.store.get(id);
46261
+ if (!operation || operation.status !== "queued") return;
46262
+ const running = this.update(id, { status: "running", startedAt: Date.now() });
46263
+ if (!running) return;
46264
+ try {
46265
+ const handler = this.handlers.get(running.kind);
46266
+ if (!handler) throw new Error(`No node operation handler registered for kind: ${running.kind}`);
46267
+ const result = await handler(running, this.deps);
46268
+ this.update(id, { status: "succeeded", result, completedAt: Date.now() });
46269
+ } catch (err) {
46270
+ this.update(id, {
46271
+ status: "failed",
46272
+ result: err instanceof NodeOperationFailure ? err.result : void 0,
46273
+ error: err instanceof Error ? err.message : String(err),
46274
+ completedAt: Date.now()
46275
+ });
46276
+ }
46277
+ }
46278
+ update(id, updates) {
46279
+ const saved = this.store.update(id, { ...updates, updatedAt: Date.now() });
46280
+ if (!saved) return null;
46281
+ this.applyOperationSideEffects(saved);
46282
+ this.deps.eventBus.emit("node.operation.updated", { operation: saved });
46283
+ void this.reportToLeader(saved);
46284
+ return saved;
46285
+ }
46286
+ applyOperationSideEffects(operation) {
46287
+ if (operation.kind !== "agent.upgrade" || operation.status !== "succeeded") return;
46288
+ const settingsSnapshot = readSettingsSnapshot(operation.result);
46289
+ if (settingsSnapshot) {
46290
+ this.deps.nodeRegistry.updateSettingsSnapshot(operation.nodeId, settingsSnapshot);
46291
+ }
46292
+ }
46293
+ async reportToLeader(operation) {
46294
+ if (this.deps.nodeRegistry.isLeader()) return;
46295
+ const leaderEndpoint = this.deps.nodeRegistry.getLeaderEndpoint?.();
46296
+ if (!leaderEndpoint) return;
46297
+ try {
46298
+ await fetch(`${leaderEndpoint}/api/worker/node-operations/${operation.id}`, applyRequestAuthHeaders({
46299
+ method: "POST",
46300
+ headers: { "Content-Type": "application/json" },
46301
+ body: JSON.stringify(operation)
46302
+ }));
46303
+ } catch (err) {
46304
+ this.deps.logger.child("node-operation").warn("failed to report node operation update to leader", {
46305
+ operationId: operation.id,
46306
+ kind: operation.kind,
46307
+ error: err instanceof Error ? err.message : String(err)
46308
+ });
46309
+ }
46310
+ }
46311
+ };
46312
+ function getNodeOperationService(deps) {
46313
+ if (deps.nodeOperationService) return deps.nodeOperationService;
46314
+ const store = deps.nodeOperationStore ?? (deps.storagePath ? new FileNodeOperationStore(deps.storagePath) : new InMemoryNodeOperationStore());
46315
+ const service = new NodeOperationService(deps, store);
46316
+ deps.nodeOperationStore = store;
46317
+ deps.nodeOperationService = service;
46318
+ return service;
46319
+ }
46320
+ async function dispatchNodeOperation(deps, operation, node) {
46321
+ const message = createNodeMessage("node.operation.execute", { operation });
46322
+ const heartbeat = deps.heartbeat;
46323
+ if (heartbeat.canPushToNode?.(node.id) === false) {
46324
+ if (!heartbeat.enqueueNodeMessage) throw new Error(`Cannot queue node operation for ${node.id}`);
46325
+ heartbeat.enqueueNodeMessage(node.id, message);
46326
+ return;
46327
+ }
46328
+ const client = new NodeMessageClient({
46329
+ heartbeat: heartbeat.enqueueNodeMessage ? { enqueueNodeMessage: heartbeat.enqueueNodeMessage.bind(heartbeat) } : void 0,
46330
+ logger: deps.logger
46331
+ });
46332
+ await client.send(node, message);
46333
+ }
46334
+ function runAgentUpgradeOperation(operation, deps) {
46335
+ const agent = readPayloadString(operation, "agent");
46336
+ if (!isRuntimeAgentId(agent)) throw new Error(`Unsupported upgrade agent: ${agent}`);
46337
+ const result = upgradeRuntimeAgentForDeps(deps, agent);
46338
+ if (!result.ok) {
46339
+ throw new NodeOperationFailure(result.detail ?? `${agent} upgrade failed`, result);
46340
+ }
46341
+ return result;
46342
+ }
46343
+ function readPayloadString(operation, key) {
46344
+ const payload = operation.payload;
46345
+ if (!payload || typeof payload !== "object") return "";
46346
+ const value = payload[key];
46347
+ return typeof value === "string" ? value : "";
46348
+ }
46349
+ function readSettingsSnapshot(value) {
46350
+ if (!value || typeof value !== "object") return void 0;
46351
+ const snapshot = value.settingsSnapshot;
46352
+ return snapshot && typeof snapshot === "object" ? snapshot : void 0;
46353
+ }
46354
+ function matchesFilter(operation, filter) {
46355
+ return (!filter.nodeId || operation.nodeId === filter.nodeId) && (!filter.status || operation.status === filter.status) && (!filter.kind || operation.kind === filter.kind);
46356
+ }
46357
+ function isNodeOperation(value) {
46358
+ if (!value || typeof value !== "object") return false;
46359
+ const record = value;
46360
+ return typeof record.id === "string" && typeof record.kind === "string" && typeof record.nodeId === "string" && typeof record.status === "string" && typeof record.createdAt === "number" && typeof record.updatedAt === "number";
46361
+ }
46362
+ function clone2(value) {
46363
+ return JSON.parse(JSON.stringify(value));
46364
+ }
46365
+
45443
46366
  // ../../packages/api/src/node/worker-control.ts
45444
46367
  function jsonResponse(requestId, statusCode, body) {
45445
46368
  return {
@@ -45607,6 +46530,15 @@ async function executeWorkerControlRequest(deps, request) {
45607
46530
  response = jsonResponse(request.id, 200, upgradeRuntimeAgentForDeps(deps, agent));
45608
46531
  break;
45609
46532
  }
46533
+ case "node.operation.execute": {
46534
+ const operation = payloadValue(request, "operation", null);
46535
+ if (!operation || typeof operation !== "object") {
46536
+ throw new MeshyError("VALIDATION_ERROR", "node.operation.execute requires an operation payload", 400);
46537
+ }
46538
+ const accepted = getNodeOperationService(deps).accept(operation);
46539
+ response = jsonResponse(request.id, 202, { operationId: accepted.id, accepted: true });
46540
+ break;
46541
+ }
45610
46542
  case "task.cancel": {
45611
46543
  const taskId = payloadValue(request, "taskId", "");
45612
46544
  const result = cancelTaskOnCurrentNode({
@@ -45675,10 +46607,15 @@ async function executeWorkerControlRequest(deps, request) {
45675
46607
  break;
45676
46608
  }
45677
46609
  case "task.preview.create": {
46610
+ const previewPath = payloadValue(request, "path", void 0);
46611
+ const previewPort = payloadValue(request, "port", void 0);
45678
46612
  response = jsonResponse(
45679
46613
  request.id,
45680
46614
  200,
45681
- await createPreviewSessionPayload(deps, payloadValue(request, "taskId", ""), payloadValue(request, "path", void 0))
46615
+ await createPreviewSessionPayload(deps, payloadValue(request, "taskId", ""), {
46616
+ path: typeof previewPath === "string" ? previewPath : void 0,
46617
+ port: typeof previewPort === "number" ? previewPort : void 0
46618
+ })
45682
46619
  );
45683
46620
  break;
45684
46621
  }
@@ -45751,58 +46688,10 @@ function sendLocalNodeNativeSessions(req, res, nodeId, options = {}) {
45751
46688
  }
45752
46689
 
45753
46690
  // ../../packages/api/src/routes/node-agent-upgrade.ts
45754
- function isRecord5(value) {
45755
- return typeof value === "object" && value !== null && !Array.isArray(value);
45756
- }
45757
- function readSettingsSnapshot(value) {
45758
- if (!isRecord5(value)) return void 0;
45759
- const snapshot = value.settingsSnapshot;
45760
- if (!isRecord5(snapshot)) return void 0;
45761
- return snapshot;
45762
- }
45763
- function applySyncedSettingsSnapshot(deps, nodeId, body) {
45764
- const settingsSnapshot = readSettingsSnapshot(body);
45765
- if (settingsSnapshot) {
45766
- deps.nodeRegistry.updateSettingsSnapshot(nodeId, settingsSnapshot);
45767
- }
45768
- }
45769
46691
  function parseAgent(value) {
45770
46692
  if (isRuntimeAgentId(value)) return value;
45771
46693
  throw new MeshyError("VALIDATION_ERROR", `Unsupported upgrade agent: ${value}`, 400);
45772
46694
  }
45773
- function upgradeSelfNode(deps, nodeId, agent) {
45774
- const result = upgradeRuntimeAgentForDeps(deps, agent);
45775
- applySyncedSettingsSnapshot(deps, nodeId, result);
45776
- return result;
45777
- }
45778
- async function fallbackUpgrade(deps, res, nodeId, agent) {
45779
- if (!canRequestNodeMessage(deps.heartbeat)) {
45780
- throw new MeshyError("NODE_OFFLINE", `Cannot reach node ${nodeId} to upgrade ${agent}`, 502);
45781
- }
45782
- const controlResponse = await requestFallbackNodeMessage(
45783
- deps.heartbeat,
45784
- nodeId,
45785
- createNodeMessage("node.agent.upgrade", { agent }, { expectsResponse: true })
45786
- );
45787
- applySyncedSettingsSnapshot(deps, nodeId, controlResponse.body);
45788
- sendWorkerControlResponse(res, controlResponse);
45789
- }
45790
- async function proxyUpgrade(deps, nodeId, agent) {
45791
- const node = deps.nodeRegistry.getNode(nodeId);
45792
- if (!node) {
45793
- throw new MeshyError("NODE_NOT_FOUND", `Node ${nodeId} not found`, 404);
45794
- }
45795
- const { response } = await fetchNodeWithFallback(node, `/api/nodes/${nodeId}/agents/${agent}/upgrade`, {
45796
- method: "POST",
45797
- headers: { "Content-Type": "application/json" }
45798
- }, void 0, void 0, { preferPublicEndpoint: true });
45799
- const body = await response.json().catch(() => ({ error: response.statusText }));
45800
- if (!response.ok) {
45801
- throw new MeshyError("NODE_OFFLINE", `Remote node returned ${response.status}`, response.status, body);
45802
- }
45803
- applySyncedSettingsSnapshot(deps, nodeId, body);
45804
- return body;
45805
- }
45806
46695
  async function sendNodeAgentUpgrade(req, res, nodeId, agentParam) {
45807
46696
  const deps = req.app.locals.deps;
45808
46697
  const agent = parseAgent(agentParam);
@@ -45811,21 +46700,23 @@ async function sendNodeAgentUpgrade(req, res, nodeId, agentParam) {
45811
46700
  if (!isSelf && !deps.election.isLeader()) {
45812
46701
  throw new MeshyError("NOT_LEADER", "Only the leader can upgrade agents on other nodes", 403);
45813
46702
  }
45814
- if (isSelf) {
45815
- res.json(upgradeSelfNode(deps, nodeId, agent));
45816
- return;
45817
- }
45818
- const canPushToNode = deps.heartbeat?.canPushToNode?.(nodeId) ?? true;
45819
- if (!canPushToNode) {
45820
- await fallbackUpgrade(deps, res, nodeId, agent);
45821
- return;
46703
+ const node = isSelf ? self2 : deps.nodeRegistry.getNode(nodeId);
46704
+ if (!node) {
46705
+ throw new MeshyError("NODE_NOT_FOUND", `Node ${nodeId} not found`, 404);
45822
46706
  }
45823
- try {
45824
- res.json(await proxyUpgrade(deps, nodeId, agent));
45825
- } catch (err) {
45826
- if (!canRequestNodeMessage(deps.heartbeat)) throw err;
45827
- await fallbackUpgrade(deps, res, nodeId, agent);
46707
+ const operations = getNodeOperationService(deps);
46708
+ const operation = operations.create("agent.upgrade", nodeId, { agent });
46709
+ if (isSelf) {
46710
+ operations.runLocal(operation.id);
46711
+ } else {
46712
+ try {
46713
+ await dispatchNodeOperation(deps, operation, node);
46714
+ } catch (err) {
46715
+ operations.markFailed(operation.id, err instanceof Error ? err.message : String(err));
46716
+ throw new MeshyError("NODE_OFFLINE", `Cannot reach node ${nodeId} to upgrade ${agent}`, 502);
46717
+ }
45828
46718
  }
46719
+ res.status(202).json(operation);
45829
46720
  }
45830
46721
 
45831
46722
  // ../../packages/api/src/routes/nodes.ts
@@ -47180,12 +48071,12 @@ function createTaskOutputRoutes(options = {}) {
47180
48071
  method: "POST",
47181
48072
  headers: { "Content-Type": "application/json" },
47182
48073
  body: JSON.stringify(body)
47183
- }, createNodeMessage("task.preview.create", { taskId, path: body.path }, { expectsResponse: true }));
48074
+ }, createNodeMessage("task.preview.create", { taskId, path: body.path, port: body.port }, { expectsResponse: true }));
47184
48075
  if (handled) {
47185
48076
  return;
47186
48077
  }
47187
48078
  }
47188
- res.json(await createPreviewSessionPayload(req.app.locals.deps, taskId, body.path, resolveRequestOrigin(req)));
48079
+ res.json(await createPreviewSessionPayload(req.app.locals.deps, taskId, body, resolveRequestOrigin(req)));
47189
48080
  }));
47190
48081
  return router;
47191
48082
  }
@@ -47750,13 +48641,16 @@ function createSharedRoutes() {
47750
48641
  const shareId = req.params.shareId;
47751
48642
  const share = assertActiveShare(taskEngine.getTaskShare(shareId));
47752
48643
  assertFilesPreviewShare(share);
48644
+ if (body.port !== void 0) {
48645
+ throw new MeshyError("VALIDATION_ERROR", "Shared previews only support task output files", 403);
48646
+ }
47753
48647
  const handled = await maybeHandleRemoteTaskOutputRequest(req, res, share.taskId, "/preview-sessions", {
47754
48648
  method: "POST",
47755
48649
  headers: { "Content-Type": "application/json" },
47756
48650
  body: JSON.stringify(body)
47757
48651
  }, createNodeMessage("task.preview.create", { taskId: share.taskId, path: body.path }, { expectsResponse: true }));
47758
48652
  if (handled) return;
47759
- res.json(await createPreviewSessionPayload(req.app.locals.deps, share.taskId, body.path, resolveRequestOrigin(req)));
48653
+ res.json(await createPreviewSessionPayload(req.app.locals.deps, share.taskId, body, resolveRequestOrigin(req)));
47760
48654
  }));
47761
48655
  return router;
47762
48656
  }
@@ -47774,6 +48668,15 @@ function asyncHandler8(fn) {
47774
48668
  }
47775
48669
  function createWorkerRoutes() {
47776
48670
  const router = (0, import_express10.Router)();
48671
+ router.post("/node-operations/:id", asyncHandler8(async (req, res) => {
48672
+ const deps = req.app.locals.deps;
48673
+ const operation = req.body;
48674
+ if (!operation || operation.id !== req.params.id) {
48675
+ throw new MeshyError("VALIDATION_ERROR", "Node operation update id mismatch", 400);
48676
+ }
48677
+ const saved = getNodeOperationService(deps).applyRemoteUpdate(operation);
48678
+ res.json({ ok: true, operation: saved });
48679
+ }));
47777
48680
  router.post("/execute", asyncHandler8(async (req, res) => {
47778
48681
  const { taskEngine, engineRegistry, nodeRegistry, eventBus, logger: rootLogger, workDir } = req.app.locals.deps;
47779
48682
  const log2 = rootLogger.child("worker/execute");
@@ -47945,20 +48848,20 @@ function createWorkerRoutes() {
47945
48848
  const payload = await createPreviewSessionPayload(
47946
48849
  req.app.locals.deps,
47947
48850
  body.taskId,
47948
- body.path,
48851
+ body,
47949
48852
  resolveRequestOrigin(req)
47950
48853
  );
47951
- log2.info("created preview session", { taskId: body.taskId, entryPath: payload.entryPath });
48854
+ log2.info("created preview session", { taskId: body.taskId, entryPath: payload.entryPath, kind: payload.kind, port: payload.port });
47952
48855
  res.json(payload);
47953
48856
  }));
47954
- router.get("/preview-asset", asyncHandler8(async (req, res) => {
48857
+ router.all("/preview-asset", asyncHandler8(async (req, res) => {
47955
48858
  const { previewSessionManager } = req.app.locals.deps;
47956
48859
  if (!previewSessionManager) {
47957
48860
  throw new MeshyError("VALIDATION_ERROR", "Preview not available on this node", 400);
47958
48861
  }
47959
48862
  const token = external_exports.string().min(1).parse(req.query.token);
47960
48863
  const requestedPath = typeof req.query.path === "string" && req.query.path.length > 0 ? req.query.path : void 0;
47961
- sendPreviewAssetResponse(previewSessionManager, token, requestedPath, res);
48864
+ await sendPreviewAssetResponse(previewSessionManager, token, requestedPath, res, req);
47962
48865
  }));
47963
48866
  router.post("/control-response", asyncHandler8(async (req, res) => {
47964
48867
  const { heartbeat, logger: rootLogger } = req.app.locals.deps;
@@ -48101,15 +49004,17 @@ function createSystemRoutes() {
48101
49004
  var import_express12 = __toESM(require_express2(), 1);
48102
49005
  var HEARTBEAT_INTERVAL_MS = 15e3;
48103
49006
  var CATEGORY_MAP = {
48104
- tasks: "task.",
48105
- nodes: "node.",
48106
- elections: "election.",
48107
- cluster: "cluster."
49007
+ tasks: ["task."],
49008
+ nodes: ["node.", "transport."],
49009
+ elections: ["election."],
49010
+ cluster: ["cluster."]
48108
49011
  };
48109
49012
  var ALL_EVENT_NAMES = [
48110
49013
  "node.joined",
48111
49014
  "node.left",
48112
49015
  "node.status",
49016
+ "node.operation.created",
49017
+ "node.operation.updated",
48113
49018
  "task.created",
48114
49019
  "task.assigned",
48115
49020
  "task.status",
@@ -48118,7 +49023,8 @@ var ALL_EVENT_NAMES = [
48118
49023
  "task.output",
48119
49024
  "election.started",
48120
49025
  "election.complete",
48121
- "cluster.state"
49026
+ "cluster.state",
49027
+ "transport.changed"
48122
49028
  ];
48123
49029
  function parseFilter(filterParam) {
48124
49030
  if (typeof filterParam !== "string" || filterParam.trim() === "") {
@@ -48129,8 +49035,8 @@ function parseFilter(filterParam) {
48129
49035
  function shouldIncludeEvent(eventName, categories) {
48130
49036
  if (!categories) return true;
48131
49037
  return categories.some((cat) => {
48132
- const prefix = CATEGORY_MAP[cat];
48133
- return prefix != null && eventName.startsWith(prefix);
49038
+ const prefixes = CATEGORY_MAP[cat];
49039
+ return prefixes != null && prefixes.some((prefix) => eventName.startsWith(prefix));
48134
49040
  });
48135
49041
  }
48136
49042
  function createEventRoutes() {
@@ -48174,6 +49080,37 @@ data: ${JSON.stringify(data)}
48174
49080
  return router;
48175
49081
  }
48176
49082
 
49083
+ // ../../packages/api/src/routes/node-operations.ts
49084
+ var import_express13 = __toESM(require_express2(), 1);
49085
+ function asyncHandler10(fn) {
49086
+ return (req, res, next) => fn(req, res, next).catch(next);
49087
+ }
49088
+ function parseStatus(value) {
49089
+ if (value === "queued" || value === "running" || value === "succeeded" || value === "failed") return value;
49090
+ return void 0;
49091
+ }
49092
+ function createNodeOperationRoutes() {
49093
+ const router = (0, import_express13.Router)();
49094
+ router.get("/", asyncHandler10(async (req, res) => {
49095
+ const deps = req.app.locals.deps;
49096
+ const operations = getNodeOperationService(deps).list({
49097
+ nodeId: typeof req.query.nodeId === "string" ? req.query.nodeId : void 0,
49098
+ status: parseStatus(req.query.status),
49099
+ kind: typeof req.query.kind === "string" ? req.query.kind : void 0
49100
+ });
49101
+ res.json({ operations });
49102
+ }));
49103
+ router.get("/:id", asyncHandler10(async (req, res) => {
49104
+ const deps = req.app.locals.deps;
49105
+ const operation = getNodeOperationService(deps).get(req.params.id);
49106
+ if (!operation) {
49107
+ throw new MeshyError("NODE_NOT_FOUND", `Node operation ${req.params.id} not found`, 404);
49108
+ }
49109
+ res.json(operation);
49110
+ }));
49111
+ return router;
49112
+ }
49113
+
48177
49114
  // ../../packages/api/src/app/server.ts
48178
49115
  var JSON_BODY_LIMIT = "1mb";
48179
49116
  var JSON_BODY_LIMIT_LARGE = "25mb";
@@ -48211,11 +49148,18 @@ function isShareHostRequest(req, shareOrigin) {
48211
49148
  function isAllowedSharePath(pathname) {
48212
49149
  return pathname === "/favicon.ico" || pathname === "/api/shared" || pathname.startsWith("/api/shared/") || pathname === "/preview" || pathname.startsWith("/preview/") || pathname === "/shared" || pathname.startsWith("/shared/") || pathname === "/assets" || pathname.startsWith("/assets/");
48213
49150
  }
49151
+ function hasAuthorizationHeader(req) {
49152
+ const header = req.headers[MESHY_AUTHORIZATION_HEADER] ?? req.headers.authorization;
49153
+ if (Array.isArray(header)) {
49154
+ return header.some((value) => value.trim().length > 0);
49155
+ }
49156
+ return typeof header === "string" && header.trim().length > 0;
49157
+ }
48214
49158
  function resolveRuntimeBaseDir() {
48215
49159
  const entryPath = process.argv[1];
48216
49160
  if (typeof entryPath === "string" && entryPath.length > 0) {
48217
- const resolved = fs18.realpathSync(path19.resolve(entryPath));
48218
- return path19.dirname(resolved);
49161
+ const resolved = fs19.realpathSync(path20.resolve(entryPath));
49162
+ return path20.dirname(resolved);
48219
49163
  }
48220
49164
  return process.cwd();
48221
49165
  }
@@ -48223,25 +49167,25 @@ function resolveStaticDir(baseDir) {
48223
49167
  const envStaticDir = process.env.MESHY_STATIC_DIR;
48224
49168
  const candidateDirs = [
48225
49169
  envStaticDir,
48226
- path19.resolve(baseDir, "dashboard"),
48227
- path19.resolve(baseDir, "../dashboard"),
48228
- path19.resolve(baseDir, "../../dashboard/dist"),
48229
- path19.resolve(baseDir, "../../../packages/dashboard/dist"),
48230
- path19.resolve(baseDir, "../public"),
48231
- path19.resolve(baseDir, "../../packages/api/public"),
48232
- path19.resolve(baseDir, "../../../packages/api/public"),
48233
- path19.resolve(process.cwd(), "packages/dashboard/dist"),
48234
- path19.resolve(process.cwd(), "packages/api/public")
49170
+ path20.resolve(baseDir, "dashboard"),
49171
+ path20.resolve(baseDir, "../dashboard"),
49172
+ path20.resolve(baseDir, "../../dashboard/dist"),
49173
+ path20.resolve(baseDir, "../../../packages/dashboard/dist"),
49174
+ path20.resolve(baseDir, "../public"),
49175
+ path20.resolve(baseDir, "../../packages/api/public"),
49176
+ path20.resolve(baseDir, "../../../packages/api/public"),
49177
+ path20.resolve(process.cwd(), "packages/dashboard/dist"),
49178
+ path20.resolve(process.cwd(), "packages/api/public")
48235
49179
  ].filter((value) => typeof value === "string" && value.length > 0);
48236
49180
  for (const candidate of candidateDirs) {
48237
- if (fs18.existsSync(candidate)) {
49181
+ if (fs19.existsSync(candidate)) {
48238
49182
  return candidate;
48239
49183
  }
48240
49184
  }
48241
49185
  return null;
48242
49186
  }
48243
49187
  function createServer2(deps) {
48244
- const app = (0, import_express13.default)();
49188
+ const app = (0, import_express14.default)();
48245
49189
  app.locals.deps = deps;
48246
49190
  if (typeof deps.heartbeat.setNodeMessageHandler === "function") {
48247
49191
  deps.heartbeat.setNodeMessageHandler((message) => handleNodeMessage(deps, message));
@@ -48267,7 +49211,9 @@ function createServer2(deps) {
48267
49211
  }
48268
49212
  };
48269
49213
  const isApiRequest = (req) => req.path === "/api" || req.path.startsWith("/api/");
49214
+ const isPreviewRequest = (req) => req.path.startsWith("/preview/") || req.path.startsWith("/preview-open/");
48270
49215
  const canServeDashboard = (req) => !deps.config.validateBearerToken || isTrustedDashboardRequest(req, authConfig);
49216
+ const canServePreview = (req) => canServeDashboard(req) || hasAuthorizationHeader(req);
48271
49217
  app.use((req, res, next) => {
48272
49218
  if (!isShareHostRequest(req, deps.shareOrigin)) {
48273
49219
  next();
@@ -48282,9 +49228,9 @@ function createServer2(deps) {
48282
49228
  const runtimeBaseDir = resolveRuntimeBaseDir();
48283
49229
  const staticDir = resolveStaticDir(runtimeBaseDir);
48284
49230
  if (staticDir) {
48285
- const staticMiddleware = import_express13.default.static(staticDir);
49231
+ const staticMiddleware = import_express14.default.static(staticDir);
48286
49232
  app.use((req, res, next) => {
48287
- if (isApiRequest(req)) {
49233
+ if (isApiRequest(req) || isPreviewRequest(req)) {
48288
49234
  next();
48289
49235
  return;
48290
49236
  }
@@ -48295,29 +49241,33 @@ function createServer2(deps) {
48295
49241
  staticMiddleware(req, res, next);
48296
49242
  });
48297
49243
  }
48298
- app.use(import_express13.default.json({ limit: JSON_BODY_LIMIT }));
49244
+ app.use(import_express14.default.json({ limit: JSON_BODY_LIMIT }));
48299
49245
  app.use(createAuthMiddleware(authConfig));
48300
49246
  app.use((req, res, next) => {
48301
49247
  void (async () => {
48302
- if (!req.path.startsWith("/preview/")) {
49248
+ if (!isPreviewRequest(req)) {
48303
49249
  next();
48304
49250
  return;
48305
49251
  }
48306
- if (!canServeDashboard(req)) {
49252
+ if (!canServePreview(req)) {
48307
49253
  res.status(404).type("text/plain").send("Not Found");
48308
49254
  return;
48309
49255
  }
48310
49256
  if (deps.previewProxyManager && await handlePreviewProxyRequest(deps.previewProxyManager, deps.nodeRegistry, deps.logger, req, res)) {
48311
49257
  return;
48312
49258
  }
48313
- if (deps.previewSessionManager && handlePreviewRequest(deps.previewSessionManager, req, res)) {
49259
+ if (deps.previewSessionManager && await handlePreviewRequest(deps.previewSessionManager, req, res)) {
48314
49260
  return;
48315
49261
  }
48316
49262
  next();
48317
49263
  })().catch(next);
48318
49264
  });
48319
- app.use(createRoutingMiddleware(deps.dataRouter));
48320
- const largeBodyParser = import_express13.default.json({ limit: JSON_BODY_LIMIT_LARGE });
49265
+ app.use(createRoutingMiddleware({
49266
+ dataRouter: deps.dataRouter,
49267
+ taskEngine: deps.taskEngine,
49268
+ logger: deps.logger
49269
+ }));
49270
+ const largeBodyParser = import_express14.default.json({ limit: JSON_BODY_LIMIT_LARGE });
48321
49271
  app.use("/api/cluster", createClusterRoutes());
48322
49272
  app.use("/api/cluster-control", createClusterControlRoutes());
48323
49273
  app.use("/api/node", largeBodyParser, createNodeMessageRoutes());
@@ -48326,10 +49276,11 @@ function createServer2(deps) {
48326
49276
  app.use("/api/shared", createSharedRoutes());
48327
49277
  app.use("/api/worker", largeBodyParser, createWorkerRoutes());
48328
49278
  app.use("/api/system", createSystemRoutes());
49279
+ app.use("/api/node-operations", createNodeOperationRoutes());
48329
49280
  app.use("/api/events", createEventRoutes());
48330
49281
  if (staticDir) {
48331
- const indexPath = path19.join(staticDir, "index.html");
48332
- if (fs18.existsSync(indexPath)) {
49282
+ const indexPath = path20.join(staticDir, "index.html");
49283
+ if (fs19.existsSync(indexPath)) {
48333
49284
  app.get("*", (req, res, next) => {
48334
49285
  if (isApiRequest(req)) {
48335
49286
  next();
@@ -48725,8 +49676,8 @@ var terminalWriter = {
48725
49676
  };
48726
49677
 
48727
49678
  // src/startup.ts
48728
- var fs19 = __toESM(require("fs"), 1);
48729
- var path20 = __toESM(require("path"), 1);
49679
+ var fs20 = __toESM(require("fs"), 1);
49680
+ var path21 = __toESM(require("path"), 1);
48730
49681
  var readline = __toESM(require("readline/promises"), 1);
48731
49682
  var import_node_child_process11 = require("child_process");
48732
49683
  function getDefaultNodeName() {
@@ -48789,19 +49740,19 @@ function createDefaultCommandRunner(platform2) {
48789
49740
  };
48790
49741
  }
48791
49742
  function getNodeMetadataPath2(storagePath) {
48792
- return path20.join(storagePath, "metadata.json");
49743
+ return path21.join(storagePath, "metadata.json");
48793
49744
  }
48794
49745
  function readStartupMetadataFile(storagePath) {
48795
49746
  try {
48796
- const raw = JSON.parse(fs19.readFileSync(getNodeMetadataPath2(storagePath), "utf-8"));
49747
+ const raw = JSON.parse(fs20.readFileSync(getNodeMetadataPath2(storagePath), "utf-8"));
48797
49748
  return typeof raw === "object" && raw !== null ? raw : {};
48798
49749
  } catch {
48799
49750
  return {};
48800
49751
  }
48801
49752
  }
48802
49753
  function writeStartupMetadataFile(storagePath, metadata) {
48803
- fs19.mkdirSync(storagePath, { recursive: true });
48804
- fs19.writeFileSync(getNodeMetadataPath2(storagePath), JSON.stringify(metadata, null, 2) + "\n", "utf-8");
49754
+ fs20.mkdirSync(storagePath, { recursive: true });
49755
+ fs20.writeFileSync(getNodeMetadataPath2(storagePath), JSON.stringify(metadata, null, 2) + "\n", "utf-8");
48805
49756
  }
48806
49757
  function formatLocalDate2(now) {
48807
49758
  const year = now.getFullYear();
@@ -49040,9 +49991,9 @@ async function ensureStartupRequirements(storagePath, options = {}) {
49040
49991
  metadata
49041
49992
  };
49042
49993
  }
49043
- function loadConfigFile(path22) {
49994
+ function loadConfigFile(path23) {
49044
49995
  try {
49045
- const raw = fs19.readFileSync(path22, "utf-8");
49996
+ const raw = fs20.readFileSync(path23, "utf-8");
49046
49997
  return JSON.parse(raw);
49047
49998
  } catch {
49048
49999
  return {};
@@ -49220,26 +50171,26 @@ function formatLoadedStartMetadata(info, authEnabled) {
49220
50171
  }
49221
50172
 
49222
50173
  // src/runtime-metadata.ts
49223
- var fs20 = __toESM(require("fs"), 1);
49224
- var path21 = __toESM(require("path"), 1);
50174
+ var fs21 = __toESM(require("fs"), 1);
50175
+ var path22 = __toESM(require("path"), 1);
49225
50176
  var import_node_child_process12 = require("child_process");
49226
50177
  var runtimeDir = resolveRuntimeDir();
49227
50178
  var appRoot = resolveAppRoot(runtimeDir);
49228
- var repoRoot = path21.resolve(appRoot, "../..");
50179
+ var repoRoot = path22.resolve(appRoot, "../..");
49229
50180
  function resolveRuntimeDir() {
49230
50181
  const entryPath = process.argv[1];
49231
50182
  if (typeof entryPath === "string" && entryPath.length > 0) {
49232
50183
  try {
49233
- return path21.dirname(fs20.realpathSync(path21.resolve(entryPath)));
50184
+ return path22.dirname(fs21.realpathSync(path22.resolve(entryPath)));
49234
50185
  } catch {
49235
- return path21.dirname(path21.resolve(entryPath));
50186
+ return path22.dirname(path22.resolve(entryPath));
49236
50187
  }
49237
50188
  }
49238
50189
  return process.cwd();
49239
50190
  }
49240
50191
  function readJsonFile(filePath) {
49241
50192
  try {
49242
- return JSON.parse(fs20.readFileSync(filePath, "utf-8"));
50193
+ return JSON.parse(fs21.readFileSync(filePath, "utf-8"));
49243
50194
  } catch {
49244
50195
  return null;
49245
50196
  }
@@ -49249,9 +50200,9 @@ function readPackageManifest(filePath) {
49249
50200
  }
49250
50201
  function readEmbeddedRuntimeMetadata() {
49251
50202
  const candidates = [
49252
- path21.join(appRoot, "runtime-metadata.json"),
49253
- path21.join(runtimeDir, "runtime-metadata.json"),
49254
- path21.resolve(process.cwd(), "apps/node/dist/runtime-metadata.json")
50203
+ path22.join(appRoot, "runtime-metadata.json"),
50204
+ path22.join(runtimeDir, "runtime-metadata.json"),
50205
+ path22.resolve(process.cwd(), "apps/node/dist/runtime-metadata.json")
49255
50206
  ];
49256
50207
  for (const candidate of candidates) {
49257
50208
  const metadata = readJsonFile(candidate);
@@ -49264,23 +50215,23 @@ function readEmbeddedRuntimeMetadata() {
49264
50215
  function resolveAppRoot(baseDir) {
49265
50216
  const candidates = [
49266
50217
  baseDir,
49267
- path21.resolve(baseDir, ".."),
49268
- path21.resolve(process.cwd(), "apps/node/dist"),
49269
- path21.resolve(process.cwd(), "apps/node"),
50218
+ path22.resolve(baseDir, ".."),
50219
+ path22.resolve(process.cwd(), "apps/node/dist"),
50220
+ path22.resolve(process.cwd(), "apps/node"),
49270
50221
  process.cwd()
49271
50222
  ];
49272
50223
  for (const candidate of candidates) {
49273
- const manifest = readPackageManifest(path21.join(candidate, "package.json"));
50224
+ const manifest = readPackageManifest(path22.join(candidate, "package.json"));
49274
50225
  if (manifest?.name === "@meshy/node" || manifest?.name === "meshy-node") {
49275
50226
  return candidate;
49276
50227
  }
49277
50228
  }
49278
50229
  for (const candidate of candidates) {
49279
- if (fs20.existsSync(path21.join(candidate, "package.json"))) {
50230
+ if (fs21.existsSync(path22.join(candidate, "package.json"))) {
49280
50231
  return candidate;
49281
50232
  }
49282
50233
  }
49283
- return path21.resolve(baseDir, "..");
50234
+ return path22.resolve(baseDir, "..");
49284
50235
  }
49285
50236
  function toPackageInfo(filePath) {
49286
50237
  const manifest = readPackageManifest(filePath);
@@ -49340,8 +50291,8 @@ function buildRuntimeMetadata(storagePath) {
49340
50291
  components: startupRequirements.components
49341
50292
  };
49342
50293
  }
49343
- const appPackage = toPackageInfo(path21.join(appRoot, "package.json"));
49344
- const workspaceManifest = readPackageManifest(path21.join(repoRoot, "package.json"));
50294
+ const appPackage = toPackageInfo(path22.join(appRoot, "package.json"));
50295
+ const workspaceManifest = readPackageManifest(path22.join(repoRoot, "package.json"));
49345
50296
  return {
49346
50297
  packageName: appPackage?.name ?? "meshy",
49347
50298
  packageVersion: appPackage?.version ?? "0.1.0",
@@ -49349,11 +50300,11 @@ function buildRuntimeMetadata(storagePath) {
49349
50300
  startupRequirementsLastCheckedOn: startupRequirements.lastCheckedOn,
49350
50301
  components: startupRequirements.components,
49351
50302
  packages: {
49352
- workspace: toPackageInfo(path21.join(repoRoot, "package.json")),
50303
+ workspace: toPackageInfo(path22.join(repoRoot, "package.json")),
49353
50304
  node: appPackage,
49354
- core: toPackageInfo(path21.join(repoRoot, "packages/core/package.json")),
49355
- dashboard: toPackageInfo(path21.join(repoRoot, "packages/dashboard/package.json")),
49356
- api: toPackageInfo(path21.join(repoRoot, "packages/api/package.json"))
50305
+ core: toPackageInfo(path22.join(repoRoot, "packages/core/package.json")),
50306
+ dashboard: toPackageInfo(path22.join(repoRoot, "packages/dashboard/package.json")),
50307
+ api: toPackageInfo(path22.join(repoRoot, "packages/api/package.json"))
49357
50308
  },
49358
50309
  repository: {
49359
50310
  url: normalizeRepositoryUrl(readGitValue(["config", "--get", "remote.upstream.url"])) ?? normalizeRepositoryUrl(readGitValue(["config", "--get", "remote.origin.url"])) ?? readRepositoryUrlFromManifest(workspaceManifest),