mellos-mapping 0.22.1 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.mjs CHANGED
@@ -15,9 +15,9 @@ var __export = (target, all) => {
15
15
  };
16
16
  var __copyProps = (to, from, except, desc) => {
17
17
  if (from && typeof from === "object" || typeof from === "function") {
18
- for (let key of __getOwnPropNames(from))
19
- if (!__hasOwnProp.call(to, key) && key !== except)
20
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ for (let key2 of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key2) && key2 !== except)
20
+ __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
21
21
  }
22
22
  return to;
23
23
  };
@@ -166,15 +166,15 @@ var require_code = __commonJS({
166
166
  return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
167
167
  }
168
168
  exports.safeStringify = safeStringify;
169
- function getProperty(key) {
170
- return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`;
169
+ function getProperty(key2) {
170
+ return typeof key2 == "string" && exports.IDENTIFIER.test(key2) ? new _Code(`.${key2}`) : _`[${key2}]`;
171
171
  }
172
172
  exports.getProperty = getProperty;
173
- function getEsmExportName(key) {
174
- if (typeof key == "string" && exports.IDENTIFIER.test(key)) {
175
- return new _Code(`${key}`);
173
+ function getEsmExportName(key2) {
174
+ if (typeof key2 == "string" && exports.IDENTIFIER.test(key2)) {
175
+ return new _Code(`${key2}`);
176
176
  }
177
- throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
177
+ throw new Error(`CodeGen: invalid export name: ${key2}, use explicit $id name mapping`);
178
178
  }
179
179
  exports.getEsmExportName = getEsmExportName;
180
180
  function regexpCode(rx) {
@@ -801,11 +801,11 @@ var require_codegen = __commonJS({
801
801
  // returns code for object literal for the passed argument list of key-value pairs
802
802
  object(...keyValues) {
803
803
  const code = ["{"];
804
- for (const [key, value] of keyValues) {
804
+ for (const [key2, value] of keyValues) {
805
805
  if (code.length > 1)
806
806
  code.push(",");
807
- code.push(key);
808
- if (key !== value || this.opts.es5) {
807
+ code.push(key2);
808
+ if (key2 !== value || this.opts.es5) {
809
809
  code.push(":");
810
810
  (0, code_1.addCodeArg)(code, value);
811
811
  }
@@ -1058,10 +1058,10 @@ var require_util = __commonJS({
1058
1058
  var codegen_1 = require_codegen();
1059
1059
  var code_1 = require_code();
1060
1060
  function toHash(arr) {
1061
- const hash = {};
1061
+ const hash2 = {};
1062
1062
  for (const item of arr)
1063
- hash[item] = true;
1064
- return hash;
1063
+ hash2[item] = true;
1064
+ return hash2;
1065
1065
  }
1066
1066
  exports.toHash = toHash;
1067
1067
  function alwaysValidSchema(it, schema) {
@@ -1080,17 +1080,17 @@ var require_util = __commonJS({
1080
1080
  if (typeof schema === "boolean")
1081
1081
  return;
1082
1082
  const rules = self.RULES.keywords;
1083
- for (const key in schema) {
1084
- if (!rules[key])
1085
- checkStrictMode(it, `unknown keyword: "${key}"`);
1083
+ for (const key2 in schema) {
1084
+ if (!rules[key2])
1085
+ checkStrictMode(it, `unknown keyword: "${key2}"`);
1086
1086
  }
1087
1087
  }
1088
1088
  exports.checkUnknownRules = checkUnknownRules;
1089
1089
  function schemaHasRules(schema, rules) {
1090
1090
  if (typeof schema == "boolean")
1091
1091
  return !schema;
1092
- for (const key in schema)
1093
- if (rules[key])
1092
+ for (const key2 in schema)
1093
+ if (rules[key2])
1094
1094
  return true;
1095
1095
  return false;
1096
1096
  }
@@ -1098,8 +1098,8 @@ var require_util = __commonJS({
1098
1098
  function schemaHasRulesButRef(schema, RULES) {
1099
1099
  if (typeof schema == "boolean")
1100
1100
  return !schema;
1101
- for (const key in schema)
1102
- if (key !== "$ref" && RULES.all[key])
1101
+ for (const key2 in schema)
1102
+ if (key2 !== "$ref" && RULES.all[key2])
1103
1103
  return true;
1104
1104
  return false;
1105
1105
  }
@@ -1677,8 +1677,8 @@ var require_defaults = __commonJS({
1677
1677
  function assignDefaults(it, ty) {
1678
1678
  const { properties, items } = it.schema;
1679
1679
  if (ty === "object" && properties) {
1680
- for (const key in properties) {
1681
- assignDefault(it, key, properties[key].default);
1680
+ for (const key2 in properties) {
1681
+ assignDefault(it, key2, properties[key2].default);
1682
1682
  }
1683
1683
  } else if (ty === "array" && Array.isArray(items)) {
1684
1684
  items.forEach((sch, i) => assignDefault(it, i, sch.default));
@@ -1760,7 +1760,7 @@ var require_code2 = __commonJS({
1760
1760
  return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
1761
1761
  }
1762
1762
  exports.schemaProperties = schemaProperties;
1763
- function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
1763
+ function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context2, passSchema) {
1764
1764
  const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
1765
1765
  const valCxt = [
1766
1766
  [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
@@ -1771,7 +1771,7 @@ var require_code2 = __commonJS({
1771
1771
  if (it.opts.dynamicRef)
1772
1772
  valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
1773
1773
  const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
1774
- return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`;
1774
+ return context2 !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context2}, ${args})` : (0, codegen_1._)`${func}(${args})`;
1775
1775
  }
1776
1776
  exports.callValidateCode = callValidateCode;
1777
1777
  var newRegExp = (0, codegen_1._)`new RegExp`;
@@ -2062,8 +2062,8 @@ var require_fast_deep_equal = __commonJS({
2062
2062
  for (i = length; i-- !== 0; )
2063
2063
  if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
2064
2064
  for (i = length; i-- !== 0; ) {
2065
- var key = keys[i];
2066
- if (!equal(a[key], b[key])) return false;
2065
+ var key2 = keys[i];
2066
+ if (!equal(a[key2], b[key2])) return false;
2067
2067
  }
2068
2068
  return true;
2069
2069
  }
@@ -2135,20 +2135,20 @@ var require_json_schema_traverse = __commonJS({
2135
2135
  function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
2136
2136
  if (schema && typeof schema == "object" && !Array.isArray(schema)) {
2137
2137
  pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
2138
- for (var key in schema) {
2139
- var sch = schema[key];
2138
+ for (var key2 in schema) {
2139
+ var sch = schema[key2];
2140
2140
  if (Array.isArray(sch)) {
2141
- if (key in traverse.arrayKeywords) {
2141
+ if (key2 in traverse.arrayKeywords) {
2142
2142
  for (var i = 0; i < sch.length; i++)
2143
- _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i);
2143
+ _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key2 + "/" + i, rootSchema, jsonPtr, key2, schema, i);
2144
2144
  }
2145
- } else if (key in traverse.propsKeywords) {
2145
+ } else if (key2 in traverse.propsKeywords) {
2146
2146
  if (sch && typeof sch == "object") {
2147
2147
  for (var prop in sch)
2148
- _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
2148
+ _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key2 + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key2, schema, prop);
2149
2149
  }
2150
- } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) {
2151
- _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
2150
+ } else if (key2 in traverse.keywords || opts.allKeys && !(key2 in traverse.skipKeywords)) {
2151
+ _traverse(opts, pre, post, sch, jsonPtr + "/" + key2, rootSchema, jsonPtr, key2, schema);
2152
2152
  }
2153
2153
  }
2154
2154
  post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
@@ -2205,10 +2205,10 @@ var require_resolve = __commonJS({
2205
2205
  "$dynamicAnchor"
2206
2206
  ]);
2207
2207
  function hasRef(schema) {
2208
- for (const key in schema) {
2209
- if (REF_KEYWORDS.has(key))
2208
+ for (const key2 in schema) {
2209
+ if (REF_KEYWORDS.has(key2))
2210
2210
  return true;
2211
- const sch = schema[key];
2211
+ const sch = schema[key2];
2212
2212
  if (Array.isArray(sch) && sch.some(hasRef))
2213
2213
  return true;
2214
2214
  if (typeof sch == "object" && hasRef(sch))
@@ -2218,14 +2218,14 @@ var require_resolve = __commonJS({
2218
2218
  }
2219
2219
  function countKeys(schema) {
2220
2220
  let count = 0;
2221
- for (const key in schema) {
2222
- if (key === "$ref")
2221
+ for (const key2 in schema) {
2222
+ if (key2 === "$ref")
2223
2223
  return Infinity;
2224
2224
  count++;
2225
- if (SIMPLE_INLINED.has(key))
2225
+ if (SIMPLE_INLINED.has(key2))
2226
2226
  continue;
2227
- if (typeof schema[key] == "object") {
2228
- (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch));
2227
+ if (typeof schema[key2] == "object") {
2228
+ (0, util_1.eachItem)(schema[key2], (sch) => count += countKeys(sch));
2229
2229
  }
2230
2230
  if (count === Infinity)
2231
2231
  return Infinity;
@@ -2414,8 +2414,8 @@ var require_validate = __commonJS({
2414
2414
  function schemaCxtHasRules({ schema, self }) {
2415
2415
  if (typeof schema == "boolean")
2416
2416
  return !schema;
2417
- for (const key in schema)
2418
- if (self.RULES.all[key])
2417
+ for (const key2 in schema)
2418
+ if (self.RULES.all[key2])
2419
2419
  return true;
2420
2420
  return false;
2421
2421
  }
@@ -2981,7 +2981,7 @@ var require_compile = __commonJS({
2981
2981
  const schOrFunc = root.refs[ref];
2982
2982
  if (schOrFunc)
2983
2983
  return schOrFunc;
2984
- let _sch = resolve2.call(this, root, ref);
2984
+ let _sch = resolve4.call(this, root, ref);
2985
2985
  if (_sch === void 0) {
2986
2986
  const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref];
2987
2987
  const { schemaId } = this.opts;
@@ -3008,7 +3008,7 @@ var require_compile = __commonJS({
3008
3008
  function sameSchemaEnv(s1, s2) {
3009
3009
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
3010
3010
  }
3011
- function resolve2(root, ref) {
3011
+ function resolve4(root, ref) {
3012
3012
  let sch;
3013
3013
  while (typeof (sch = this.refs[ref]) == "string")
3014
3014
  ref = sch;
@@ -3838,7 +3838,7 @@ var require_fast_uri = __commonJS({
3838
3838
  }
3839
3839
  return uri;
3840
3840
  }
3841
- function resolve2(baseURI, relativeURI, options) {
3841
+ function resolve4(baseURI, relativeURI, options) {
3842
3842
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
3843
3843
  const {
3844
3844
  parsed: baseParsed,
@@ -3871,49 +3871,49 @@ var require_fast_uri = __commonJS({
3871
3871
  schemelessOptions.skipEscape = true;
3872
3872
  return serialize(resolved, schemelessOptions);
3873
3873
  }
3874
- function resolveComponent(base, relative, options, skipNormalization) {
3874
+ function resolveComponent(base, relative2, options, skipNormalization) {
3875
3875
  const target = {};
3876
3876
  if (!skipNormalization) {
3877
3877
  base = parse3(serialize(base, options), options);
3878
- relative = parse3(serialize(relative, options), options);
3878
+ relative2 = parse3(serialize(relative2, options), options);
3879
3879
  }
3880
3880
  options = options || {};
3881
- if (!options.tolerant && relative.scheme) {
3882
- target.scheme = relative.scheme;
3883
- target.userinfo = relative.userinfo;
3884
- target.host = relative.host;
3885
- target.port = relative.port;
3886
- target.path = removeDotSegments(relative.path || "");
3887
- target.query = relative.query;
3881
+ if (!options.tolerant && relative2.scheme) {
3882
+ target.scheme = relative2.scheme;
3883
+ target.userinfo = relative2.userinfo;
3884
+ target.host = relative2.host;
3885
+ target.port = relative2.port;
3886
+ target.path = removeDotSegments(relative2.path || "");
3887
+ target.query = relative2.query;
3888
3888
  } else {
3889
- if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) {
3890
- target.userinfo = relative.userinfo;
3891
- target.host = relative.host;
3892
- target.port = relative.port;
3893
- target.path = removeDotSegments(relative.path || "");
3894
- target.query = relative.query;
3889
+ if (relative2.userinfo !== void 0 || relative2.host !== void 0 || relative2.port !== void 0) {
3890
+ target.userinfo = relative2.userinfo;
3891
+ target.host = relative2.host;
3892
+ target.port = relative2.port;
3893
+ target.path = removeDotSegments(relative2.path || "");
3894
+ target.query = relative2.query;
3895
3895
  } else {
3896
- if (!relative.path) {
3896
+ if (!relative2.path) {
3897
3897
  target.path = base.path;
3898
- if (relative.query !== void 0) {
3899
- target.query = relative.query;
3898
+ if (relative2.query !== void 0) {
3899
+ target.query = relative2.query;
3900
3900
  } else {
3901
3901
  target.query = base.query;
3902
3902
  }
3903
3903
  } else {
3904
- if (relative.path[0] === "/") {
3905
- target.path = removeDotSegments(relative.path);
3904
+ if (relative2.path[0] === "/") {
3905
+ target.path = removeDotSegments(relative2.path);
3906
3906
  } else {
3907
3907
  if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) {
3908
- target.path = "/" + relative.path;
3908
+ target.path = "/" + relative2.path;
3909
3909
  } else if (!base.path) {
3910
- target.path = relative.path;
3910
+ target.path = relative2.path;
3911
3911
  } else {
3912
- target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
3912
+ target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative2.path;
3913
3913
  }
3914
3914
  target.path = removeDotSegments(target.path);
3915
3915
  }
3916
- target.query = relative.query;
3916
+ target.query = relative2.query;
3917
3917
  }
3918
3918
  target.userinfo = base.userinfo;
3919
3919
  target.host = base.host;
@@ -3921,7 +3921,7 @@ var require_fast_uri = __commonJS({
3921
3921
  }
3922
3922
  target.scheme = base.scheme;
3923
3923
  }
3924
- target.fragment = relative.fragment;
3924
+ target.fragment = relative2.fragment;
3925
3925
  return target;
3926
3926
  }
3927
3927
  function equal(uriA, uriB, options) {
@@ -4206,7 +4206,7 @@ var require_fast_uri = __commonJS({
4206
4206
  var fastUri = {
4207
4207
  SCHEMES,
4208
4208
  normalize,
4209
- resolve: resolve2,
4209
+ resolve: resolve4,
4210
4210
  resolveComponent,
4211
4211
  equal,
4212
4212
  serialize,
@@ -4453,7 +4453,7 @@ var require_core = __commonJS({
4453
4453
  }
4454
4454
  }
4455
4455
  // Adds schema to the instance
4456
- addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) {
4456
+ addSchema(schema, key2, _meta, _validateSchema = this.opts.validateSchema) {
4457
4457
  if (Array.isArray(schema)) {
4458
4458
  for (const sch of schema)
4459
4459
  this.addSchema(sch, void 0, _meta, _validateSchema);
@@ -4467,15 +4467,15 @@ var require_core = __commonJS({
4467
4467
  throw new Error(`schema ${schemaId} must be string`);
4468
4468
  }
4469
4469
  }
4470
- key = (0, resolve_1.normalizeId)(key || id2);
4471
- this._checkUnique(key);
4472
- this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
4470
+ key2 = (0, resolve_1.normalizeId)(key2 || id2);
4471
+ this._checkUnique(key2);
4472
+ this.schemas[key2] = this._addSchema(schema, _meta, key2, _validateSchema, true);
4473
4473
  return this;
4474
4474
  }
4475
4475
  // Add schema that will be used to validate other schemas
4476
4476
  // options in META_IGNORE_OPTIONS are alway set to false
4477
- addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) {
4478
- this.addSchema(schema, key, true, _validateSchema);
4477
+ addMetaSchema(schema, key2, _validateSchema = this.opts.validateSchema) {
4478
+ this.addSchema(schema, key2, true, _validateSchema);
4479
4479
  return this;
4480
4480
  }
4481
4481
  // Validate schema against its meta-schema
@@ -4631,14 +4631,14 @@ var require_core = __commonJS({
4631
4631
  let keywords = metaSchema;
4632
4632
  for (const seg of segments)
4633
4633
  keywords = keywords[seg];
4634
- for (const key in rules) {
4635
- const rule = rules[key];
4634
+ for (const key2 in rules) {
4635
+ const rule = rules[key2];
4636
4636
  if (typeof rule != "object")
4637
4637
  continue;
4638
4638
  const { $data } = rule.definition;
4639
- const schema = keywords[key];
4639
+ const schema = keywords[key2];
4640
4640
  if ($data && schema)
4641
- keywords[key] = schemaOrData(schema);
4641
+ keywords[key2] = schemaOrData(schema);
4642
4642
  }
4643
4643
  }
4644
4644
  return metaSchema;
@@ -4711,10 +4711,10 @@ var require_core = __commonJS({
4711
4711
  Ajv2.MissingRefError = ref_error_1.default;
4712
4712
  exports.default = Ajv2;
4713
4713
  function checkOptions(checkOpts, options, msg, log = "error") {
4714
- for (const key in checkOpts) {
4715
- const opt = key;
4714
+ for (const key2 in checkOpts) {
4715
+ const opt = key2;
4716
4716
  if (opt in options)
4717
- this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
4717
+ this.logger[log](`${msg}: option ${key2}. ${checkOpts[opt]}`);
4718
4718
  }
4719
4719
  }
4720
4720
  function getSchEnv(keyRef) {
@@ -4728,8 +4728,8 @@ var require_core = __commonJS({
4728
4728
  if (Array.isArray(optsSchemas))
4729
4729
  this.addSchema(optsSchemas);
4730
4730
  else
4731
- for (const key in optsSchemas)
4732
- this.addSchema(optsSchemas[key], key);
4731
+ for (const key2 in optsSchemas)
4732
+ this.addSchema(optsSchemas[key2], key2);
4733
4733
  }
4734
4734
  function addInitialFormats() {
4735
4735
  for (const name in this.opts.formats) {
@@ -5777,11 +5777,11 @@ var require_dependencies = __commonJS({
5777
5777
  function splitDependencies({ schema }) {
5778
5778
  const propertyDeps = {};
5779
5779
  const schemaDeps = {};
5780
- for (const key in schema) {
5781
- if (key === "__proto__")
5780
+ for (const key2 in schema) {
5781
+ if (key2 === "__proto__")
5782
5782
  continue;
5783
- const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
5784
- deps[key] = schema[key];
5783
+ const deps = Array.isArray(schema[key2]) ? propertyDeps : schemaDeps;
5784
+ deps[key2] = schema[key2];
5785
5785
  }
5786
5786
  return [propertyDeps, schemaDeps];
5787
5787
  }
@@ -5858,13 +5858,13 @@ var require_propertyNames = __commonJS({
5858
5858
  if ((0, util_1.alwaysValidSchema)(it, schema))
5859
5859
  return;
5860
5860
  const valid = gen.name("valid");
5861
- gen.forIn("key", data, (key) => {
5862
- cxt.setParams({ propertyName: key });
5861
+ gen.forIn("key", data, (key2) => {
5862
+ cxt.setParams({ propertyName: key2 });
5863
5863
  cxt.subschema({
5864
5864
  keyword: "propertyNames",
5865
- data: key,
5865
+ data: key2,
5866
5866
  dataTypes: ["string"],
5867
- propertyName: key,
5867
+ propertyName: key2,
5868
5868
  compositeRule: true
5869
5869
  }, valid);
5870
5870
  gen.if((0, codegen_1.not)(valid), () => {
@@ -5913,38 +5913,38 @@ var require_additionalProperties = __commonJS({
5913
5913
  checkAdditionalProperties();
5914
5914
  cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
5915
5915
  function checkAdditionalProperties() {
5916
- gen.forIn("key", data, (key) => {
5916
+ gen.forIn("key", data, (key2) => {
5917
5917
  if (!props.length && !patProps.length)
5918
- additionalPropertyCode(key);
5918
+ additionalPropertyCode(key2);
5919
5919
  else
5920
- gen.if(isAdditional(key), () => additionalPropertyCode(key));
5920
+ gen.if(isAdditional(key2), () => additionalPropertyCode(key2));
5921
5921
  });
5922
5922
  }
5923
- function isAdditional(key) {
5923
+ function isAdditional(key2) {
5924
5924
  let definedProp;
5925
5925
  if (props.length > 8) {
5926
5926
  const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
5927
- definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
5927
+ definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key2);
5928
5928
  } else if (props.length) {
5929
- definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`));
5929
+ definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key2} === ${p}`));
5930
5930
  } else {
5931
5931
  definedProp = codegen_1.nil;
5932
5932
  }
5933
5933
  if (patProps.length) {
5934
- definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
5934
+ definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key2})`));
5935
5935
  }
5936
5936
  return (0, codegen_1.not)(definedProp);
5937
5937
  }
5938
- function deleteAdditional(key) {
5939
- gen.code((0, codegen_1._)`delete ${data}[${key}]`);
5938
+ function deleteAdditional(key2) {
5939
+ gen.code((0, codegen_1._)`delete ${data}[${key2}]`);
5940
5940
  }
5941
- function additionalPropertyCode(key) {
5941
+ function additionalPropertyCode(key2) {
5942
5942
  if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) {
5943
- deleteAdditional(key);
5943
+ deleteAdditional(key2);
5944
5944
  return;
5945
5945
  }
5946
5946
  if (schema === false) {
5947
- cxt.setParams({ additionalProperty: key });
5947
+ cxt.setParams({ additionalProperty: key2 });
5948
5948
  cxt.error();
5949
5949
  if (!allErrors)
5950
5950
  gen.break();
@@ -5953,22 +5953,22 @@ var require_additionalProperties = __commonJS({
5953
5953
  if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
5954
5954
  const valid = gen.name("valid");
5955
5955
  if (opts.removeAdditional === "failing") {
5956
- applyAdditionalSchema(key, valid, false);
5956
+ applyAdditionalSchema(key2, valid, false);
5957
5957
  gen.if((0, codegen_1.not)(valid), () => {
5958
5958
  cxt.reset();
5959
- deleteAdditional(key);
5959
+ deleteAdditional(key2);
5960
5960
  });
5961
5961
  } else {
5962
- applyAdditionalSchema(key, valid);
5962
+ applyAdditionalSchema(key2, valid);
5963
5963
  if (!allErrors)
5964
5964
  gen.if((0, codegen_1.not)(valid), () => gen.break());
5965
5965
  }
5966
5966
  }
5967
5967
  }
5968
- function applyAdditionalSchema(key, valid, errors) {
5968
+ function applyAdditionalSchema(key2, valid, errors) {
5969
5969
  const subschema = {
5970
5970
  keyword: "additionalProperties",
5971
- dataProp: key,
5971
+ dataProp: key2,
5972
5972
  dataPropType: util_1.Type.Str
5973
5973
  };
5974
5974
  if (errors === false) {
@@ -6093,19 +6093,19 @@ var require_patternProperties = __commonJS({
6093
6093
  }
6094
6094
  }
6095
6095
  function validateProperties(pat) {
6096
- gen.forIn("key", data, (key) => {
6097
- gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
6096
+ gen.forIn("key", data, (key2) => {
6097
+ gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key2})`, () => {
6098
6098
  const alwaysValid = alwaysValidPatterns.includes(pat);
6099
6099
  if (!alwaysValid) {
6100
6100
  cxt.subschema({
6101
6101
  keyword: "patternProperties",
6102
6102
  schemaProp: pat,
6103
- dataProp: key,
6103
+ dataProp: key2,
6104
6104
  dataPropType: util_2.Type.Str
6105
6105
  }, valid);
6106
6106
  }
6107
6107
  if (it.opts.unevaluated && props !== true) {
6108
- gen.assign((0, codegen_1._)`${props}[${key}]`, true);
6108
+ gen.assign((0, codegen_1._)`${props}[${key2}]`, true);
6109
6109
  } else if (!alwaysValid && !it.allErrors) {
6110
6110
  gen.if((0, codegen_1.not)(valid), () => gen.break());
6111
6111
  }
@@ -7196,9 +7196,9 @@ var require_dist = __commonJS({
7196
7196
  });
7197
7197
 
7198
7198
  // src/server/server.ts
7199
- import { existsSync as existsSync6, realpathSync as realpathSync2 } from "node:fs";
7200
- import { homedir } from "node:os";
7201
- import { join as join8 } from "node:path";
7199
+ import { existsSync as existsSync8, realpathSync as realpathSync4 } from "node:fs";
7200
+ import { homedir as homedir2 } from "node:os";
7201
+ import { join as join10 } from "node:path";
7202
7202
  import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";
7203
7203
 
7204
7204
  // node_modules/zod/v3/external.js
@@ -7347,9 +7347,9 @@ var util;
7347
7347
  };
7348
7348
  util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object3) => {
7349
7349
  const keys = [];
7350
- for (const key in object3) {
7351
- if (Object.prototype.hasOwnProperty.call(object3, key)) {
7352
- keys.push(key);
7350
+ for (const key2 in object3) {
7351
+ if (Object.prototype.hasOwnProperty.call(object3, key2)) {
7352
+ keys.push(key2);
7353
7353
  }
7354
7354
  }
7355
7355
  return keys;
@@ -7749,10 +7749,10 @@ var ParseStatus = class _ParseStatus {
7749
7749
  static async mergeObjectAsync(status2, pairs) {
7750
7750
  const syncPairs = [];
7751
7751
  for (const pair of pairs) {
7752
- const key = await pair.key;
7752
+ const key2 = await pair.key;
7753
7753
  const value = await pair.value;
7754
7754
  syncPairs.push({
7755
- key,
7755
+ key: key2,
7756
7756
  value
7757
7757
  });
7758
7758
  }
@@ -7761,17 +7761,17 @@ var ParseStatus = class _ParseStatus {
7761
7761
  static mergeObjectSync(status2, pairs) {
7762
7762
  const finalObject = {};
7763
7763
  for (const pair of pairs) {
7764
- const { key, value } = pair;
7765
- if (key.status === "aborted")
7764
+ const { key: key2, value } = pair;
7765
+ if (key2.status === "aborted")
7766
7766
  return INVALID;
7767
7767
  if (value.status === "aborted")
7768
7768
  return INVALID;
7769
- if (key.status === "dirty")
7769
+ if (key2.status === "dirty")
7770
7770
  status2.dirty();
7771
7771
  if (value.status === "dirty")
7772
7772
  status2.dirty();
7773
- if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
7774
- finalObject[key.value] = value.value;
7773
+ if (key2.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
7774
+ finalObject[key2.value] = value.value;
7775
7775
  }
7776
7776
  }
7777
7777
  return { status: status2.value, value: finalObject };
@@ -7796,12 +7796,12 @@ var errorUtil;
7796
7796
 
7797
7797
  // node_modules/zod/v3/types.js
7798
7798
  var ParseInputLazyPath = class {
7799
- constructor(parent, value, path, key) {
7799
+ constructor(parent, value, path, key2) {
7800
7800
  this._cachedPath = [];
7801
7801
  this.parent = parent;
7802
7802
  this.data = value;
7803
7803
  this._path = path;
7804
- this._key = key;
7804
+ this._key = key2;
7805
7805
  }
7806
7806
  get path() {
7807
7807
  if (!this._cachedPath.length) {
@@ -9546,9 +9546,9 @@ ZodArray.create = (schema, params) => {
9546
9546
  function deepPartialify(schema) {
9547
9547
  if (schema instanceof ZodObject) {
9548
9548
  const newShape = {};
9549
- for (const key in schema.shape) {
9550
- const fieldSchema = schema.shape[key];
9551
- newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
9549
+ for (const key2 in schema.shape) {
9550
+ const fieldSchema = schema.shape[key2];
9551
+ newShape[key2] = ZodOptional.create(deepPartialify(fieldSchema));
9552
9552
  }
9553
9553
  return new ZodObject({
9554
9554
  ...schema._def,
@@ -9599,29 +9599,29 @@ var ZodObject = class _ZodObject extends ZodType {
9599
9599
  const { shape, keys: shapeKeys } = this._getCached();
9600
9600
  const extraKeys = [];
9601
9601
  if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
9602
- for (const key in ctx.data) {
9603
- if (!shapeKeys.includes(key)) {
9604
- extraKeys.push(key);
9602
+ for (const key2 in ctx.data) {
9603
+ if (!shapeKeys.includes(key2)) {
9604
+ extraKeys.push(key2);
9605
9605
  }
9606
9606
  }
9607
9607
  }
9608
9608
  const pairs = [];
9609
- for (const key of shapeKeys) {
9610
- const keyValidator = shape[key];
9611
- const value = ctx.data[key];
9609
+ for (const key2 of shapeKeys) {
9610
+ const keyValidator = shape[key2];
9611
+ const value = ctx.data[key2];
9612
9612
  pairs.push({
9613
- key: { status: "valid", value: key },
9614
- value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
9615
- alwaysSet: key in ctx.data
9613
+ key: { status: "valid", value: key2 },
9614
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key2)),
9615
+ alwaysSet: key2 in ctx.data
9616
9616
  });
9617
9617
  }
9618
9618
  if (this._def.catchall instanceof ZodNever) {
9619
9619
  const unknownKeys = this._def.unknownKeys;
9620
9620
  if (unknownKeys === "passthrough") {
9621
- for (const key of extraKeys) {
9621
+ for (const key2 of extraKeys) {
9622
9622
  pairs.push({
9623
- key: { status: "valid", value: key },
9624
- value: { status: "valid", value: ctx.data[key] }
9623
+ key: { status: "valid", value: key2 },
9624
+ value: { status: "valid", value: ctx.data[key2] }
9625
9625
  });
9626
9626
  }
9627
9627
  } else if (unknownKeys === "strict") {
@@ -9638,15 +9638,15 @@ var ZodObject = class _ZodObject extends ZodType {
9638
9638
  }
9639
9639
  } else {
9640
9640
  const catchall = this._def.catchall;
9641
- for (const key of extraKeys) {
9642
- const value = ctx.data[key];
9641
+ for (const key2 of extraKeys) {
9642
+ const value = ctx.data[key2];
9643
9643
  pairs.push({
9644
- key: { status: "valid", value: key },
9644
+ key: { status: "valid", value: key2 },
9645
9645
  value: catchall._parse(
9646
- new ParseInputLazyPath(ctx, value, ctx.path, key)
9646
+ new ParseInputLazyPath(ctx, value, ctx.path, key2)
9647
9647
  //, ctx.child(key), value, getParsedType(value)
9648
9648
  ),
9649
- alwaysSet: key in ctx.data
9649
+ alwaysSet: key2 in ctx.data
9650
9650
  });
9651
9651
  }
9652
9652
  }
@@ -9654,10 +9654,10 @@ var ZodObject = class _ZodObject extends ZodType {
9654
9654
  return Promise.resolve().then(async () => {
9655
9655
  const syncPairs = [];
9656
9656
  for (const pair of pairs) {
9657
- const key = await pair.key;
9657
+ const key2 = await pair.key;
9658
9658
  const value = await pair.value;
9659
9659
  syncPairs.push({
9660
- key,
9660
+ key: key2,
9661
9661
  value,
9662
9662
  alwaysSet: pair.alwaysSet
9663
9663
  });
@@ -9782,8 +9782,8 @@ var ZodObject = class _ZodObject extends ZodType {
9782
9782
  // }) as any;
9783
9783
  // return merged;
9784
9784
  // }
9785
- setKey(key, schema) {
9786
- return this.augment({ [key]: schema });
9785
+ setKey(key2, schema) {
9786
+ return this.augment({ [key2]: schema });
9787
9787
  }
9788
9788
  // merge<Incoming extends AnyZodObject>(
9789
9789
  // merging: Incoming
@@ -9814,9 +9814,9 @@ var ZodObject = class _ZodObject extends ZodType {
9814
9814
  }
9815
9815
  pick(mask) {
9816
9816
  const shape = {};
9817
- for (const key of util.objectKeys(mask)) {
9818
- if (mask[key] && this.shape[key]) {
9819
- shape[key] = this.shape[key];
9817
+ for (const key2 of util.objectKeys(mask)) {
9818
+ if (mask[key2] && this.shape[key2]) {
9819
+ shape[key2] = this.shape[key2];
9820
9820
  }
9821
9821
  }
9822
9822
  return new _ZodObject({
@@ -9826,9 +9826,9 @@ var ZodObject = class _ZodObject extends ZodType {
9826
9826
  }
9827
9827
  omit(mask) {
9828
9828
  const shape = {};
9829
- for (const key of util.objectKeys(this.shape)) {
9830
- if (!mask[key]) {
9831
- shape[key] = this.shape[key];
9829
+ for (const key2 of util.objectKeys(this.shape)) {
9830
+ if (!mask[key2]) {
9831
+ shape[key2] = this.shape[key2];
9832
9832
  }
9833
9833
  }
9834
9834
  return new _ZodObject({
@@ -9844,12 +9844,12 @@ var ZodObject = class _ZodObject extends ZodType {
9844
9844
  }
9845
9845
  partial(mask) {
9846
9846
  const newShape = {};
9847
- for (const key of util.objectKeys(this.shape)) {
9848
- const fieldSchema = this.shape[key];
9849
- if (mask && !mask[key]) {
9850
- newShape[key] = fieldSchema;
9847
+ for (const key2 of util.objectKeys(this.shape)) {
9848
+ const fieldSchema = this.shape[key2];
9849
+ if (mask && !mask[key2]) {
9850
+ newShape[key2] = fieldSchema;
9851
9851
  } else {
9852
- newShape[key] = fieldSchema.optional();
9852
+ newShape[key2] = fieldSchema.optional();
9853
9853
  }
9854
9854
  }
9855
9855
  return new _ZodObject({
@@ -9859,16 +9859,16 @@ var ZodObject = class _ZodObject extends ZodType {
9859
9859
  }
9860
9860
  required(mask) {
9861
9861
  const newShape = {};
9862
- for (const key of util.objectKeys(this.shape)) {
9863
- if (mask && !mask[key]) {
9864
- newShape[key] = this.shape[key];
9862
+ for (const key2 of util.objectKeys(this.shape)) {
9863
+ if (mask && !mask[key2]) {
9864
+ newShape[key2] = this.shape[key2];
9865
9865
  } else {
9866
- const fieldSchema = this.shape[key];
9866
+ const fieldSchema = this.shape[key2];
9867
9867
  let newField = fieldSchema;
9868
9868
  while (newField instanceof ZodOptional) {
9869
9869
  newField = newField._def.innerType;
9870
9870
  }
9871
- newShape[key] = newField;
9871
+ newShape[key2] = newField;
9872
9872
  }
9873
9873
  }
9874
9874
  return new _ZodObject({
@@ -10112,14 +10112,14 @@ function mergeValues(a, b) {
10112
10112
  return { valid: true, data: a };
10113
10113
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
10114
10114
  const bKeys = util.objectKeys(b);
10115
- const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
10115
+ const sharedKeys = util.objectKeys(a).filter((key2) => bKeys.indexOf(key2) !== -1);
10116
10116
  const newObj = { ...a, ...b };
10117
- for (const key of sharedKeys) {
10118
- const sharedValue = mergeValues(a[key], b[key]);
10117
+ for (const key2 of sharedKeys) {
10118
+ const sharedValue = mergeValues(a[key2], b[key2]);
10119
10119
  if (!sharedValue.valid) {
10120
10120
  return { valid: false };
10121
10121
  }
10122
- newObj[key] = sharedValue.data;
10122
+ newObj[key2] = sharedValue.data;
10123
10123
  }
10124
10124
  return { valid: true, data: newObj };
10125
10125
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
@@ -10283,11 +10283,11 @@ var ZodRecord = class _ZodRecord extends ZodType {
10283
10283
  const pairs = [];
10284
10284
  const keyType = this._def.keyType;
10285
10285
  const valueType = this._def.valueType;
10286
- for (const key in ctx.data) {
10286
+ for (const key2 in ctx.data) {
10287
10287
  pairs.push({
10288
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
10289
- value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
10290
- alwaysSet: key in ctx.data
10288
+ key: keyType._parse(new ParseInputLazyPath(ctx, key2, ctx.path, key2)),
10289
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key2], ctx.path, key2)),
10290
+ alwaysSet: key2 in ctx.data
10291
10291
  });
10292
10292
  }
10293
10293
  if (ctx.common.async) {
@@ -10335,9 +10335,9 @@ var ZodMap = class extends ZodType {
10335
10335
  }
10336
10336
  const keyType = this._def.keyType;
10337
10337
  const valueType = this._def.valueType;
10338
- const pairs = [...ctx.data.entries()].map(([key, value], index) => {
10338
+ const pairs = [...ctx.data.entries()].map(([key2, value], index) => {
10339
10339
  return {
10340
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
10340
+ key: keyType._parse(new ParseInputLazyPath(ctx, key2, ctx.path, [index, "key"])),
10341
10341
  value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
10342
10342
  };
10343
10343
  });
@@ -10345,30 +10345,30 @@ var ZodMap = class extends ZodType {
10345
10345
  const finalMap = /* @__PURE__ */ new Map();
10346
10346
  return Promise.resolve().then(async () => {
10347
10347
  for (const pair of pairs) {
10348
- const key = await pair.key;
10348
+ const key2 = await pair.key;
10349
10349
  const value = await pair.value;
10350
- if (key.status === "aborted" || value.status === "aborted") {
10350
+ if (key2.status === "aborted" || value.status === "aborted") {
10351
10351
  return INVALID;
10352
10352
  }
10353
- if (key.status === "dirty" || value.status === "dirty") {
10353
+ if (key2.status === "dirty" || value.status === "dirty") {
10354
10354
  status2.dirty();
10355
10355
  }
10356
- finalMap.set(key.value, value.value);
10356
+ finalMap.set(key2.value, value.value);
10357
10357
  }
10358
10358
  return { status: status2.value, value: finalMap };
10359
10359
  });
10360
10360
  } else {
10361
10361
  const finalMap = /* @__PURE__ */ new Map();
10362
10362
  for (const pair of pairs) {
10363
- const key = pair.key;
10363
+ const key2 = pair.key;
10364
10364
  const value = pair.value;
10365
- if (key.status === "aborted" || value.status === "aborted") {
10365
+ if (key2.status === "aborted" || value.status === "aborted") {
10366
10366
  return INVALID;
10367
10367
  }
10368
- if (key.status === "dirty" || value.status === "dirty") {
10368
+ if (key2.status === "dirty" || value.status === "dirty") {
10369
10369
  status2.dirty();
10370
10370
  }
10371
- finalMap.set(key.value, value.value);
10371
+ finalMap.set(key2.value, value.value);
10372
10372
  }
10373
10373
  return { status: status2.value, value: finalMap };
10374
10374
  }
@@ -11410,19 +11410,19 @@ function floatSafeRemainder2(val, step) {
11410
11410
  const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
11411
11411
  return valInt % stepInt / 10 ** decCount;
11412
11412
  }
11413
- function defineLazy(object3, key, getter) {
11413
+ function defineLazy(object3, key2, getter) {
11414
11414
  const set = false;
11415
- Object.defineProperty(object3, key, {
11415
+ Object.defineProperty(object3, key2, {
11416
11416
  get() {
11417
11417
  if (!set) {
11418
11418
  const value = getter();
11419
- object3[key] = value;
11419
+ object3[key2] = value;
11420
11420
  return value;
11421
11421
  }
11422
11422
  throw new Error("cached value already set");
11423
11423
  },
11424
11424
  set(v) {
11425
- Object.defineProperty(object3, key, {
11425
+ Object.defineProperty(object3, key2, {
11426
11426
  value: v
11427
11427
  // configurable: true,
11428
11428
  });
@@ -11441,11 +11441,11 @@ function assignProp(target, prop, value) {
11441
11441
  function getElementAtPath(obj, path) {
11442
11442
  if (!path)
11443
11443
  return obj;
11444
- return path.reduce((acc, key) => acc?.[key], obj);
11444
+ return path.reduce((acc, key2) => acc?.[key2], obj);
11445
11445
  }
11446
11446
  function promiseAllObject(promisesObj) {
11447
11447
  const keys = Object.keys(promisesObj);
11448
- const promises = keys.map((key) => promisesObj[key]);
11448
+ const promises = keys.map((key2) => promisesObj[key2]);
11449
11449
  return Promise.all(promises).then((results) => {
11450
11450
  const resolvedObj = {};
11451
11451
  for (let i = 0; i < keys.length; i++) {
@@ -11498,8 +11498,8 @@ function isPlainObject(o) {
11498
11498
  }
11499
11499
  function numKeys(data) {
11500
11500
  let keyCount = 0;
11501
- for (const key in data) {
11502
- if (Object.prototype.hasOwnProperty.call(data, key)) {
11501
+ for (const key2 in data) {
11502
+ if (Object.prototype.hasOwnProperty.call(data, key2)) {
11503
11503
  keyCount++;
11504
11504
  }
11505
11505
  }
@@ -11635,13 +11635,13 @@ var BIGINT_FORMAT_RANGES = {
11635
11635
  function pick(schema, mask) {
11636
11636
  const newShape = {};
11637
11637
  const currDef = schema._zod.def;
11638
- for (const key in mask) {
11639
- if (!(key in currDef.shape)) {
11640
- throw new Error(`Unrecognized key: "${key}"`);
11638
+ for (const key2 in mask) {
11639
+ if (!(key2 in currDef.shape)) {
11640
+ throw new Error(`Unrecognized key: "${key2}"`);
11641
11641
  }
11642
- if (!mask[key])
11642
+ if (!mask[key2])
11643
11643
  continue;
11644
- newShape[key] = currDef.shape[key];
11644
+ newShape[key2] = currDef.shape[key2];
11645
11645
  }
11646
11646
  return clone(schema, {
11647
11647
  ...schema._zod.def,
@@ -11652,13 +11652,13 @@ function pick(schema, mask) {
11652
11652
  function omit(schema, mask) {
11653
11653
  const newShape = { ...schema._zod.def.shape };
11654
11654
  const currDef = schema._zod.def;
11655
- for (const key in mask) {
11656
- if (!(key in currDef.shape)) {
11657
- throw new Error(`Unrecognized key: "${key}"`);
11655
+ for (const key2 in mask) {
11656
+ if (!(key2 in currDef.shape)) {
11657
+ throw new Error(`Unrecognized key: "${key2}"`);
11658
11658
  }
11659
- if (!mask[key])
11659
+ if (!mask[key2])
11660
11660
  continue;
11661
- delete newShape[key];
11661
+ delete newShape[key2];
11662
11662
  }
11663
11663
  return clone(schema, {
11664
11664
  ...schema._zod.def,
@@ -11699,23 +11699,23 @@ function partial(Class2, schema, mask) {
11699
11699
  const oldShape = schema._zod.def.shape;
11700
11700
  const shape = { ...oldShape };
11701
11701
  if (mask) {
11702
- for (const key in mask) {
11703
- if (!(key in oldShape)) {
11704
- throw new Error(`Unrecognized key: "${key}"`);
11702
+ for (const key2 in mask) {
11703
+ if (!(key2 in oldShape)) {
11704
+ throw new Error(`Unrecognized key: "${key2}"`);
11705
11705
  }
11706
- if (!mask[key])
11706
+ if (!mask[key2])
11707
11707
  continue;
11708
- shape[key] = Class2 ? new Class2({
11708
+ shape[key2] = Class2 ? new Class2({
11709
11709
  type: "optional",
11710
- innerType: oldShape[key]
11711
- }) : oldShape[key];
11710
+ innerType: oldShape[key2]
11711
+ }) : oldShape[key2];
11712
11712
  }
11713
11713
  } else {
11714
- for (const key in oldShape) {
11715
- shape[key] = Class2 ? new Class2({
11714
+ for (const key2 in oldShape) {
11715
+ shape[key2] = Class2 ? new Class2({
11716
11716
  type: "optional",
11717
- innerType: oldShape[key]
11718
- }) : oldShape[key];
11717
+ innerType: oldShape[key2]
11718
+ }) : oldShape[key2];
11719
11719
  }
11720
11720
  }
11721
11721
  return clone(schema, {
@@ -11728,22 +11728,22 @@ function required(Class2, schema, mask) {
11728
11728
  const oldShape = schema._zod.def.shape;
11729
11729
  const shape = { ...oldShape };
11730
11730
  if (mask) {
11731
- for (const key in mask) {
11732
- if (!(key in shape)) {
11733
- throw new Error(`Unrecognized key: "${key}"`);
11731
+ for (const key2 in mask) {
11732
+ if (!(key2 in shape)) {
11733
+ throw new Error(`Unrecognized key: "${key2}"`);
11734
11734
  }
11735
- if (!mask[key])
11735
+ if (!mask[key2])
11736
11736
  continue;
11737
- shape[key] = new Class2({
11737
+ shape[key2] = new Class2({
11738
11738
  type: "nonoptional",
11739
- innerType: oldShape[key]
11739
+ innerType: oldShape[key2]
11740
11740
  });
11741
11741
  }
11742
11742
  } else {
11743
- for (const key in oldShape) {
11744
- shape[key] = new Class2({
11743
+ for (const key2 in oldShape) {
11744
+ shape[key2] = new Class2({
11745
11745
  type: "nonoptional",
11746
- innerType: oldShape[key]
11746
+ innerType: oldShape[key2]
11747
11747
  });
11748
11748
  }
11749
11749
  }
@@ -12941,28 +12941,28 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
12941
12941
  return payload;
12942
12942
  };
12943
12943
  });
12944
- function handleObjectResult(result, final, key) {
12944
+ function handleObjectResult(result, final, key2) {
12945
12945
  if (result.issues.length) {
12946
- final.issues.push(...prefixIssues(key, result.issues));
12946
+ final.issues.push(...prefixIssues(key2, result.issues));
12947
12947
  }
12948
- final.value[key] = result.value;
12948
+ final.value[key2] = result.value;
12949
12949
  }
12950
- function handleOptionalObjectResult(result, final, key, input) {
12950
+ function handleOptionalObjectResult(result, final, key2, input) {
12951
12951
  if (result.issues.length) {
12952
- if (input[key] === void 0) {
12953
- if (key in input) {
12954
- final.value[key] = void 0;
12952
+ if (input[key2] === void 0) {
12953
+ if (key2 in input) {
12954
+ final.value[key2] = void 0;
12955
12955
  } else {
12956
- final.value[key] = result.value;
12956
+ final.value[key2] = result.value;
12957
12957
  }
12958
12958
  } else {
12959
- final.issues.push(...prefixIssues(key, result.issues));
12959
+ final.issues.push(...prefixIssues(key2, result.issues));
12960
12960
  }
12961
12961
  } else if (result.value === void 0) {
12962
- if (key in input)
12963
- final.value[key] = void 0;
12962
+ if (key2 in input)
12963
+ final.value[key2] = void 0;
12964
12964
  } else {
12965
- final.value[key] = result.value;
12965
+ final.value[key2] = result.value;
12966
12966
  }
12967
12967
  }
12968
12968
  var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
@@ -12986,12 +12986,12 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
12986
12986
  defineLazy(inst._zod, "propValues", () => {
12987
12987
  const shape = def.shape;
12988
12988
  const propValues = {};
12989
- for (const key in shape) {
12990
- const field = shape[key]._zod;
12989
+ for (const key2 in shape) {
12990
+ const field = shape[key2]._zod;
12991
12991
  if (field.values) {
12992
- propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
12992
+ propValues[key2] ?? (propValues[key2] = /* @__PURE__ */ new Set());
12993
12993
  for (const v of field.values)
12994
- propValues[key].add(v);
12994
+ propValues[key2].add(v);
12995
12995
  }
12996
12996
  }
12997
12997
  return propValues;
@@ -12999,22 +12999,22 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
12999
12999
  const generateFastpass = (shape) => {
13000
13000
  const doc = new Doc(["shape", "payload", "ctx"]);
13001
13001
  const normalized = _normalized.value;
13002
- const parseStr = (key) => {
13003
- const k = esc(key);
13002
+ const parseStr = (key2) => {
13003
+ const k = esc(key2);
13004
13004
  return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
13005
13005
  };
13006
13006
  doc.write(`const input = payload.value;`);
13007
13007
  const ids = /* @__PURE__ */ Object.create(null);
13008
13008
  let counter = 0;
13009
- for (const key of normalized.keys) {
13010
- ids[key] = `key_${counter++}`;
13009
+ for (const key2 of normalized.keys) {
13010
+ ids[key2] = `key_${counter++}`;
13011
13011
  }
13012
13012
  doc.write(`const newResult = {}`);
13013
- for (const key of normalized.keys) {
13014
- if (normalized.optionalKeys.has(key)) {
13015
- const id2 = ids[key];
13016
- doc.write(`const ${id2} = ${parseStr(key)};`);
13017
- const k = esc(key);
13013
+ for (const key2 of normalized.keys) {
13014
+ if (normalized.optionalKeys.has(key2)) {
13015
+ const id2 = ids[key2];
13016
+ doc.write(`const ${id2} = ${parseStr(key2)};`);
13017
+ const k = esc(key2);
13018
13018
  doc.write(`
13019
13019
  if (${id2}.issues.length) {
13020
13020
  if (input[${k}] === undefined) {
@@ -13036,14 +13036,14 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
13036
13036
  }
13037
13037
  `);
13038
13038
  } else {
13039
- const id2 = ids[key];
13040
- doc.write(`const ${id2} = ${parseStr(key)};`);
13039
+ const id2 = ids[key2];
13040
+ doc.write(`const ${id2} = ${parseStr(key2)};`);
13041
13041
  doc.write(`
13042
13042
  if (${id2}.issues.length) payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
13043
13043
  ...iss,
13044
- path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}]
13044
+ path: iss.path ? [${esc(key2)}, ...iss.path] : [${esc(key2)}]
13045
13045
  })));`);
13046
- doc.write(`newResult[${esc(key)}] = ${id2}.value`);
13046
+ doc.write(`newResult[${esc(key2)}] = ${id2}.value`);
13047
13047
  }
13048
13048
  }
13049
13049
  doc.write(`payload.value = newResult;`);
@@ -13078,16 +13078,16 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
13078
13078
  } else {
13079
13079
  payload.value = {};
13080
13080
  const shape = value.shape;
13081
- for (const key of value.keys) {
13082
- const el = shape[key];
13083
- const r = el._zod.run({ value: input[key], issues: [] }, ctx);
13081
+ for (const key2 of value.keys) {
13082
+ const el = shape[key2];
13083
+ const r = el._zod.run({ value: input[key2], issues: [] }, ctx);
13084
13084
  const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional";
13085
13085
  if (r instanceof Promise) {
13086
- proms.push(r.then((r2) => isOptional ? handleOptionalObjectResult(r2, payload, key, input) : handleObjectResult(r2, payload, key)));
13086
+ proms.push(r.then((r2) => isOptional ? handleOptionalObjectResult(r2, payload, key2, input) : handleObjectResult(r2, payload, key2)));
13087
13087
  } else if (isOptional) {
13088
- handleOptionalObjectResult(r, payload, key, input);
13088
+ handleOptionalObjectResult(r, payload, key2, input);
13089
13089
  } else {
13090
- handleObjectResult(r, payload, key);
13090
+ handleObjectResult(r, payload, key2);
13091
13091
  }
13092
13092
  }
13093
13093
  }
@@ -13098,18 +13098,18 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
13098
13098
  const keySet = value.keySet;
13099
13099
  const _catchall = catchall._zod;
13100
13100
  const t = _catchall.def.type;
13101
- for (const key of Object.keys(input)) {
13102
- if (keySet.has(key))
13101
+ for (const key2 of Object.keys(input)) {
13102
+ if (keySet.has(key2))
13103
13103
  continue;
13104
13104
  if (t === "never") {
13105
- unrecognized.push(key);
13105
+ unrecognized.push(key2);
13106
13106
  continue;
13107
13107
  }
13108
- const r = _catchall.run({ value: input[key], issues: [] }, ctx);
13108
+ const r = _catchall.run({ value: input[key2], issues: [] }, ctx);
13109
13109
  if (r instanceof Promise) {
13110
- proms.push(r.then((r2) => handleObjectResult(r2, payload, key)));
13110
+ proms.push(r.then((r2) => handleObjectResult(r2, payload, key2)));
13111
13111
  } else {
13112
- handleObjectResult(r, payload, key);
13112
+ handleObjectResult(r, payload, key2);
13113
13113
  }
13114
13114
  }
13115
13115
  if (unrecognized.length) {
@@ -13271,17 +13271,17 @@ function mergeValues2(a, b) {
13271
13271
  }
13272
13272
  if (isPlainObject(a) && isPlainObject(b)) {
13273
13273
  const bKeys = Object.keys(b);
13274
- const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
13274
+ const sharedKeys = Object.keys(a).filter((key2) => bKeys.indexOf(key2) !== -1);
13275
13275
  const newObj = { ...a, ...b };
13276
- for (const key of sharedKeys) {
13277
- const sharedValue = mergeValues2(a[key], b[key]);
13276
+ for (const key2 of sharedKeys) {
13277
+ const sharedValue = mergeValues2(a[key2], b[key2]);
13278
13278
  if (!sharedValue.valid) {
13279
13279
  return {
13280
13280
  valid: false,
13281
- mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
13281
+ mergeErrorPath: [key2, ...sharedValue.mergeErrorPath]
13282
13282
  };
13283
13283
  }
13284
- newObj[key] = sharedValue.data;
13284
+ newObj[key2] = sharedValue.data;
13285
13285
  }
13286
13286
  return { valid: true, data: newObj };
13287
13287
  }
@@ -13339,29 +13339,29 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
13339
13339
  if (def.keyType._zod.values) {
13340
13340
  const values = def.keyType._zod.values;
13341
13341
  payload.value = {};
13342
- for (const key of values) {
13343
- if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
13344
- const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
13342
+ for (const key2 of values) {
13343
+ if (typeof key2 === "string" || typeof key2 === "number" || typeof key2 === "symbol") {
13344
+ const result = def.valueType._zod.run({ value: input[key2], issues: [] }, ctx);
13345
13345
  if (result instanceof Promise) {
13346
13346
  proms.push(result.then((result2) => {
13347
13347
  if (result2.issues.length) {
13348
- payload.issues.push(...prefixIssues(key, result2.issues));
13348
+ payload.issues.push(...prefixIssues(key2, result2.issues));
13349
13349
  }
13350
- payload.value[key] = result2.value;
13350
+ payload.value[key2] = result2.value;
13351
13351
  }));
13352
13352
  } else {
13353
13353
  if (result.issues.length) {
13354
- payload.issues.push(...prefixIssues(key, result.issues));
13354
+ payload.issues.push(...prefixIssues(key2, result.issues));
13355
13355
  }
13356
- payload.value[key] = result.value;
13356
+ payload.value[key2] = result.value;
13357
13357
  }
13358
13358
  }
13359
13359
  }
13360
13360
  let unrecognized;
13361
- for (const key in input) {
13362
- if (!values.has(key)) {
13361
+ for (const key2 in input) {
13362
+ if (!values.has(key2)) {
13363
13363
  unrecognized = unrecognized ?? [];
13364
- unrecognized.push(key);
13364
+ unrecognized.push(key2);
13365
13365
  }
13366
13366
  }
13367
13367
  if (unrecognized && unrecognized.length > 0) {
@@ -13374,10 +13374,10 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
13374
13374
  }
13375
13375
  } else {
13376
13376
  payload.value = {};
13377
- for (const key of Reflect.ownKeys(input)) {
13378
- if (key === "__proto__")
13377
+ for (const key2 of Reflect.ownKeys(input)) {
13378
+ if (key2 === "__proto__")
13379
13379
  continue;
13380
- const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
13380
+ const keyResult = def.keyType._zod.run({ value: key2, issues: [] }, ctx);
13381
13381
  if (keyResult instanceof Promise) {
13382
13382
  throw new Error("Async schemas not supported in object keys currently");
13383
13383
  }
@@ -13386,24 +13386,24 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
13386
13386
  origin: "record",
13387
13387
  code: "invalid_key",
13388
13388
  issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
13389
- input: key,
13390
- path: [key],
13389
+ input: key2,
13390
+ path: [key2],
13391
13391
  inst
13392
13392
  });
13393
13393
  payload.value[keyResult.value] = keyResult.value;
13394
13394
  continue;
13395
13395
  }
13396
- const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
13396
+ const result = def.valueType._zod.run({ value: input[key2], issues: [] }, ctx);
13397
13397
  if (result instanceof Promise) {
13398
13398
  proms.push(result.then((result2) => {
13399
13399
  if (result2.issues.length) {
13400
- payload.issues.push(...prefixIssues(key, result2.issues));
13400
+ payload.issues.push(...prefixIssues(key2, result2.issues));
13401
13401
  }
13402
13402
  payload.value[keyResult.value] = result2.value;
13403
13403
  }));
13404
13404
  } else {
13405
13405
  if (result.issues.length) {
13406
- payload.issues.push(...prefixIssues(key, result.issues));
13406
+ payload.issues.push(...prefixIssues(key2, result.issues));
13407
13407
  }
13408
13408
  payload.value[keyResult.value] = result.value;
13409
13409
  }
@@ -14460,15 +14460,15 @@ var JSONSchemaGenerator = class {
14460
14460
  json.type = "object";
14461
14461
  json.properties = {};
14462
14462
  const shape = def.shape;
14463
- for (const key in shape) {
14464
- json.properties[key] = this.process(shape[key], {
14463
+ for (const key2 in shape) {
14464
+ json.properties[key2] = this.process(shape[key2], {
14465
14465
  ...params,
14466
- path: [...params.path, "properties", key]
14466
+ path: [...params.path, "properties", key2]
14467
14467
  });
14468
14468
  }
14469
14469
  const allKeys = new Set(Object.keys(shape));
14470
- const requiredKeys = new Set([...allKeys].filter((key) => {
14471
- const v = def.shape[key]._zod;
14470
+ const requiredKeys = new Set([...allKeys].filter((key2) => {
14471
+ const v = def.shape[key2]._zod;
14472
14472
  if (this.io === "input") {
14473
14473
  return v.optin === void 0;
14474
14474
  } else {
@@ -14802,8 +14802,8 @@ var JSONSchemaGenerator = class {
14802
14802
  if (defId)
14803
14803
  seen.defId = defId;
14804
14804
  const schema2 = seen.schema;
14805
- for (const key in schema2) {
14806
- delete schema2[key];
14805
+ for (const key2 in schema2) {
14806
+ delete schema2[key2];
14807
14807
  }
14808
14808
  schema2.$ref = ref;
14809
14809
  };
@@ -14930,8 +14930,8 @@ function toJSONSchema(input, _params) {
14930
14930
  defs
14931
14931
  };
14932
14932
  for (const entry of input._idmap.entries()) {
14933
- const [key, schema] = entry;
14934
- schemas[key] = gen2.emit(schema, {
14933
+ const [key2, schema] = entry;
14934
+ schemas[key2] = gen2.emit(schema, {
14935
14935
  ..._params,
14936
14936
  external
14937
14937
  });
@@ -14978,8 +14978,8 @@ function isTransforming(_schema, _ctx) {
14978
14978
  return isTransforming(def.element, ctx);
14979
14979
  }
14980
14980
  case "object": {
14981
- for (const key in def.shape) {
14982
- if (isTransforming(def.shape[key], ctx))
14981
+ for (const key2 in def.shape) {
14982
+ if (isTransforming(def.shape[key2], ctx))
14983
14983
  return true;
14984
14984
  }
14985
14985
  return false;
@@ -17541,19 +17541,19 @@ var getRefs = (options) => {
17541
17541
  };
17542
17542
 
17543
17543
  // node_modules/zod-to-json-schema/dist/esm/errorMessages.js
17544
- function addErrorMessage(res, key, errorMessage, refs) {
17544
+ function addErrorMessage(res, key2, errorMessage, refs) {
17545
17545
  if (!refs?.errorMessages)
17546
17546
  return;
17547
17547
  if (errorMessage) {
17548
17548
  res.errorMessage = {
17549
17549
  ...res.errorMessage,
17550
- [key]: errorMessage
17550
+ [key2]: errorMessage
17551
17551
  };
17552
17552
  }
17553
17553
  }
17554
- function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
17555
- res[key] = value;
17556
- addErrorMessage(res, key, errorMessage, refs);
17554
+ function setResponseValueAndErrors(res, key2, value, errorMessage, refs) {
17555
+ res[key2] = value;
17556
+ addErrorMessage(res, key2, errorMessage, refs);
17557
17557
  }
17558
17558
 
17559
17559
  // node_modules/zod-to-json-schema/dist/esm/getRelativePath.js
@@ -18145,11 +18145,11 @@ function parseRecordDef(def, refs) {
18145
18145
  return {
18146
18146
  type: "object",
18147
18147
  required: def.keyType._def.values,
18148
- properties: def.keyType._def.values.reduce((acc, key) => ({
18148
+ properties: def.keyType._def.values.reduce((acc, key2) => ({
18149
18149
  ...acc,
18150
- [key]: parseDef(def.valueType._def, {
18150
+ [key2]: parseDef(def.valueType._def, {
18151
18151
  ...refs,
18152
- currentPath: [...refs.currentPath, "properties", key]
18152
+ currentPath: [...refs.currentPath, "properties", key2]
18153
18153
  }) ?? parseAnyDef(refs)
18154
18154
  }), {}),
18155
18155
  additionalProperties: refs.rejectedAdditionalProperties
@@ -18216,10 +18216,10 @@ function parseMapDef(def, refs) {
18216
18216
  // node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
18217
18217
  function parseNativeEnumDef(def) {
18218
18218
  const object3 = def.values;
18219
- const actualKeys = Object.keys(def.values).filter((key) => {
18220
- return typeof object3[object3[key]] !== "number";
18219
+ const actualKeys = Object.keys(def.values).filter((key2) => {
18220
+ return typeof object3[object3[key2]] !== "number";
18221
18221
  });
18222
- const actualValues = actualKeys.map((key) => object3[key]);
18222
+ const actualValues = actualKeys.map((key2) => object3[key2]);
18223
18223
  const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
18224
18224
  return {
18225
18225
  type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
@@ -19311,7 +19311,7 @@ var Protocol = class {
19311
19311
  return;
19312
19312
  }
19313
19313
  const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
19314
- await new Promise((resolve2) => setTimeout(resolve2, pollInterval));
19314
+ await new Promise((resolve4) => setTimeout(resolve4, pollInterval));
19315
19315
  options?.signal?.throwIfAborted();
19316
19316
  }
19317
19317
  } catch (error2) {
@@ -19328,7 +19328,7 @@ var Protocol = class {
19328
19328
  */
19329
19329
  request(request, resultSchema, options) {
19330
19330
  const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
19331
- return new Promise((resolve2, reject) => {
19331
+ return new Promise((resolve4, reject) => {
19332
19332
  const earlyReject = (error2) => {
19333
19333
  reject(error2);
19334
19334
  };
@@ -19406,7 +19406,7 @@ var Protocol = class {
19406
19406
  if (!parseResult.success) {
19407
19407
  reject(parseResult.error);
19408
19408
  } else {
19409
- resolve2(parseResult.data);
19409
+ resolve4(parseResult.data);
19410
19410
  }
19411
19411
  } catch (error2) {
19412
19412
  reject(error2);
@@ -19667,12 +19667,12 @@ var Protocol = class {
19667
19667
  }
19668
19668
  } catch {
19669
19669
  }
19670
- return new Promise((resolve2, reject) => {
19670
+ return new Promise((resolve4, reject) => {
19671
19671
  if (signal.aborted) {
19672
19672
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
19673
19673
  return;
19674
19674
  }
19675
- const timeoutId = setTimeout(resolve2, interval);
19675
+ const timeoutId = setTimeout(resolve4, interval);
19676
19676
  signal.addEventListener("abort", () => {
19677
19677
  clearTimeout(timeoutId);
19678
19678
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
@@ -19750,8 +19750,8 @@ function isPlainObject2(value) {
19750
19750
  }
19751
19751
  function mergeCapabilities(base, additional) {
19752
19752
  const result = { ...base };
19753
- for (const key in additional) {
19754
- const k = key;
19753
+ for (const key2 in additional) {
19754
+ const k = key2;
19755
19755
  const addValue = additional[k];
19756
19756
  if (addValue === void 0)
19757
19757
  continue;
@@ -20763,7 +20763,7 @@ var McpServer = class {
20763
20763
  let task = createTaskResult.task;
20764
20764
  const pollInterval = task.pollInterval ?? 5e3;
20765
20765
  while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") {
20766
- await new Promise((resolve2) => setTimeout(resolve2, pollInterval));
20766
+ await new Promise((resolve4) => setTimeout(resolve4, pollInterval));
20767
20767
  const updatedTask = await extra.taskStore.getTask(taskId);
20768
20768
  if (!updatedTask) {
20769
20769
  throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`);
@@ -21427,12 +21427,12 @@ var StdioServerTransport = class {
21427
21427
  this.onclose?.();
21428
21428
  }
21429
21429
  send(message) {
21430
- return new Promise((resolve2) => {
21430
+ return new Promise((resolve4) => {
21431
21431
  const json = serializeMessage(message);
21432
21432
  if (this._stdout.write(json)) {
21433
- resolve2();
21433
+ resolve4();
21434
21434
  } else {
21435
- this._stdout.once("drain", resolve2);
21435
+ this._stdout.once("drain", resolve4);
21436
21436
  }
21437
21437
  });
21438
21438
  }
@@ -21869,12 +21869,37 @@ function flipForSequence(map) {
21869
21869
  };
21870
21870
  }
21871
21871
 
21872
+ // src/domain/context.ts
21873
+ function sourceError(raw) {
21874
+ if (!Array.isArray(raw) || raw.length > 100) return "sources must be an array of at most 100 file references";
21875
+ for (const item of raw) {
21876
+ if (!item || typeof item !== "object" || Array.isArray(item)) return "source must be an object";
21877
+ const s = item;
21878
+ if (Object.keys(s).some((k) => k !== "path" && k !== "sha256")) return "unknown source field";
21879
+ if (typeof s.path !== "string" || s.path.length > 1024 || !s.path || /[\u0000-\u001f\u007f-\u009f\\:]/.test(s.path) || s.path.startsWith("/") || s.path.split("/").some((p) => !p || p === "." || p === "..")) return "source path must be relative to the project, with forward slashes and no traversal";
21880
+ if (s.sha256 !== void 0 && (typeof s.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(s.sha256))) return "source sha256 must be a lowercase SHA256 hash";
21881
+ }
21882
+ return void 0;
21883
+ }
21884
+ function contextError(raw) {
21885
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return "context must be an object";
21886
+ for (const [key2, value] of Object.entries(raw)) {
21887
+ if (key2 !== "summary" && key2 !== "next") return "unknown context field";
21888
+ if (typeof value !== "string" || value.length > 2e3 || /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/.test(value)) return "context fields must be text of at most 2000 characters";
21889
+ }
21890
+ return void 0;
21891
+ }
21892
+
21872
21893
  // src/domain/text.ts
21873
21894
  var NO_CONTROLS = /^[^\u0000-\u001f\u007f-\u009f]*$/;
21874
21895
  var NO_CONTROLS_TEXT = "one line of text; control characters (ESC, newline, tab) are not allowed";
21875
21896
  var NO_CONTROLS_BUT_BREAKS = /^[^\u0000-\u0008\u000b-\u001f\u007f-\u009f]*$/;
21876
21897
  var NO_CONTROLS_BUT_BREAKS_TEXT = "text with optional newlines (\\n) and tabs; other control characters (ESC, BEL, CR) are not allowed";
21877
21898
  function mapTextError(map) {
21899
+ if (map.context !== void 0) {
21900
+ const error3 = contextError(map.context);
21901
+ if (error3) return error3;
21902
+ }
21878
21903
  const check2 = (field, value, multiline = false) => value === void 0 || (multiline ? NO_CONTROLS_BUT_BREAKS : NO_CONTROLS).test(value) ? void 0 : `${field}: ${multiline ? NO_CONTROLS_BUT_BREAKS_TEXT : NO_CONTROLS_TEXT}`;
21879
21904
  let error2 = check2("title", map.title);
21880
21905
  if (error2) return error2;
@@ -21889,6 +21914,10 @@ function mapTextError(map) {
21889
21914
  }
21890
21915
  }
21891
21916
  for (const [i, node] of map.nodes.entries()) {
21917
+ if (node.sources !== void 0) {
21918
+ const error3 = sourceError(node.sources);
21919
+ if (error3) return `nodes[${i}]: ${error3}`;
21920
+ }
21892
21921
  for (const name of ["label", "evidence", "detail"]) {
21893
21922
  error2 = check2(`nodes[${i}].${name}`, node[name], name !== "label");
21894
21923
  if (error2) return error2;
@@ -22792,25 +22821,25 @@ function describeValue(v) {
22792
22821
  function badShape(path, where, expected, got) {
22793
22822
  return err({ kind: "bad-shape", path, detail: `${where} is ${describeValue(got)}, expected ${expected}` });
22794
22823
  }
22795
- function arrayField(raw, key, path, presence) {
22796
- const v = raw[key];
22824
+ function arrayField(raw, key2, path, presence) {
22825
+ const v = raw[key2];
22797
22826
  if (Array.isArray(v)) return ok(v);
22798
22827
  if (v === void 0 && presence === "optional") return ok([]);
22799
- return badShape(path, `"${key}"`, "an array", v);
22828
+ return badShape(path, `"${key2}"`, "an array", v);
22800
22829
  }
22801
- function requiredString(rec, key, where, path) {
22802
- const v = rec[key];
22803
- return typeof v === "string" ? ok(v) : badShape(path, `${where}.${key}`, "a string", v);
22830
+ function requiredString(rec, key2, where, path) {
22831
+ const v = rec[key2];
22832
+ return typeof v === "string" ? ok(v) : badShape(path, `${where}.${key2}`, "a string", v);
22804
22833
  }
22805
- function optionalString(rec, key, where, path) {
22806
- const v = rec[key];
22834
+ function optionalString(rec, key2, where, path) {
22835
+ const v = rec[key2];
22807
22836
  if (v === void 0) return ok(void 0);
22808
- return typeof v === "string" ? ok(v) : badShape(path, `${where}.${key}`, "a string", v);
22837
+ return typeof v === "string" ? ok(v) : badShape(path, `${where}.${key2}`, "a string", v);
22809
22838
  }
22810
22839
  function parseMap(raw, path) {
22811
22840
  if (!isRecord(raw)) return err({ kind: "bad-shape", path, detail: "root is not an object" });
22812
- if (raw["version"] !== STATE_FILE_VERSION) {
22813
- return err({ kind: "bad-shape", path, detail: `version is ${String(raw["version"])}, expected ${STATE_FILE_VERSION}` });
22841
+ if (raw["version"] !== STATE_FILE_VERSION && raw["version"] !== 2) {
22842
+ return err({ kind: "bad-shape", path, detail: `version is ${String(raw["version"])}, expected ${STATE_FILE_VERSION} or 2` });
22814
22843
  }
22815
22844
  const layers = arrayField(raw, "layers", path, "required");
22816
22845
  if (!layers.ok) return layers;
@@ -22823,6 +22852,11 @@ function parseMap(raw, path) {
22823
22852
  const groups = arrayField(raw, "groups", path, "optional");
22824
22853
  if (!groups.ok) return groups;
22825
22854
  let map = EMPTY_MAP;
22855
+ if (raw["context"] !== void 0) {
22856
+ const error2 = contextError(raw["context"]);
22857
+ if (error2) return err({ kind: "bad-shape", path, detail: error2 });
22858
+ map = { ...map, context: raw["context"] };
22859
+ }
22826
22860
  const title = optionalString(raw, "title", "map", path);
22827
22861
  if (!title.ok) return title;
22828
22862
  if (title.value !== void 0) map = setTitle(map, title.value);
@@ -22951,6 +22985,11 @@ function parseMap(raw, path) {
22951
22985
  if (!updated.ok) return err({ kind: "invariant-violation", path, violation: updated.error });
22952
22986
  map = updated.value;
22953
22987
  }
22988
+ if (rawNode["sources"] !== void 0) {
22989
+ const error2 = sourceError(rawNode["sources"]);
22990
+ if (error2) return err({ kind: "bad-shape", path, detail: `${where}: ${error2}` });
22991
+ map = { ...map, nodes: map.nodes.map((n) => n.id === id2.value ? { ...n, sources: rawNode["sources"] } : n) };
22992
+ }
22954
22993
  }
22955
22994
  for (const [i, rawEdge] of edges.value.entries()) {
22956
22995
  const where = `edges[${i}]`;
@@ -22974,7 +23013,9 @@ function parseMap(raw, path) {
22974
23013
  }
22975
23014
  function serializeMap(map) {
22976
23015
  const body = {
22977
- version: STATE_FILE_VERSION,
23016
+ // Older runtimes must refuse maps with provenance rather than silently erasing it.
23017
+ version: map.context !== void 0 || map.nodes.some((n) => n.sources !== void 0) ? 2 : STATE_FILE_VERSION,
23018
+ ...map.context !== void 0 ? { context: map.context } : {},
22978
23019
  ...map.title !== void 0 ? { title: map.title } : {},
22979
23020
  ...map.kind !== void 0 ? { kind: map.kind } : {},
22980
23021
  layers: map.layers,
@@ -23253,11 +23294,201 @@ function saveMapFile(path, map) {
23253
23294
  return writeFileAtomic(path, serializeMap(map));
23254
23295
  }
23255
23296
 
23297
+ // src/store/transaction.ts
23298
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync4, rmSync as rmSync4, writeFileSync as writeFileSync2 } from "node:fs";
23299
+ import { dirname as dirname6, join as join5 } from "node:path";
23300
+ import { randomUUID, createHash } from "node:crypto";
23301
+ var LedgerError = class extends Error {
23302
+ constructor(code, message, details = {}) {
23303
+ super(message);
23304
+ this.code = code;
23305
+ this.details = details;
23306
+ }
23307
+ };
23308
+ var revisionOf = (map) => createHash("sha256").update(serializeMap(map)).digest("hex");
23309
+ function assertRevision(actual, expected) {
23310
+ if (expected !== void 0 && expected !== actual) throw new LedgerError("CONFLICT", "Map changed; read the current revision before retrying.", { expectedRevision: expected, actualRevision: actual });
23311
+ }
23312
+ function storeDirectory(file) {
23313
+ const dir = dirname6(file);
23314
+ return dir.endsWith("/pages") || dir.endsWith("\\pages") ? dirname6(dir) : dir;
23315
+ }
23316
+ function deadOwner(lock) {
23317
+ try {
23318
+ const owner = JSON.parse(readFileSync4(join5(lock, "owner.json"), "utf8"));
23319
+ if (!Number.isSafeInteger(owner.pid) || owner.pid <= 0) return false;
23320
+ try {
23321
+ process.kill(owner.pid, 0);
23322
+ return false;
23323
+ } catch (e) {
23324
+ return e.code === "ESRCH";
23325
+ }
23326
+ } catch {
23327
+ return false;
23328
+ }
23329
+ }
23330
+ function withStoreLock(file, action) {
23331
+ const dir = storeDirectory(file);
23332
+ mkdirSync3(dir, { recursive: true });
23333
+ const lock = join5(dir, ".write-lock");
23334
+ const owner = join5(lock, "owner.json");
23335
+ const token = randomUUID();
23336
+ try {
23337
+ mkdirSync3(lock);
23338
+ } catch (error2) {
23339
+ if (error2.code !== "EEXIST") throw error2;
23340
+ if (!deadOwner(lock)) throw new LedgerError("BUSY", `Another writer owns ${lock}; retry after it completes. An orphan without owner metadata needs manual inspection.`);
23341
+ try {
23342
+ mkdirSync3(join5(lock, ".reap"));
23343
+ } catch {
23344
+ throw new LedgerError("BUSY", "Another process is recovering the writer lock.");
23345
+ }
23346
+ if (!deadOwner(lock)) {
23347
+ rmSync4(join5(lock, ".reap"), { recursive: true, force: true });
23348
+ throw new LedgerError("BUSY", "Writer ownership changed.");
23349
+ }
23350
+ rmSync4(lock, { recursive: true });
23351
+ try {
23352
+ mkdirSync3(lock);
23353
+ } catch {
23354
+ throw new LedgerError("BUSY", "Another writer acquired the recovered lock.");
23355
+ }
23356
+ }
23357
+ let initialized = false;
23358
+ try {
23359
+ writeFileSync2(owner, JSON.stringify({ pid: process.pid, token }), { flag: "wx" });
23360
+ initialized = true;
23361
+ return action();
23362
+ } finally {
23363
+ try {
23364
+ if (!initialized || JSON.parse(readFileSync4(owner, "utf8")).token === token) rmSync4(lock, { recursive: true });
23365
+ } catch {
23366
+ }
23367
+ }
23368
+ }
23369
+
23370
+ // src/store/project.ts
23371
+ import { existsSync as existsSync3, realpathSync } from "node:fs";
23372
+ import { dirname as dirname7, join as join6, resolve } from "node:path";
23373
+ import { homedir, tmpdir } from "node:os";
23374
+ function resolveProjectDirectory(cwd, stopAt = [homedir(), tmpdir()]) {
23375
+ let start = resolve(cwd);
23376
+ try {
23377
+ start = realpathSync(start);
23378
+ } catch {
23379
+ }
23380
+ let dir = start;
23381
+ const boundaries = new Set(stopAt.map((path) => {
23382
+ try {
23383
+ return realpathSync(path);
23384
+ } catch {
23385
+ return resolve(path);
23386
+ }
23387
+ }));
23388
+ while (true) {
23389
+ if (dir !== start && boundaries.has(dir)) return start;
23390
+ if (existsSync3(join6(dir, ".git")) || existsSync3(join6(dir, ".mellos", "map.json")) || existsSync3(join6(dir, ".mellos", "pages"))) return dir;
23391
+ const parent = dirname7(dir);
23392
+ if (parent === dir) return start;
23393
+ dir = parent;
23394
+ }
23395
+ }
23396
+
23397
+ // src/server/mutations.ts
23398
+ var key = (resource, row) => resource === "edges" ? `${String(row.from)}->${String(row.to)}` : row.id;
23399
+ function patch(row, values) {
23400
+ const next = { ...row };
23401
+ for (const [field, value] of Object.entries(values)) {
23402
+ if (value === void 0 || field === "id") continue;
23403
+ if (value === null) delete next[field];
23404
+ else next[field] = value;
23405
+ }
23406
+ return next;
23407
+ }
23408
+ function update(draft, resource, locator, values) {
23409
+ const index = draft[resource].findIndex((r) => key(resource, r) === locator);
23410
+ if (index < 0) throw new Error(`unknown ${resource}: ${String(locator)}`);
23411
+ draft[resource][index] = patch(draft[resource][index], values);
23412
+ }
23413
+ function applyBatch(map, operations, page2) {
23414
+ if (!operations.length) return err("nothing to change: pass operations");
23415
+ const draft = JSON.parse(serializeMap(map));
23416
+ draft.groups ??= [];
23417
+ draft.lanes ??= [];
23418
+ try {
23419
+ for (const [index, operation] of operations.entries()) {
23420
+ try {
23421
+ const input = operation.data;
23422
+ if (operation.op === "declare") {
23423
+ const data = input;
23424
+ for (const resource of ["layers", "lanes", "groups", "nodes", "edges"]) {
23425
+ for (const item of data[resource] ?? []) {
23426
+ const row = { ...item };
23427
+ if (draft[resource].some((r) => key(resource, r) === key(resource, row))) throw new Error(`${resource}: already exists ${String(key(resource, row))}`);
23428
+ if (resource === "nodes") row.status ??= "planned";
23429
+ draft[resource].push(row);
23430
+ }
23431
+ }
23432
+ if (data.title !== void 0) {
23433
+ if (data.title === null) delete draft.title;
23434
+ else draft.title = data.title;
23435
+ }
23436
+ if (data.kind !== void 0) draft.kind = data.kind;
23437
+ if (data.context !== void 0) draft.context = data.context;
23438
+ } else if (operation.op === "update") {
23439
+ const data = input;
23440
+ if (data.title !== void 0) {
23441
+ if (data.title === null) delete draft.title;
23442
+ else draft.title = data.title;
23443
+ }
23444
+ if (data.kind !== void 0) draft.kind = data.kind;
23445
+ if (data.context !== void 0) {
23446
+ if (data.context === null) delete draft.context;
23447
+ else draft.context = data.context;
23448
+ }
23449
+ for (const resource of ["layers", "groups", "lanes"]) for (const item of data[resource] ?? []) update(draft, resource, item.id, { ...item });
23450
+ for (const item of data.updates ?? []) update(draft, "nodes", item.id, { ...item });
23451
+ for (const item of data.edges ?? []) {
23452
+ const { from, to, newFrom, newTo, ...fields } = item;
23453
+ update(draft, "edges", `${from}->${to}`, { ...fields, ...newFrom !== void 0 ? { from: newFrom } : {}, ...newTo !== void 0 ? { to: newTo } : {} });
23454
+ }
23455
+ if (data.laneOrder !== void 0) {
23456
+ if (data.laneOrder.length !== draft.lanes.length || new Set(data.laneOrder).size !== draft.lanes.length || data.laneOrder.some((id2) => !draft.lanes.some((l) => l.id === id2))) throw new Error("laneOrder must name every lane exactly once");
23457
+ draft.lanes = data.laneOrder.map((id2) => draft.lanes.find((l) => l.id === id2));
23458
+ }
23459
+ } else {
23460
+ const data = input;
23461
+ for (const resource of ["edges", "nodes", "groups", "lanes", "layers"]) {
23462
+ for (const item of data[resource] ?? []) {
23463
+ const id2 = resource === "edges" ? key("edges", item) : item;
23464
+ if (!draft[resource].some((r) => key(resource, r) === id2)) throw new Error(`unknown ${resource}: ${String(id2)}`);
23465
+ draft[resource] = draft[resource].filter((r) => key(resource, r) !== id2);
23466
+ if (resource === "nodes") draft.edges = draft.edges.filter((e) => e.from !== id2 && e.to !== id2);
23467
+ if (resource === "groups" || resource === "lanes") {
23468
+ const field = resource === "groups" ? "group" : "lane";
23469
+ draft.nodes = draft.nodes.map((n) => n[field] === id2 ? patch(n, { [field]: null }) : n);
23470
+ }
23471
+ }
23472
+ }
23473
+ }
23474
+ } catch (error2) {
23475
+ throw new Error(`operations[${index}]: ${error2.message}`);
23476
+ }
23477
+ }
23478
+ if (page2 !== void 0 && draft.nodes.some((n) => n.submap === page2)) return err("a node cannot dive into its own page");
23479
+ const parsed = parseMap(draft, "transaction");
23480
+ return parsed.ok ? ok(parsed.value) : err(describeStoreError(parsed.error));
23481
+ } catch (error2) {
23482
+ return err(error2.message);
23483
+ }
23484
+ }
23485
+
23256
23486
  // src/server/apply.ts
23257
23487
  function refuseSelfDive(where, submap, page2) {
23258
23488
  return submap === page2 ? `${where}: a node cannot dive into its own page ("${submap}"); a submap links a CHILD page` : void 0;
23259
23489
  }
23260
23490
  function applyDeclare(map, input) {
23491
+ if (input.context !== void 0 || input.nodes?.some((n) => n.sources !== void 0)) return applyBatch(map, [{ op: "declare", data: input }], input.page);
23261
23492
  let next = input.title !== void 0 ? setTitle(map, input.title) : map;
23262
23493
  if (input.kind !== void 0) {
23263
23494
  const kind = makeMapKind(input.kind);
@@ -23353,6 +23584,7 @@ function applyDeclare(map, input) {
23353
23584
  return ok(next);
23354
23585
  }
23355
23586
  function applyUpdate(map, input) {
23587
+ if (input.title !== void 0 || input.kind !== void 0 || input.context !== void 0 || input.edges !== void 0 || input.laneOrder !== void 0 || input.groups?.some((g) => g.layer !== void 0) || input.updates?.some((n) => n.sources !== void 0)) return applyBatch(map, [{ op: "update", data: input }], input.page);
23356
23588
  let next = map;
23357
23589
  const items = (input.updates?.length ?? 0) + (input.layers?.length ?? 0) + (input.groups?.length ?? 0) + (input.lanes?.length ?? 0);
23358
23590
  if (items === 0) return err("nothing to revise: pass updates, layers, groups or lanes");
@@ -23378,6 +23610,7 @@ function applyUpdate(map, input) {
23378
23610
  for (const [i, g] of (input.groups ?? []).entries()) {
23379
23611
  const id2 = makeGroupId(g.id);
23380
23612
  if (!id2.ok) return err(`groups[${i}]: ${describeMapError(id2.error)}`);
23613
+ if (g.label === void 0) return err(`groups[${i}]: nothing to change; give a label or layer`);
23381
23614
  const updated = updateGroup(next, id2.value, g.label);
23382
23615
  if (!updated.ok) return err(`groups[${i}]: ${describeMapError(updated.error)}`);
23383
23616
  next = updated.value;
@@ -23500,9 +23733,9 @@ function summarize(map) {
23500
23733
  }
23501
23734
 
23502
23735
  // src/preview/publisher.ts
23503
- import { createHash } from "node:crypto";
23504
- import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync4, readdirSync as readdirSync3, realpathSync, rmdirSync } from "node:fs";
23505
- import { dirname as dirname6, join as join5, resolve } from "node:path";
23736
+ import { createHash as createHash2 } from "node:crypto";
23737
+ import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync5, readdirSync as readdirSync3, realpathSync as realpathSync2, rmdirSync } from "node:fs";
23738
+ import { dirname as dirname8, join as join7, resolve as resolve2 } from "node:path";
23506
23739
 
23507
23740
  // src/preview/presentation.ts
23508
23741
  var LABELS = { planned: "\u5F85\u5F00\u53D1", "in-progress": "\u5F00\u53D1\u4E2D", done: "\u5DF2\u9A8C\u8BC1", regressed: "\u51FA\u73B0\u56DE\u5F52" };
@@ -23660,15 +23893,15 @@ var PREVIEW_DIR_NAME = "previews";
23660
23893
  var ENABLED = ".enabled";
23661
23894
  var PUBLISH_LOCK = ".publish-lock";
23662
23895
  function previewDirectory(defaultFile) {
23663
- return join5(dirname6(defaultFile), PREVIEW_DIR_NAME);
23896
+ return join7(dirname8(defaultFile), PREVIEW_DIR_NAME);
23664
23897
  }
23665
23898
  function previewFile(defaultFile, page2) {
23666
23899
  if (page2 !== void 0 && !ID_RULE.test(page2)) throw new Error("Invalid preview page id.");
23667
- return join5(previewDirectory(defaultFile), documentName(page2));
23900
+ return join7(previewDirectory(defaultFile), documentName(page2));
23668
23901
  }
23669
23902
  function save(path, contents) {
23670
23903
  try {
23671
- if (readFileSync4(path, "utf8") === contents) return;
23904
+ if (readFileSync5(path, "utf8") === contents) return;
23672
23905
  } catch (error2) {
23673
23906
  if (error2.code !== "ENOENT") throw error2;
23674
23907
  }
@@ -23676,19 +23909,19 @@ function save(path, contents) {
23676
23909
  if (!result.ok) throw new Error(describeStoreError(result.error));
23677
23910
  }
23678
23911
  function ownedDirectory(path) {
23679
- mkdirSync3(path, { recursive: true });
23680
- const expected = join5(realpathSync(dirname6(path)), path.slice(dirname6(path).length + 1));
23681
- const actual = realpathSync(path);
23912
+ mkdirSync4(path, { recursive: true });
23913
+ const expected = join7(realpathSync2(dirname8(path)), path.slice(dirname8(path).length + 1));
23914
+ const actual = realpathSync2(path);
23682
23915
  if (process.platform === "win32" ? actual.toLowerCase() !== expected.toLowerCase() : actual !== expected) {
23683
23916
  throw new Error(`Preview directory redirects outside its parent: ${path}`);
23684
23917
  }
23685
23918
  }
23686
23919
  function acquireLock(directory) {
23687
- const path = join5(directory, PUBLISH_LOCK);
23920
+ const path = join7(directory, PUBLISH_LOCK);
23688
23921
  const deadline = Date.now() + 2e3;
23689
23922
  while (true) {
23690
23923
  try {
23691
- mkdirSync3(path);
23924
+ mkdirSync4(path);
23692
23925
  return () => rmdirSync(path);
23693
23926
  } catch (error2) {
23694
23927
  if (error2.code !== "EEXIST") throw error2;
@@ -23699,8 +23932,8 @@ function acquireLock(directory) {
23699
23932
  }
23700
23933
  function createPreviewPublisher(defaultFile) {
23701
23934
  const directory = previewDirectory(defaultFile);
23702
- const enabledFile = join5(directory, ENABLED);
23703
- const enabled = () => existsSync3(enabledFile);
23935
+ const enabledFile = join7(directory, ENABLED);
23936
+ const enabled = () => existsSync4(enabledFile);
23704
23937
  const refresh = (page2) => {
23705
23938
  try {
23706
23939
  const path = previewFile(defaultFile, page2);
@@ -23717,26 +23950,26 @@ function createPreviewPublisher(defaultFile) {
23717
23950
  }
23718
23951
  if (page2 !== void 0 && !pages.some((p) => p.page === page2)) return err(`No map page named "${page2}".`);
23719
23952
  if (page2 === void 0 && !pages.some((p) => p.page === void 0)) pages.unshift({ page: void 0, map: EMPTY_MAP });
23720
- const images = join5(directory, "images");
23953
+ const images = join7(directory, "images");
23721
23954
  ownedDirectory(images);
23722
23955
  const present = /* @__PURE__ */ new Set();
23723
23956
  for (const item of pages) {
23724
23957
  const svg = renderMapSvg(item.map);
23725
- const digest = createHash("sha256").update(svg).digest("hex");
23958
+ const digest = createHash2("sha256").update(svg).digest("hex");
23726
23959
  const image = `images/${digest}.svg`;
23727
- save(join5(images, `${digest}.svg`), svg);
23960
+ save(join7(images, `${digest}.svg`), svg);
23728
23961
  const filename = documentName(item.page);
23729
- save(join5(directory, filename), renderMapMarkdown(item.map, image, pages));
23962
+ save(join7(directory, filename), renderMapMarkdown(item.map, image, pages));
23730
23963
  present.add(filename);
23731
23964
  }
23732
23965
  for (const filename of readdirSync3(directory)) {
23733
23966
  if (/^(map|page-[a-z0-9][a-z0-9-]{0,63})\.md$/.test(filename) && !present.has(filename)) {
23734
- save(join5(directory, filename), "# \u5730\u56FE\u5DF2\u5220\u9664\n\n\u6B64\u9875\u9762\u5DF2\u4E0D\u5728\u9879\u76EE\u5730\u56FE\u4E2D\u3002\n\n[\u8FD4\u56DE\u5730\u56FE\u76EE\u5F55](index.md)\n");
23967
+ save(join7(directory, filename), "# \u5730\u56FE\u5DF2\u5220\u9664\n\n\u6B64\u9875\u9762\u5DF2\u4E0D\u5728\u9879\u76EE\u5730\u56FE\u4E2D\u3002\n\n[\u8FD4\u56DE\u5730\u56FE\u76EE\u5F55](index.md)\n");
23735
23968
  }
23736
23969
  }
23737
- const index = join5(directory, "index.md");
23970
+ const index = join7(directory, "index.md");
23738
23971
  save(index, renderPreviewIndex(pages));
23739
- return ok({ path: resolve(path), index: resolve(index), pages: pages.length });
23972
+ return ok({ path: resolve2(path), index: resolve2(index), pages: pages.length });
23740
23973
  } finally {
23741
23974
  release();
23742
23975
  }
@@ -23759,13 +23992,13 @@ function createPreviewPublisher(defaultFile) {
23759
23992
 
23760
23993
  // src/web/launcher.ts
23761
23994
  import { spawn } from "node:child_process";
23762
- import { existsSync as existsSync4, readFileSync as readFileSync5 } from "node:fs";
23763
- import { dirname as dirname8, join as join6 } from "node:path";
23995
+ import { existsSync as existsSync5, readFileSync as readFileSync6 } from "node:fs";
23996
+ import { dirname as dirname10, join as join8 } from "node:path";
23764
23997
 
23765
23998
  // src/web/source.ts
23766
- import { createHash as createHash2 } from "node:crypto";
23999
+ import { createHash as createHash3 } from "node:crypto";
23767
24000
  import { statSync as statSync2 } from "node:fs";
23768
- import { basename as basename2, dirname as dirname7 } from "node:path";
24001
+ import { basename as basename2, dirname as dirname9 } from "node:path";
23769
24002
  function readWebSnapshot(defaultFile) {
23770
24003
  const pages = listPageFiles(defaultFile).map((file) => {
23771
24004
  const id2 = pageIdOfFile(defaultFile, file) ?? "";
@@ -23780,15 +24013,15 @@ function readWebSnapshot(defaultFile) {
23780
24013
  }
23781
24014
  });
23782
24015
  if (pages.length === 0) pages.push({ id: "", title: "\u7B49\u5F85\u7B2C\u4E00\u5F20\u5730\u56FE", modified: 0, map: EMPTY_MAP });
23783
- const value = { project: basename2(dirname7(dirname7(defaultFile))), pages };
23784
- return { revision: createHash2("sha256").update(JSON.stringify(value)).digest("hex"), value };
24016
+ const value = { project: basename2(dirname9(dirname9(defaultFile))), pages };
24017
+ return { revision: createHash3("sha256").update(JSON.stringify(value)).digest("hex"), value };
23785
24018
  }
23786
24019
 
23787
24020
  // src/web/launcher.ts
23788
- var webRuntimeFile = (defaultFile) => join6(dirname8(defaultFile), "web", "server.json");
24021
+ var webRuntimeFile = (defaultFile) => join8(dirname10(defaultFile), "web", "server.json");
23789
24022
  async function runningWebUrl(defaultFile) {
23790
24023
  try {
23791
- const info = JSON.parse(readFileSync5(webRuntimeFile(defaultFile), "utf8"));
24024
+ const info = JSON.parse(readFileSync6(webRuntimeFile(defaultFile), "utf8"));
23792
24025
  if (!Number.isInteger(info.port) || info.port < 1 || info.port > 65535 || !/^[a-f0-9]{48}$/.test(info.token)) return void 0;
23793
24026
  const url = `http://127.0.0.1:${info.port}/${info.token}/`;
23794
24027
  const response = await fetch(`${url}api/health`, { signal: AbortSignal.timeout(700) });
@@ -23800,21 +24033,21 @@ async function runningWebUrl(defaultFile) {
23800
24033
  async function openWebPreview(defaultFile, entry, page2, terminal = false) {
23801
24034
  if (page2 !== void 0 && (!ID_RULE.test(page2) || !readWebSnapshot(defaultFile).value.pages.some((p) => p.id === page2))) throw new Error(`No map page named "${page2}".`);
23802
24035
  let url = await runningWebUrl(defaultFile);
23803
- if (url && terminal) {
24036
+ if (url) {
23804
24037
  const health = await fetch(`${url}api/health`, { signal: AbortSignal.timeout(2e3) });
23805
24038
  const info = await health.json();
23806
- if (!info.surfaces?.includes("web-terminal")) {
24039
+ if (!info.formats?.includes(2) || terminal && !info.surfaces?.includes("web-terminal")) {
23807
24040
  await fetch(`${url}api/stop`, { method: "POST", signal: AbortSignal.timeout(2e3) });
23808
24041
  const deadline = Date.now() + 3e3;
23809
24042
  while (await runningWebUrl(defaultFile)) {
23810
- if (Date.now() > deadline) throw new Error("Old web viewer is still stopping. Retry opening the terminal.");
23811
- await new Promise((resolve2) => setTimeout(resolve2, 100));
24043
+ if (Date.now() > deadline) throw new Error("Old web viewer is still stopping. Retry opening the map.");
24044
+ await new Promise((resolve4) => setTimeout(resolve4, 100));
23812
24045
  }
23813
24046
  url = void 0;
23814
24047
  }
23815
24048
  }
23816
24049
  if (!url) {
23817
- if (!existsSync4(entry)) throw new Error(`Web runtime missing: ${entry}. Run npm run build or reinstall the plugin.`);
24050
+ if (!existsSync5(entry)) throw new Error(`Web runtime missing: ${entry}. Run npm run build or reinstall the plugin.`);
23818
24051
  const child = spawn(process.execPath, [entry, "--serve", defaultFile], { detached: true, windowsHide: true, stdio: "ignore" });
23819
24052
  let failure;
23820
24053
  child.on("error", (error2) => {
@@ -23824,7 +24057,7 @@ async function openWebPreview(defaultFile, entry, page2, terminal = false) {
23824
24057
  const deadline = Date.now() + 8e3;
23825
24058
  while (!url && Date.now() < deadline) {
23826
24059
  if (failure) throw failure;
23827
- await new Promise((resolve2) => setTimeout(resolve2, 100));
24060
+ await new Promise((resolve4) => setTimeout(resolve4, 100));
23828
24061
  url = await runningWebUrl(defaultFile);
23829
24062
  }
23830
24063
  if (!url) throw new Error("Web preview did not start. Run the web CLI directly to inspect the error.");
@@ -23860,7 +24093,7 @@ var EDGE_LABEL_MAX = 80;
23860
24093
  function id(description) {
23861
24094
  return external_exports.string().regex(ID_RULE, ID_RULE_TEXT).describe(description);
23862
24095
  }
23863
- var PAGE_DESCRIPTION = "page (parallel map) this call targets; omit for the default page. One effort = one page: start a NEW effort on its own page named after the effort, so concurrent sessions never write over each other and the pane can switch between pages.";
24096
+ var PAGE_DESCRIPTION = "page (parallel map) this call targets; omit for the default page. A new conversation is not a new effort. Read existing pages with mmap_read first; reuse the same page for continued work. Create a new page only for a distinct effort.";
23864
24097
  function page() {
23865
24098
  return id(PAGE_DESCRIPTION).optional();
23866
24099
  }
@@ -23896,12 +24129,17 @@ function note(max, description) {
23896
24129
  function closed(shape) {
23897
24130
  return external_exports.object(shape).strict();
23898
24131
  }
24132
+ var expectedRevision = () => external_exports.string().regex(/^(?:[a-f0-9]{64}|absent)$/).optional().describe("Revision from mmap_read; absent requires a new page. A stale revision returns CONFLICT.");
24133
+ var context = () => closed({ summary: note(2e3, "Concise purpose and confirmed decisions").optional(), next: note(2e3, "Next actions for resuming this effort").optional() });
24134
+ var sources = () => external_exports.array(closed({ path: external_exports.string().max(1024), sha256: external_exports.string().regex(/^[a-f0-9]{64}$/).optional() })).max(100).refine((value) => sourceError(value) === void 0, "Use project-relative file paths without traversal.").describe("Optional source files and verified SHA256 baselines. mmap_read changes checks them without rescanning the repository.");
23899
24135
  function declareTool() {
23900
24136
  return {
23901
24137
  title: "Declare map structure",
23902
- description: "Grow the Mellos map: set the title and diagram kind, add layer bands, lanes and groups (labeled subsystems within ONE band \u2014 declare them when a single band grows crowded, roughly five or more nodes in that band; a group must be a strict subset of its band, and a map spread thin across many bands needs none), add nodes, add dependency edges. Declare the whole ghost design up front, then grow it as understanding deepens. Edges must point strictly downward (a node may only use nodes on lower layers); the batch is all-or-nothing. The title lives here and only here: pass it again to replace it, or null to remove it. Revising what already exists (moving, renaming, relabeling, clearing) is mmap_update.",
24138
+ description: "Grow the Mellos map: set the title and diagram kind, add layer bands, lanes and groups (labeled subsystems within ONE band \u2014 declare them when a single band grows crowded, roughly five or more nodes in that band; a group must be a strict subset of its band, and a map spread thin across many bands needs none), add nodes, add dependency edges. Declare the missing design after reading existing pages with mmap_read; reuse verified nodes. Edges must point strictly downward (a node may only use nodes on lower layers); the batch is all-or-nothing. Title and kind can also be changed with mmap_update; this legacy form remains supported. Revising what already exists (moving, renaming, relabeling, clearing) is mmap_update.",
23903
24139
  inputSchema: closed({
23904
24140
  page: page(),
24141
+ expectedRevision: expectedRevision(),
24142
+ context: context().optional(),
23905
24143
  title: line(TITLE_MAX, "map title, e.g. the feature being built; null removes it").nullable().optional(),
23906
24144
  kind: mapKind().optional(),
23907
24145
  lanes: external_exports.array(
@@ -23927,6 +24165,7 @@ function declareTool() {
23927
24165
  nodes: external_exports.array(
23928
24166
  closed({
23929
24167
  id: id("stable kebab-case identifier of the node"),
24168
+ sources: sources().optional(),
23930
24169
  label: line(LABEL_MAX, "display label inside the box"),
23931
24170
  layer: id("id of the band this node lives in"),
23932
24171
  status: status("defaults to planned").optional(),
@@ -23961,9 +24200,16 @@ function updateTool() {
23961
24200
  description: "The revision tool, all-or-nothing. Record progress on nodes: in-progress when starting a node (the pane spins), done with evidence when its verification passes, regressed with evidence when a done node breaks. Revise what the ghost design got wrong: move a node to another band, join or leave a group or lane, rename a band (or re-rank it, which reorders the whole map), relabel a group or a lane. Every clearable field takes null to empty it \u2014 that is how a field is cleared, never an empty string. Bands, groups and lanes are applied before the node updates, and within one node update `layer` moves the node before its other fields. The map is a ledger: report honestly, it never blocks you.",
23962
24201
  inputSchema: closed({
23963
24202
  page: page(),
24203
+ expectedRevision: expectedRevision(),
24204
+ title: line(TITLE_MAX, "Map title; null clears").nullable().optional(),
24205
+ kind: mapKind().optional(),
24206
+ context: context().nullable().optional(),
24207
+ laneOrder: external_exports.array(id("existing lane id")).max(100).optional().describe("Every lane exactly once, in display order."),
24208
+ edges: external_exports.array(closed({ ...edgeEnds(), label: line(EDGE_LABEL_MAX, "New edge label; null clears").nullable().optional(), newFrom: id("replacement consumer").optional(), newTo: id("replacement dependency").optional() })).min(1).optional(),
23964
24209
  updates: external_exports.array(
23965
24210
  closed({
23966
24211
  id: id("id of the node to update"),
24212
+ sources: sources().nullable().optional(),
23967
24213
  status: status("the status to record").optional(),
23968
24214
  label: line(LABEL_MAX, "new display label inside the box").optional(),
23969
24215
  evidence: line(EVIDENCE_MAX, "for done: how it was verified; for regressed: what broke; null clears it").nullable().optional(),
@@ -23987,7 +24233,7 @@ function updateTool() {
23987
24233
  rank: rank().optional()
23988
24234
  })
23989
24235
  ).min(1).optional().describe("rename and/or re-rank existing bands; an item must carry a name, a rank, or both"),
23990
- groups: external_exports.array(closed({ id: id("id of the group to relabel"), label: line(LABEL_MAX, "new subsystem name") })).min(1).optional().describe("relabel existing groups; membership and band are untouched"),
24236
+ groups: external_exports.array(closed({ id: id("id of the group to revise"), label: line(LABEL_MAX, "new subsystem name").optional(), layer: id("new layer; move members in the same batch").optional() })).min(1).optional().describe("relabel or move a group; final membership must match its layer"),
23991
24237
  lanes: external_exports.array(closed({ id: id("id of the lane to relabel"), label: line(LABEL_MAX, "new column name") })).min(1).optional().describe("relabel existing lanes; order and membership are untouched")
23992
24238
  })
23993
24239
  };
@@ -23998,6 +24244,9 @@ function removeTool() {
23998
24244
  description: 'Remove edges, nodes, groups and empty layer bands (in that order, all-or-nothing). Removing a node also removes every edge touching it; removing a group merely ungroups its members. Use when the ghost design turns out wrong \u2014 the map is a hypothesis, revising it is honest work. `pages` is the other scale: it DELETES whole page files, so a finished effort can be cleaned up instead of accumulating tabs forever. A bare `{pages: ["slug"]}` with no other field is the normal form; combined with map edits, the edits are applied first and the pages are deleted after. The deletion is permanent and cannot be undone, so delete only pages whose effort is over \u2014 and only ever with the user behind it. An unknown slug is refused with the project\'s real page list (naming a page that does not exist is a typo, not a request). The default page has no slug and is not deletable here. A node elsewhere still pointing at a deleted page with `submap` stays legal \u2014 a submap reference has no existence invariant \u2014 but it has nowhere to dive until the page comes back.',
23999
24245
  inputSchema: closed({
24000
24246
  page: page(),
24247
+ expectedRevision: expectedRevision(),
24248
+ deletePage: external_exports.boolean().optional().describe("Delete the page targeted by page, including the default page; cannot be combined with other edits."),
24249
+ references: external_exports.enum(["reject", "keep"]).optional().describe("For deletePage: reject inbound submap references by default, or explicitly keep them."),
24001
24250
  edges: external_exports.array(closed(edgeEnds())).optional(),
24002
24251
  nodes: external_exports.array(id("id of the node to remove, with every edge touching it")).optional(),
24003
24252
  groups: external_exports.array(id("id of the group to remove; members stay, merely ungrouped")).optional(),
@@ -24023,6 +24272,44 @@ function setupTool() {
24023
24272
  })
24024
24273
  };
24025
24274
  }
24275
+ function readTool() {
24276
+ return {
24277
+ title: "Read and resume saved maps",
24278
+ description: "Read existing pages before creating a map. Returns structured IDs, revisions and bounded results. pages lists summaries; map reads page metadata/context; nodes/edges/layers/groups/lanes read editable records; neighborhood reads related nodes; changes compares saved source hashes with local files. New conversations and compacted context should resume the existing effort. mmap_view remains the picture.",
24279
+ inputSchema: closed({
24280
+ resource: external_exports.enum(["pages", "map", "nodes", "edges", "layers", "groups", "lanes", "neighborhood", "changes"]).optional(),
24281
+ page: page(),
24282
+ id: external_exports.string().min(1).max(200).optional().describe("Exact ID; missing returns NOT_FOUND. Edge IDs use from->to; default page ID is _default."),
24283
+ ids: external_exports.array(external_exports.string().min(1).max(200)).max(100).optional(),
24284
+ query: external_exports.string().max(200).optional(),
24285
+ status: external_exports.enum(NODE_STATUSES).optional(),
24286
+ layer: id("filter by layer").optional(),
24287
+ group: id("filter by group").optional(),
24288
+ lane: id("filter by lane").optional(),
24289
+ fields: external_exports.array(external_exports.enum(["id", "label", "name", "rank", "status", "layer", "group", "lane", "kind", "submap", "detail", "evidence", "sources", "from", "to", "title", "context", "counts", "revision", "error", "state", "affectedConsumers"])).min(1).max(30).optional(),
24290
+ limit: external_exports.number().int().min(1).max(100).optional(),
24291
+ cursor: external_exports.string().max(2048).optional().describe("Opaque cursor; reuse the same query. Changes return CONFLICT instead of skipping records."),
24292
+ ifRevision: expectedRevision(),
24293
+ depth: external_exports.number().int().min(0).max(4).optional(),
24294
+ direction: external_exports.enum(["dependencies", "consumers", "both"]).optional()
24295
+ })
24296
+ };
24297
+ }
24298
+ function batchTool() {
24299
+ return {
24300
+ title: "Commit a single-page transaction",
24301
+ description: "Atomically combine additions, updates and removals on ONE page. Checks the final graph, so a coordinated move or edge replacement needs no intermediate saves. Read IDs and revision with mmap_read first. Cross-page deletion is excluded.",
24302
+ inputSchema: closed({
24303
+ page: page(),
24304
+ expectedRevision: expectedRevision(),
24305
+ operations: external_exports.array(external_exports.discriminatedUnion("op", [
24306
+ closed({ op: external_exports.literal("declare"), data: declareTool().inputSchema.omit({ page: true, expectedRevision: true }) }),
24307
+ closed({ op: external_exports.literal("update"), data: updateTool().inputSchema.omit({ page: true, expectedRevision: true }) }),
24308
+ closed({ op: external_exports.literal("remove"), data: removeTool().inputSchema.omit({ page: true, expectedRevision: true, pages: true, deletePage: true, references: true }) })
24309
+ ])).min(1).max(100)
24310
+ })
24311
+ };
24312
+ }
24026
24313
  function viewTool() {
24027
24314
  return {
24028
24315
  title: "View the current map",
@@ -24049,6 +24336,126 @@ function openTool() {
24049
24336
  };
24050
24337
  }
24051
24338
 
24339
+ // src/server/read.ts
24340
+ import { createHash as createHash4 } from "node:crypto";
24341
+ import { readFileSync as readFileSync7, realpathSync as realpathSync3, statSync as statSync3 } from "node:fs";
24342
+ import { dirname as dirname11, isAbsolute, relative, resolve as resolve3 } from "node:path";
24343
+ var hash = (value) => createHash4("sha256").update(JSON.stringify(value)).digest("hex");
24344
+ function requireMap(file) {
24345
+ const result = loadMapFile(file);
24346
+ if (!result.ok) throw new LedgerError(result.error.kind === "not-found" ? "NOT_FOUND" : "INVALID_STORE", describeStoreError(result.error));
24347
+ return result.value;
24348
+ }
24349
+ function summary(map, page2) {
24350
+ return { id: page2 ?? "_default", title: map.title ?? page2 ?? "Default map", kind: map.kind ?? "dev", context: map.context ?? null, revision: revisionOf(map), counts: { nodes: map.nodes.length, edges: map.edges.length, layers: map.layers.length, groups: map.groups.length, lanes: map.lanes.length, ...Object.fromEntries(["planned", "in-progress", "done", "regressed"].map((s) => [s, map.nodes.filter((n) => n.status === s).length])) } };
24351
+ }
24352
+ function related(map, seeds, direction, depth) {
24353
+ const adjacency = /* @__PURE__ */ new Map();
24354
+ const add = (from, to) => {
24355
+ const row = adjacency.get(from) ?? [];
24356
+ row.push(to);
24357
+ adjacency.set(from, row);
24358
+ };
24359
+ for (const edge of map.edges) {
24360
+ if (direction !== "consumers") add(edge.from, edge.to);
24361
+ if (direction !== "dependencies") add(edge.to, edge.from);
24362
+ }
24363
+ const found = new Set(seeds);
24364
+ let frontier = seeds;
24365
+ for (let step = 0; step < depth; step++) {
24366
+ const next = /* @__PURE__ */ new Set();
24367
+ for (const id2 of frontier) for (const neighbor of adjacency.get(id2) ?? []) if (!found.has(neighbor)) next.add(neighbor);
24368
+ for (const id2 of next) found.add(id2);
24369
+ frontier = [...next];
24370
+ if (!frontier.length) break;
24371
+ }
24372
+ return found;
24373
+ }
24374
+ function changes(node, project, map) {
24375
+ const sources2 = (node.sources ?? []).map((source) => {
24376
+ try {
24377
+ const root = realpathSync3(project), target = realpathSync3(resolve3(root, source.path));
24378
+ const rel = relative(root, target);
24379
+ if (isAbsolute(rel) || rel === ".." || rel.startsWith("..\\") || rel.startsWith("../")) return { ...source, state: "outside-project" };
24380
+ const stat = statSync3(target);
24381
+ if (!stat.isFile() || stat.size > 8 * 1024 * 1024) return { ...source, state: "unreadable" };
24382
+ const currentSha256 = createHash4("sha256").update(readFileSync7(target)).digest("hex");
24383
+ return { ...source, currentSha256, state: source.sha256 === void 0 ? "unverified" : source.sha256 === currentSha256 ? "unchanged" : "changed" };
24384
+ } catch (e) {
24385
+ return { ...source, state: e.code === "ENOENT" ? "missing" : "unreadable" };
24386
+ }
24387
+ });
24388
+ const changed = sources2.some((s) => s.state === "changed" || s.state === "missing");
24389
+ const affected = changed ? [...related(map, [node.id], "consumers", map.nodes.length)].filter((id2) => id2 !== node.id) : [];
24390
+ return { id: node.id, label: node.label, state: changed ? "changed" : sources2.length && sources2.every((s) => s.state === "unchanged") ? "unchanged" : "unknown", sources: sources2, affectedConsumers: affected.slice(0, 100), affectedConsumersTruncated: affected.length > 100 };
24391
+ }
24392
+ function readMaps(stateFile, input) {
24393
+ const resource = input.resource ?? "pages";
24394
+ const project = dirname11(dirname11(stateFile));
24395
+ let records;
24396
+ let revision;
24397
+ let map;
24398
+ if (resource === "pages") {
24399
+ records = listPageFiles(stateFile).map((file) => {
24400
+ const page2 = pageIdOfFile(stateFile, file);
24401
+ try {
24402
+ return summary(requireMap(file), page2);
24403
+ } catch (error2) {
24404
+ return { id: page2 ?? "_default", error: error2.message };
24405
+ }
24406
+ });
24407
+ revision = hash(records);
24408
+ } else {
24409
+ map = requireMap(pageFilePath(stateFile, input.page));
24410
+ revision = revisionOf(map);
24411
+ if (resource === "map") records = [summary(map, input.page)];
24412
+ else if (resource === "neighborhood") {
24413
+ const seeds = input.id !== void 0 ? [input.id] : input.ids ?? [];
24414
+ if (!seeds.length) throw new LedgerError("INVALID_QUERY", "neighborhood requires id or ids");
24415
+ const missing = seeds.filter((id2) => !map.nodes.some((n) => n.id === id2));
24416
+ if (missing.length) throw new LedgerError("NOT_FOUND", "Unknown neighborhood roots", { ids: missing });
24417
+ const selected = related(map, seeds, input.direction ?? "both", input.depth ?? 1);
24418
+ records = map.nodes.filter((n) => selected.has(n.id)).map((n) => ({ ...n }));
24419
+ } else if (resource === "changes") records = map.nodes.map((n) => ({ ...n }));
24420
+ else records = map[resource].map((row) => ({ ...row, ...resource === "edges" ? { id: `${"from" in row ? row.from : ""}->${"to" in row ? row.to : ""}` } : {} }));
24421
+ }
24422
+ if (resource !== "neighborhood") {
24423
+ if (input.id !== void 0) {
24424
+ records = records.filter((r) => r.id === input.id);
24425
+ if (!records.length) throw new LedgerError("NOT_FOUND", `No ${resource} record with ID ${input.id}`);
24426
+ }
24427
+ if (input.ids !== void 0) records = records.filter((r) => input.ids.includes(String(r.id)));
24428
+ }
24429
+ for (const field of ["status", "layer", "group", "lane"]) if (input[field] !== void 0) records = records.filter((r) => r[field] === input[field]);
24430
+ if (input.query) {
24431
+ const query2 = input.query.toLowerCase();
24432
+ records = records.filter((r) => JSON.stringify(r).toLowerCase().includes(query2));
24433
+ }
24434
+ const { cursor: _cursor, ifRevision: _ifRevision, ...query } = input;
24435
+ const queryHash = hash(query);
24436
+ let offset = 0;
24437
+ if (input.cursor !== void 0) {
24438
+ let cursor;
24439
+ try {
24440
+ cursor = JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8"));
24441
+ } catch {
24442
+ throw new LedgerError("INVALID_CURSOR", "Malformed cursor");
24443
+ }
24444
+ if (!cursor || cursor.query !== queryHash || !Number.isSafeInteger(cursor.offset) || cursor.offset < 0) throw new LedgerError("INVALID_CURSOR", "Cursor does not belong to this query");
24445
+ if (cursor.revision !== revision) throw new LedgerError("CONFLICT", "Map changed during pagination; restart this query.", { actualRevision: revision });
24446
+ offset = cursor.offset;
24447
+ }
24448
+ if (input.ifRevision === revision && resource !== "changes") return { resource, project, page: input.page ?? null, revision, notModified: true };
24449
+ const limit = input.limit ?? 30, total = records.length;
24450
+ records = records.slice(offset, offset + limit);
24451
+ if (resource === "changes") records = records.map((r) => changes(r, project, map));
24452
+ records = records.map((r) => {
24453
+ const fields = input.fields ?? (resource === "nodes" || resource === "neighborhood" ? ["id", "label", "layer", "status", "group", "lane", "kind", "submap"] : Object.keys(r));
24454
+ return Object.fromEntries([.../* @__PURE__ */ new Set(["id", ..."from" in r ? ["from", "to"] : [], ...fields])].filter((f) => f in r).map((f) => [f, r[f]]));
24455
+ });
24456
+ return { resource, project, page: input.page ?? null, revision, total, items: records, nextCursor: offset + limit < total ? Buffer.from(JSON.stringify({ revision, query: queryHash, offset: offset + limit })).toString("base64url") : null };
24457
+ }
24458
+
24052
24459
  // src/server/presence.ts
24053
24460
  var DEFAULT_PAGE_NAME = "(default)";
24054
24461
  var DEFAULT_PAGE_ABSENT = "(default: absent)";
@@ -24077,14 +24484,16 @@ function paneLine(stateFile, touched, openFailure) {
24077
24484
  }
24078
24485
 
24079
24486
  // src/server/map-service.ts
24487
+ import { existsSync as existsSync6 } from "node:fs";
24080
24488
  function loadOrEmpty(file) {
24081
24489
  const loaded = loadMapFile(file);
24082
24490
  if (loaded.ok) return loaded;
24083
24491
  return loaded.error.kind === "not-found" ? { ok: true, value: EMPTY_MAP } : { ok: false, error: describeStoreError(loaded.error) };
24084
24492
  }
24085
- function mutateMap(file, apply) {
24493
+ function mutateMap(file, apply, expectedRevision2) {
24086
24494
  const current = loadOrEmpty(file);
24087
24495
  if (!current.ok) return { ok: false, error: { kind: "load", detail: current.error } };
24496
+ assertRevision(existsSync6(file) ? revisionOf(current.value) : "absent", expectedRevision2);
24088
24497
  const applied = apply(current.value);
24089
24498
  if (!applied.ok) return { ok: false, error: { kind: "refused", detail: applied.error } };
24090
24499
  const saved = saveMapFile(file, applied.value);
@@ -24093,18 +24502,18 @@ function mutateMap(file, apply) {
24093
24502
 
24094
24503
  // src/server/pane-launcher.ts
24095
24504
  import { spawn as spawn2 } from "node:child_process";
24096
- import { existsSync as existsSync5 } from "node:fs";
24097
- import { dirname as dirname9, join as join7 } from "node:path";
24505
+ import { existsSync as existsSync7 } from "node:fs";
24506
+ import { dirname as dirname12, join as join9 } from "node:path";
24098
24507
  import { fileURLToPath } from "node:url";
24099
24508
  var pageName2 = (page2) => page2 ?? "(default)";
24100
24509
  var LAUNCH_TIMEOUT_MS = 6e4;
24101
24510
  var PANE_REPORT_TIMEOUT_MS = 8e3;
24102
24511
  var PANE_REPORT_POLL_MS = 250;
24103
24512
  function launcherPath(moduleUrl) {
24104
- return join7(dirname9(dirname9(fileURLToPath(moduleUrl))), "scripts", "open-pane.mjs");
24513
+ return join9(dirname12(dirname12(fileURLToPath(moduleUrl))), "scripts", "open-pane.mjs");
24105
24514
  }
24106
24515
  function projectDirOf(stateFile) {
24107
- return dirname9(dirname9(stateFile));
24516
+ return dirname12(dirname12(stateFile));
24108
24517
  }
24109
24518
  function launcherArgs(projectDir, page2, window) {
24110
24519
  const args = [projectDir];
@@ -24113,7 +24522,7 @@ function launcherArgs(projectDir, page2, window) {
24113
24522
  return args;
24114
24523
  }
24115
24524
  function runLauncher(script, args) {
24116
- return new Promise((resolve2) => {
24525
+ return new Promise((resolve4) => {
24117
24526
  const child = spawn2(process.execPath, [script, ...args], {
24118
24527
  windowsHide: true,
24119
24528
  stdio: ["ignore", "pipe", "pipe"]
@@ -24127,17 +24536,17 @@ function runLauncher(script, args) {
24127
24536
  const abandon = setTimeout(() => child.kill(), LAUNCH_TIMEOUT_MS);
24128
24537
  child.on("error", (e) => {
24129
24538
  clearTimeout(abandon);
24130
- resolve2({ ok: false, output: e.message });
24539
+ resolve4({ ok: false, output: e.message });
24131
24540
  });
24132
24541
  child.on("close", (code) => {
24133
24542
  clearTimeout(abandon);
24134
- resolve2({ ok: code === 0, output: output.trim() });
24543
+ resolve4({ ok: code === 0, output: output.trim() });
24135
24544
  });
24136
24545
  });
24137
24546
  }
24138
24547
  function launchPane(args) {
24139
24548
  const script = launcherPath(import.meta.url);
24140
- if (!existsSync5(script)) return Promise.resolve({
24549
+ if (!existsSync7(script)) return Promise.resolve({
24141
24550
  ok: false,
24142
24551
  output: `the launcher is missing at ${script}. This install is incomplete \u2014 reinstall the plugin (a source checkout needs "npm run build").`
24143
24552
  });
@@ -24181,15 +24590,26 @@ function launcherViewerPid(run) {
24181
24590
 
24182
24591
  // src/server/server.ts
24183
24592
  var SERVER_NAME = "mellos-mapping";
24184
- var SERVER_VERSION = "0.22.1";
24593
+ var SERVER_VERSION = "0.23.0";
24185
24594
  function text(s, isError = false) {
24186
24595
  return { content: [{ type: "text", text: s }], ...isError ? { isError: true } : {} };
24187
24596
  }
24597
+ function structured(value) {
24598
+ return { content: [{ type: "text", text: JSON.stringify(value) }], structuredContent: value };
24599
+ }
24600
+ function guard(action) {
24601
+ try {
24602
+ return action();
24603
+ } catch (error2) {
24604
+ const failure = error2 instanceof LedgerError ? error2 : new LedgerError("IO_ERROR", String(error2));
24605
+ return { ...structured({ error: { code: failure.code, message: failure.message, ...failure.details } }), isError: true };
24606
+ }
24607
+ }
24188
24608
  function saveFailed(error2) {
24189
24609
  return text(`save failed, nothing changed (retry): ${describeStoreError(error2)}`, true);
24190
24610
  }
24191
24611
  function buildServer(stateFile, userConfigFile, launch = launchPane) {
24192
- const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION });
24612
+ const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION }, { instructions: "Maps persist across conversations. Before mapping or resuming work, use mmap_read to discover pages, then read the relevant records and revision. A new conversation is not a new effort. Reuse verified nodes; submit only necessary changes with expectedRevision. mmap_view is a picture, not the editable data. Read mmap_setup for the user mapping policy." });
24193
24613
  let paneOpenFailure;
24194
24614
  const currentPaneLine = (page2) => paneLine(stateFile, page2, paneOpenFailure);
24195
24615
  const projectConfigFile = configFilePath(stateFile);
@@ -24204,17 +24624,20 @@ File generated; desktop visibility is not tracked.` : `
24204
24624
  preview: STALE \u2014 map changes were saved, but preview generation failed: ${published.error}. Retry mmap_open {surface: "markdown"}; do not repeat the map mutation.`;
24205
24625
  };
24206
24626
  const fileOf = (page2) => pageFilePath(stateFile, page2);
24207
- const mutate = (page2, apply) => {
24208
- const result = mutateMap(fileOf(page2), apply);
24627
+ const mutateUnlocked = (page2, apply, expectedRevision2) => {
24628
+ const result = mutateMap(fileOf(page2), apply, expectedRevision2);
24209
24629
  if (!result.ok) {
24210
24630
  const failure = result.error;
24211
- if (failure.kind === "save") return saveFailed(failure.error);
24212
- return text(failure.kind === "refused" ? `refused (nothing changed): ${failure.detail}` : failure.detail, true);
24631
+ if (failure.kind === "save") return { ...saveFailed(failure.error), structuredContent: { error: { code: "SAVE_FAILED", message: describeStoreError(failure.error) } } };
24632
+ return { ...text(failure.kind === "refused" ? `refused (nothing changed): ${failure.detail}` : failure.detail, true), structuredContent: { error: { code: failure.kind === "refused" ? "REFUSED" : "INVALID_STORE", message: failure.detail } } };
24213
24633
  }
24214
- return text(summarize(result.value) + (page2 !== void 0 ? ` [page: ${page2}]` : "") + refreshPreview(page2));
24634
+ const revision = revisionOf(result.value);
24635
+ return { ...text(summarize(result.value) + (page2 !== void 0 ? ` [page: ${page2}]` : "") + `
24636
+ revision: ${revision}` + refreshPreview(page2)), structuredContent: { page: page2 ?? null, revision, counts: { nodes: result.value.nodes.length, edges: result.value.edges.length } } };
24215
24637
  };
24216
- const withPane = (result, page2) => result.isError === true || previews.enabled() ? result : text(`${result.content[0]?.text ?? ""}
24217
- ${existsSync6(webRuntimeFile(stateFile)) ? 'web: configured \u2014 the browser reads project map updates. Use mmap_open {surface: "web", page} to open or reconnect; desktop visibility is not tracked.' : currentPaneLine(page2)}`);
24638
+ const mutate = (page2, apply, expectedRevision2) => guard(() => withStoreLock(stateFile, () => mutateUnlocked(page2, apply, expectedRevision2)));
24639
+ const withPane = (result, page2) => result.isError === true || previews.enabled() ? result : { ...result, ...text(`${result.content[0]?.text ?? ""}
24640
+ ${existsSync8(webRuntimeFile(stateFile)) ? 'web: configured \u2014 the browser reads project map updates. Use mmap_open {surface: "web", page} to open or reconnect; desktop visibility is not tracked.' : currentPaneLine(page2)}`) };
24218
24641
  const knownPages = () => listPageFiles(stateFile).map((f) => pageIdOfFile(stateFile, f)).filter((p) => p !== void 0);
24219
24642
  const refusePageDeletion = (pages, target) => {
24220
24643
  if (target !== void 0 && pages.includes(target)) {
@@ -24233,7 +24656,7 @@ ${existsSync6(webRuntimeFile(stateFile)) ? 'web: configured \u2014 the browser r
24233
24656
  }
24234
24657
  return void 0;
24235
24658
  };
24236
- const deletePages = (pages, summary) => {
24659
+ const deletePages = (pages, summary2) => {
24237
24660
  const deleted = [];
24238
24661
  const failed = [];
24239
24662
  for (const p of pages) {
@@ -24242,9 +24665,9 @@ ${existsSync6(webRuntimeFile(stateFile)) ? 'web: configured \u2014 the browser r
24242
24665
  else failed.push(`${p} (${describeStoreError(removed.error)})`);
24243
24666
  }
24244
24667
  const gone = `deleted page(s): ${deleted.length > 0 ? deleted.join(", ") : "(none)"}` + (deleted.length ? refreshPreview(void 0) : "");
24245
- if (failed.length === 0) return text(`${summary}${gone}`);
24668
+ if (failed.length === 0) return text(`${summary2}${gone}`);
24246
24669
  return text(
24247
- `${summary}${gone}; could NOT delete: ${failed.join("; ")}. Deleting files is not a transaction: what is named deleted above is gone for good, and only the failures are worth retrying.`,
24670
+ `${summary2}${gone}; could NOT delete: ${failed.join("; ")}. Deleting files is not a transaction: what is named deleted above is gone for good, and only the failures are worth retrying.`,
24248
24671
  true
24249
24672
  );
24250
24673
  };
@@ -24259,34 +24682,56 @@ note: ${describeStoreError(scopes.error)} \u2014 fix it or rerun setup (mmap_set
24259
24682
  "mmap_declare",
24260
24683
  declareTool(),
24261
24684
  (input) => {
24262
- const result = withPane(mutate(input.page, (map) => applyDeclare(map, input)), input.page);
24685
+ const result = withPane(mutate(input.page, (map) => applyDeclare(map, input), input.expectedRevision), input.page);
24263
24686
  if (result.isError === true) return result;
24264
24687
  const nudge = setupNudge();
24265
- return nudge === "" ? result : text((result.content[0]?.text ?? "") + nudge);
24688
+ return nudge === "" ? result : { ...result, ...text((result.content[0]?.text ?? "") + nudge) };
24266
24689
  }
24267
24690
  );
24268
24691
  server.registerTool(
24269
24692
  "mmap_update",
24270
24693
  updateTool(),
24271
- (input) => withPane(mutate(input.page, (map) => applyUpdate(map, input)), input.page)
24694
+ (input) => withPane(mutate(input.page, (map) => {
24695
+ requireMap(fileOf(input.page));
24696
+ return applyUpdate(map, input);
24697
+ }, input.expectedRevision), input.page)
24272
24698
  );
24699
+ server.registerTool("mmap_read", readTool(), (input) => guard(() => structured(readMaps(stateFile, input))));
24700
+ server.registerTool("mmap_batch", batchTool(), (input) => withPane(mutate(input.page, (map) => {
24701
+ if (!existsSync8(fileOf(input.page)) && !input.operations.some((op) => op.op === "declare")) throw new LedgerError("NOT_FOUND", "Create the page before updating it.");
24702
+ return applyBatch(map, input.operations, input.page);
24703
+ }, input.expectedRevision), input.page));
24273
24704
  server.registerTool(
24274
24705
  "mmap_remove",
24275
24706
  removeTool(),
24276
- (input) => {
24277
- if (input.pages === void 0) return withPane(mutate(input.page, (map) => applyRemove(map, input)), input.page);
24707
+ (input) => guard(() => withStoreLock(stateFile, () => {
24708
+ if (input.deletePage) {
24709
+ if (input.pages !== void 0 || [input.nodes, input.edges, input.layers, input.groups, input.lanes].some((items) => items !== void 0)) throw new LedgerError("INVALID_ARGUMENT", "deletePage cannot be combined with other edits.");
24710
+ const map = requireMap(fileOf(input.page));
24711
+ const revision = revisionOf(map);
24712
+ assertRevision(revision, input.expectedRevision);
24713
+ const references = input.page === void 0 ? [] : listPageFiles(stateFile).filter((file) => file !== fileOf(input.page)).flatMap((file) => requireMap(file).nodes.filter((node) => node.submap === input.page).map((node) => ({ page: pageIdOfFile(stateFile, file) ?? null, node: node.id })));
24714
+ if (references.length && input.references !== "keep") throw new LedgerError("REFERENCED", "Page has inbound submap references; unlink them or explicitly choose references: keep.", { references });
24715
+ const deleted = deletePageFile(fileOf(input.page));
24716
+ if (!deleted.ok) throw new LedgerError("DELETE_FAILED", describeStoreError(deleted.error));
24717
+ const preview = refreshPreview(void 0);
24718
+ return structured({ deleted: true, page: input.page ?? null, revision: "absent", previousRevision: revision, references, ...preview ? { preview } : {} });
24719
+ }
24720
+ if (input.references !== void 0) throw new LedgerError("INVALID_ARGUMENT", "references requires deletePage: true");
24721
+ if (input.pages === void 0) return withPane(mutateUnlocked(input.page, (map) => applyRemove(map, input), input.expectedRevision), input.page);
24722
+ if (input.expectedRevision !== void 0) throw new LedgerError("INVALID_ARGUMENT", "Use deletePage for a version-checked page deletion. Legacy pages batches report partial success.");
24278
24723
  const refusal = refusePageDeletion(input.pages, input.page);
24279
24724
  if (refusal !== void 0) return refusal;
24280
24725
  const editsAnything = (input.edges?.length ?? 0) + (input.nodes?.length ?? 0) + (input.groups?.length ?? 0) + (input.lanes?.length ?? 0) + (input.layers?.length ?? 0) > 0;
24281
- let summary = "";
24726
+ let summary2 = "";
24282
24727
  if (editsAnything) {
24283
- const edited = mutate(input.page, (map) => applyRemove(map, input));
24728
+ const edited = mutateUnlocked(input.page, (map) => applyRemove(map, input));
24284
24729
  if (edited.isError === true) return edited;
24285
- summary = `${edited.content[0]?.text ?? ""}
24730
+ summary2 = `${edited.content[0]?.text ?? ""}
24286
24731
  `;
24287
24732
  }
24288
- return withPane(deletePages(input.pages, summary), input.page);
24289
- }
24733
+ return withPane(deletePages(input.pages, summary2), input.page);
24734
+ }))
24290
24735
  );
24291
24736
  server.registerTool(
24292
24737
  "mmap_setup",
@@ -24325,7 +24770,7 @@ note: ${describeStoreError(scopes.error)} \u2014 fix it or rerun setup (mmap_set
24325
24770
  const zoom = clampZoom(input.zoom ?? 0);
24326
24771
  const picture = renderMap(current.value, { color: false, unicode: true, spinnerFrame: 0, zoom }).join("\n");
24327
24772
  const surface = previews.enabled() ? `markdown: ${previewFile(stateFile, input.page)}
24328
- Use mmap_open {surface: "markdown", page} to regenerate. Desktop visibility is not tracked.` : existsSync6(webRuntimeFile(stateFile)) ? 'web: configured \u2014 use mmap_open {surface: "web", page} to open or reconnect. Desktop visibility is not tracked.' : currentPaneLine(input.page);
24773
+ Use mmap_open {surface: "markdown", page} to regenerate. Desktop visibility is not tracked.` : existsSync8(webRuntimeFile(stateFile)) ? 'web: configured \u2014 use mmap_open {surface: "web", page} to open or reconnect. Desktop visibility is not tracked.' : currentPaneLine(input.page);
24329
24774
  return text(`${picture}
24330
24775
  ${pagesLine(stateFile, input.page)}
24331
24776
  ${surface}`);
@@ -24376,15 +24821,15 @@ Automatic preview updates are enabled for this project. Open the Markdown file i
24376
24821
  return server;
24377
24822
  }
24378
24823
  function resolveStateFile(env, cwd) {
24379
- const projectDir = env["MELLOS_MAPPING_CWD"] ?? env["CLAUDE_PROJECT_DIR"] ?? cwd;
24380
- return join8(projectDir, STATE_FILE_RELATIVE_PATH);
24824
+ const projectDir = env["MELLOS_MAPPING_CWD"] ?? env["CLAUDE_PROJECT_DIR"] ?? resolveProjectDirectory(cwd);
24825
+ return join10(projectDir, STATE_FILE_RELATIVE_PATH);
24381
24826
  }
24382
24827
  function resolveUserConfigFile(home) {
24383
24828
  return userConfigFilePath(home);
24384
24829
  }
24385
24830
  async function main() {
24386
24831
  const stateFile = resolveStateFile(process.env, process.cwd());
24387
- const userConfigFile = resolveUserConfigFile(homedir());
24832
+ const userConfigFile = resolveUserConfigFile(homedir2());
24388
24833
  if (migrateLegacyStore(stateFile)) console.error("mellos-mapping: moved the legacy .claude map store to .mellos/ \u2014 commit the move.");
24389
24834
  const server = buildServer(stateFile, userConfigFile);
24390
24835
  await server.connect(new StdioServerTransport());
@@ -24392,7 +24837,7 @@ async function main() {
24392
24837
  function launchedAsEntry(argv1, moduleUrl) {
24393
24838
  if (argv1 === void 0) return false;
24394
24839
  try {
24395
- return realpathSync2(argv1) === realpathSync2(fileURLToPath2(moduleUrl));
24840
+ return realpathSync4(argv1) === realpathSync4(fileURLToPath2(moduleUrl));
24396
24841
  } catch {
24397
24842
  return pathToFileURL(argv1).href === moduleUrl;
24398
24843
  }