ot-gateway 0.8.1 → 0.10.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.
@@ -3844,6 +3844,19 @@ __export(Context_exports, {
3844
3844
  pick: () => pick
3845
3845
  });
3846
3846
 
3847
+ // ../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js
3848
+ var Equal_exports = {};
3849
+ __export(Equal_exports, {
3850
+ asEquivalence: () => asEquivalence,
3851
+ byReference: () => byReference,
3852
+ byReferenceUnsafe: () => byReferenceUnsafe,
3853
+ equals: () => equals,
3854
+ isEqual: () => isEqual,
3855
+ makeCompareMap: () => makeCompareMap,
3856
+ makeCompareSet: () => makeCompareSet,
3857
+ symbol: () => symbol2
3858
+ });
3859
+
3847
3860
  // ../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js
3848
3861
  var pipeArguments = (self, args2) => {
3849
3862
  switch (args2.length) {
@@ -4400,6 +4413,7 @@ function makeCompareSet(equivalence) {
4400
4413
  }
4401
4414
  var isEqual = (u) => hasProperty(u, symbol2) && typeof u[symbol2] === "function";
4402
4415
  var asEquivalence = () => equals;
4416
+ var byReference = (obj) => byReferenceUnsafe(new Proxy(obj, {}));
4403
4417
  var byReferenceUnsafe = (obj) => {
4404
4418
  byReferenceInstances.add(obj);
4405
4419
  return obj;
@@ -11698,11 +11712,40 @@ var doneUnsafe = (self, effect2) => {
11698
11712
  var into = /* @__PURE__ */ dual(2, (self, deferred) => uninterruptibleMask((restore) => flatMap4(exit(restore(self)), (exit3) => done3(deferred, exit3))));
11699
11713
 
11700
11714
  // ../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/References.js
11715
+ var References_exports = {};
11716
+ __export(References_exports, {
11717
+ CurrentLogAnnotations: () => CurrentLogAnnotations2,
11718
+ CurrentLogLevel: () => CurrentLogLevel2,
11719
+ CurrentLogSpans: () => CurrentLogSpans2,
11720
+ CurrentLoggers: () => CurrentLoggers2,
11721
+ CurrentStackFrame: () => CurrentStackFrame2,
11722
+ CurrentTraceLevel: () => CurrentTraceLevel,
11723
+ DisablePropagation: () => DisablePropagation,
11724
+ LogToStderr: () => LogToStderr2,
11725
+ MaxOpsBeforeYield: () => MaxOpsBeforeYield,
11726
+ MinimumLogLevel: () => MinimumLogLevel2,
11727
+ MinimumTraceLevel: () => MinimumTraceLevel,
11728
+ PreventSchedulerYield: () => PreventSchedulerYield,
11729
+ Scheduler: () => Scheduler,
11730
+ Tracer: () => Tracer,
11731
+ TracerEnabled: () => TracerEnabled2,
11732
+ TracerSpanAnnotations: () => TracerSpanAnnotations2,
11733
+ TracerSpanLinks: () => TracerSpanLinks2,
11734
+ TracerTimingEnabled: () => TracerTimingEnabled2,
11735
+ UnhandledLogLevel: () => UnhandledLogLevel2
11736
+ });
11701
11737
  var CurrentLogAnnotations2 = CurrentLogAnnotations;
11738
+ var CurrentLogLevel2 = CurrentLogLevel;
11702
11739
  var CurrentLogSpans2 = CurrentLogSpans;
11703
11740
  var CurrentStackFrame2 = CurrentStackFrame;
11704
11741
  var MinimumLogLevel2 = MinimumLogLevel;
11742
+ var TracerEnabled2 = TracerEnabled;
11743
+ var TracerSpanAnnotations2 = TracerSpanAnnotations;
11744
+ var TracerSpanLinks2 = TracerSpanLinks;
11705
11745
  var TracerTimingEnabled2 = TracerTimingEnabled;
11746
+ var UnhandledLogLevel2 = UnhandledLogLevel;
11747
+ var CurrentLoggers2 = CurrentLoggers;
11748
+ var LogToStderr2 = LogToStderr;
11706
11749
 
11707
11750
  // ../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js
11708
11751
  var Scope_exports = {};
@@ -23176,8 +23219,8 @@ var decodeJsonError = (input) => {
23176
23219
  };
23177
23220
  var encodeUnknownAsJson = (input) => {
23178
23221
  try {
23179
- const json3 = formatJson(input);
23180
- return json3 === void 0 ? format(input) : JSON.parse(json3);
23222
+ const json4 = formatJson(input);
23223
+ return json4 === void 0 ? format(input) : JSON.parse(json4);
23181
23224
  } catch {
23182
23225
  return format(input);
23183
23226
  }
@@ -25589,14 +25632,14 @@ var template = (strings, ...expressions) => {
25589
25632
  var unwrap5 = (item) => isRedacted(item) ? value3(item) : String(item);
25590
25633
  var toWord = (item) => isRedacted(item) ? item : String(item);
25591
25634
  var reservedWords = /* @__PURE__ */ new Set(["!", "{", "}", "and", "begin", "case", "coproc", "do", "done", "elif", "else", "end", "esac", "fi", "for", "foreach", "function", "if", "in", "nocorrect", "not", "or", "repeat", "select", "switch", "then", "time", "until", "while"]);
25592
- var quoteWord = (format11, value4, program2) => {
25635
+ var quoteWord = (format11, value4, program) => {
25593
25636
  switch (format11) {
25594
25637
  case "posix":
25595
- return program2 && reservedWords.has(value4) ? `'${value4}'` : quotePosix(value4);
25638
+ return program && reservedWords.has(value4) ? `'${value4}'` : quotePosix(value4);
25596
25639
  case "powershell":
25597
25640
  return quotePowerShell(value4);
25598
25641
  case "windows":
25599
- return program2 && !value4.includes('"') ? quoteWindowsProgram(value4) : quoteWindowsArgument(value4);
25642
+ return program && !value4.includes('"') ? quoteWindowsProgram(value4) : quoteWindowsArgument(value4);
25600
25643
  }
25601
25644
  };
25602
25645
  var joinWords = (format11, quoted) => format11 === "powershell" ? `& ${quoted.join(" ")}` : quoted.join(" ");
@@ -25787,14 +25830,14 @@ var parseFdName = (name) => {
25787
25830
  };
25788
25831
  var fdName = (fd) => `fd${fd}`;
25789
25832
  var parseTemplate2 = (templates, expressions) => {
25790
- const [program2 = "", ...args2] = getOrThrow2(template(templates, ...expressions));
25791
- if (typeof program2 !== "string") {
25833
+ const [program = "", ...args2] = getOrThrow2(template(templates, ...expressions));
25834
+ if (typeof program !== "string") {
25792
25835
  throw new CommandLineError({
25793
25836
  reason: "InvalidArgument",
25794
25837
  message: "The program name of a command cannot be Redacted"
25795
25838
  });
25796
25839
  }
25797
- return [program2, args2];
25840
+ return [program, args2];
25798
25841
  };
25799
25842
  var shellScript = (templates, expressions) => {
25800
25843
  if (expressions.length > 0) {
@@ -39150,8 +39193,8 @@ var dnsSeconds = /* @__PURE__ */ dnsUint32.pipe(/* @__PURE__ */ decodeTo2(Durati
39150
39193
  var dnsRecordOfType = (type, fields) => declare((u) => isDnsRecord(u) && u._tag === type, {
39151
39194
  identifier: `Dns${type.charAt(0)}${type.slice(1).toLowerCase()}Record`,
39152
39195
  toCodecJson: () => {
39153
- const json3 = TaggedStruct(type, fields);
39154
- return link3()(json3, transformEffect2({
39196
+ const json4 = TaggedStruct(type, fields);
39197
+ return link3()(json4, transformEffect2({
39155
39198
  decode: (input, options3) => {
39156
39199
  const {
39157
39200
  _tag,
@@ -41502,8 +41545,8 @@ var awaitEmpty = (self) => whileLoop2({
41502
41545
  // ../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Logger.js
41503
41546
  var Logger_exports = {};
41504
41547
  __export(Logger_exports, {
41505
- CurrentLoggers: () => CurrentLoggers2,
41506
- LogToStderr: () => LogToStderr2,
41548
+ CurrentLoggers: () => CurrentLoggers3,
41549
+ LogToStderr: () => LogToStderr3,
41507
41550
  batched: () => batched,
41508
41551
  consoleJson: () => consoleJson,
41509
41552
  consoleLogFmt: () => consoleLogFmt,
@@ -41528,8 +41571,8 @@ __export(Logger_exports, {
41528
41571
  });
41529
41572
  var TypeId56 = "~effect/Logger";
41530
41573
  var isLogger = (u) => hasProperty(u, TypeId56);
41531
- var CurrentLoggers2 = CurrentLoggers;
41532
- var LogToStderr2 = LogToStderr;
41574
+ var CurrentLoggers3 = CurrentLoggers;
41575
+ var LogToStderr3 = LogToStderr;
41533
41576
  var map15 = /* @__PURE__ */ dual(2, (self, f) => loggerMake((options3) => f(self.log(options3))));
41534
41577
  var withConsoleLog = (self) => loggerMake((options3) => {
41535
41578
  const console2 = options3.fiber.getRef(ConsoleRef);
@@ -41653,7 +41696,7 @@ var consoleLogFmt = /* @__PURE__ */ withConsoleLog(formatLogFmt);
41653
41696
  var consoleStructured = /* @__PURE__ */ withConsoleLog(formatStructured);
41654
41697
  var consoleJson = /* @__PURE__ */ withConsoleLog(formatJson2);
41655
41698
  var tracerLogger2 = tracerLogger;
41656
- var layer13 = (loggers, options3) => effect(CurrentLoggers2, withFiber(fnUntraced(function* (fiber3) {
41699
+ var layer13 = (loggers, options3) => effect(CurrentLoggers3, withFiber(fnUntraced(function* (fiber3) {
41657
41700
  const currentLoggers = new Set(options3?.mergeWithExisting === true ? fiber3.getRef(CurrentLoggers) : []);
41658
41701
  for (const logger2 of loggers) {
41659
41702
  currentLoggers.add(isEffect(logger2) ? yield* logger2 : logger2);
@@ -49802,17 +49845,17 @@ var resolveFormatter = /* @__PURE__ */ contextWith2((context3) => succeed7(getOr
49802
49845
  })));
49803
49846
 
49804
49847
  // ../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/cli/internal/lexer.js
49805
- function lex(argv) {
49806
- const endIndex = argv.indexOf("--");
49848
+ function lex(argv2) {
49849
+ const endIndex = argv2.indexOf("--");
49807
49850
  if (endIndex === -1) {
49808
49851
  return {
49809
- tokens: lexTokens(argv),
49852
+ tokens: lexTokens(argv2),
49810
49853
  trailingOperands: []
49811
49854
  };
49812
49855
  }
49813
49856
  return {
49814
- tokens: lexTokens(argv.slice(0, endIndex)),
49815
- trailingOperands: argv.slice(endIndex + 1)
49857
+ tokens: lexTokens(argv2.slice(0, endIndex)),
49858
+ trailingOperands: argv2.slice(endIndex + 1)
49816
49859
  };
49817
49860
  }
49818
49861
  var negativeNumberRegex = /^-(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
@@ -51027,19 +51070,19 @@ var runWith2 = (command, config) => {
51027
51070
  });
51028
51071
  }
51029
51072
  const input = yield* commandImpl.parse(parsedArgs).pipe(toShowHelp);
51030
- let program2 = commandImpl.handle(input, [command.name]);
51073
+ let program = commandImpl.handle(input, [command.name]);
51031
51074
  const logLevel = activeFlags.includes(LogLevel2) ? (yield* LogLevel2.flag.parse(emptyArgs).pipe(toShowHelp))[1] : none2();
51032
- program2 = provideService2(program2, LogLevel2, logLevel);
51075
+ program = provideService2(program, LogLevel2, logLevel);
51033
51076
  for (const flag of activeFlags) {
51034
51077
  if (flag._tag !== "Setting" || flag === LogLevel2) continue;
51035
51078
  const [, value4] = yield* flag.flag.parse(emptyArgs).pipe(toShowHelp);
51036
- program2 = provideService2(program2, flag, value4);
51079
+ program = provideService2(program, flag, value4);
51037
51080
  }
51038
51081
  const services = match(logLevel, {
51039
51082
  onNone: () => empty(),
51040
51083
  onSome: (level) => make5(MinimumLogLevel2, level)
51041
51084
  });
51042
- yield* provideContext2(program2, services);
51085
+ yield* provideContext2(program, services);
51043
51086
  }, catchFilter2((error2) => isCliError(error2) && error2._tag === "ShowHelp" ? succeed2(error2) : fail2(error2), (error2) => andThen4(showHelp(command, error2, config.renderErrors !== false), fail7(error2))), catchFilter2((error2) => {
51044
51087
  if (config.renderErrors === false || !isObjectKeyword(error2)) return fail2(error2);
51045
51088
  const userMessage2 = getUserMessage(error2);
@@ -51342,6 +51385,22 @@ var makeMemoryPublisher = Effect_exports.sync(() => {
51342
51385
  });
51343
51386
 
51344
51387
  // ../../packages/core/src/Telemetry.ts
51388
+ function makeValueCounters() {
51389
+ return {
51390
+ published: Metric_exports.counter("ot_gateway_values_published", {
51391
+ description: "Point values published",
51392
+ incremental: true
51393
+ }),
51394
+ suppressed: Metric_exports.counter("ot_gateway_values_suppressed", {
51395
+ description: "Point values held back in change mode",
51396
+ incremental: true
51397
+ }),
51398
+ pushed: Metric_exports.counter("ot_gateway_pushed_readings", {
51399
+ description: "Values pushed by devices between polls",
51400
+ incremental: true
51401
+ })
51402
+ };
51403
+ }
51345
51404
  var seconds2 = { unit: "seconds" };
51346
51405
  var pollCycles = Metric_exports.counter("ot_gateway_poll_cycles", {
51347
51406
  description: "Polling cycles finished, by outcome",
@@ -51362,14 +51421,8 @@ var publishFailures = Metric_exports.counter("ot_gateway_publish_failures", {
51362
51421
  description: "Messages that failed to publish",
51363
51422
  incremental: true
51364
51423
  });
51365
- var valuesPublished = Metric_exports.counter("ot_gateway_values_published", {
51366
- description: "Point values published",
51367
- incremental: true
51368
- });
51369
- var valuesSuppressed = Metric_exports.counter("ot_gateway_values_suppressed", {
51370
- description: "Point values held back in change mode",
51371
- incremental: true
51372
- });
51424
+ var valuesPublished = makeValueCounters().published;
51425
+ var valuesSuppressed = makeValueCounters().suppressed;
51373
51426
  var deviceLastSuccess = Metric_exports.gauge("ot_gateway_device_last_success_timestamp_seconds", {
51374
51427
  description: "Unix time of the last successful polling cycle of a device",
51375
51428
  attributes: seconds2
@@ -51382,10 +51435,7 @@ var deviceRestarts = Metric_exports.counter("ot_gateway_device_restarts", {
51382
51435
  description: "Device pipelines restarted after a defect",
51383
51436
  incremental: true
51384
51437
  });
51385
- var pushedReadings = Metric_exports.counter("ot_gateway_pushed_readings", {
51386
- description: "Values pushed by devices between polls",
51387
- incremental: true
51388
- });
51438
+ var pushedReadings = makeValueCounters().pushed;
51389
51439
  var pushedPoints = Metric_exports.gauge("ot_gateway_pushed_points", {
51390
51440
  description: "Points kept up to date by device pushes instead of polling",
51391
51441
  attributes: { unit: "{point}" }
@@ -51787,7 +51837,12 @@ var MqttSettings = Schema_exports.Struct({
51787
51837
  clientId: Schema_exports.optionalKey(ConnectString),
51788
51838
  username: Schema_exports.optionalKey(ConnectString),
51789
51839
  /** Name of the environment variable holding the password. Never inline secrets. */
51790
- passwordEnv: Schema_exports.optionalKey(Schema_exports.String)
51840
+ passwordEnv: Schema_exports.optionalKey(Schema_exports.String),
51841
+ /**
51842
+ * The MQTT spoken: `auto` dials with MQTT 5 and falls back to 3.1.1 for a
51843
+ * broker that refuses it; `5` or `3.1.1` speak only that.
51844
+ */
51845
+ version: Schema_exports.Literals(["auto", "5", "3.1.1"]).pipe(Schema_exports.withDecodingDefaultKey(Effect_exports.succeed("auto")))
51791
51846
  });
51792
51847
  var loopbackIpv4 = new RegExp(`^127(\\.${octet}){3}$`);
51793
51848
  var isLoopbackHost = (hostname3) => {
@@ -52954,6 +53009,7 @@ var isRetryable = (driver, error2) => {
52954
53009
  var countCycle = (outcome) => Metric_exports.update(Metric_exports.withAttributes(pollCycles, { outcome }), 1);
52955
53010
  var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
52956
53011
  const publisher = yield* Publisher;
53012
+ const counters = makeValueCounters();
52957
53013
  const points2 = new Map(driver.points.map((p) => [p.id, p]));
52958
53014
  const policies = new Map(driver.points.map((p) => [p.id, publishOf(ctx.publish, p)]));
52959
53015
  const policyOf = (pointId) => policies.get(pointId) ?? everyRead;
@@ -53070,7 +53126,7 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53070
53126
  const sentAt = lastSentAt.get(point.id);
53071
53127
  const quietTooLong = policy2.maxSilenceMs !== void 0 && sentAt !== void 0 && atMono - sentAt >= policy2.maxSilenceMs;
53072
53128
  if (!quietTooLong && !exceedsDeadband(Option_exports.fromUndefinedOr(last2.get(point.id)), value4, policy2.deadband)) {
53073
- return yield* Metric_exports.update(valuesSuppressed, 1);
53129
+ return yield* Metric_exports.update(counters.suppressed, 1);
53074
53130
  }
53075
53131
  if (!(yield* send(point.id, message))) return;
53076
53132
  last2.set(point.id, value4);
@@ -53084,7 +53140,7 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53084
53140
  Effect_exports.as(true),
53085
53141
  Effect_exports.catchTag("PublishError", (error2) => Effect_exports.as(skipRefused(error2), false))
53086
53142
  );
53087
- if (sent) yield* Metric_exports.update(valuesPublished, 1);
53143
+ if (sent) yield* Metric_exports.update(counters.published, 1);
53088
53144
  return sent;
53089
53145
  });
53090
53146
  const closeWindows = Effect_exports.fnUntraced(function* (intervalMs, endMs) {
@@ -53191,7 +53247,7 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53191
53247
  const pushLost = (message, annotations2) => Effect_exports.all([publishFailed("values", message, annotations2), Metric_exports.update(publishFailures, 1)]);
53192
53248
  const pushed = driver.changes === void 0 ? Effect_exports.void : Stream_exports.runForEach(
53193
53249
  driver.changes,
53194
- (reading) => Metric_exports.update(pushedReadings, 1).pipe(
53250
+ (reading) => Metric_exports.update(counters.pushed, 1).pipe(
53195
53251
  // Under the deadline, so a hung publish cannot keep the permit from the polling cycle forever.
53196
53252
  Effect_exports.andThen(handling.withPermit(handleReading(reading)).pipe(deadline("pushed-value"))),
53197
53253
  // The value is lost; the next change, renewal notification or poll brings the point's value again.
@@ -55823,7 +55879,14 @@ var logDefect = (message) => (defect) => Effect_exports.logError(message).pipe(E
55823
55879
  var BACKLOG = 1024;
55824
55880
  var COV_CONCURRENCY = 4;
55825
55881
  var COV_SILENT_IN_A_ROW = 2 * COV_CONCURRENCY;
55826
- var sameAddress = (left, right) => formatInet(left.address) === formatInet(right.address) && left.network?.network === right.network?.network && (left.network?.address ?? []).join(".") === (right.network?.address ?? []).join(".");
55882
+ var sameInet = (left, right) => left.port === right.port && (left._tag === "InetAddressV4" ? right._tag === "InetAddressV4" : right._tag === "InetAddressV6" && left.scopeId === right.scopeId) && left.address[Equal_exports.symbol](right.address);
55883
+ var sameAddress = (left, right) => {
55884
+ if (!sameInet(left.address, right.address)) return false;
55885
+ if (left.network?.network !== right.network?.network) return false;
55886
+ const leftHops = left.network?.address ?? [];
55887
+ const rightHops = right.network?.address ?? [];
55888
+ return leftHops.length === rightHops.length && leftHops.every((byte, index2) => byte === rightHops[index2]);
55889
+ };
55827
55890
  var describeObject = (object) => `${nameOf(ObjectType, object.objectType)}:${object.instance}`;
55828
55891
  var OTHER_DEVICE = "for another device";
55829
55892
  var makeCovSubscriptions = (deps) => {
@@ -57849,8 +57912,9 @@ var decodeVariableByteInteger = (bytes3, offset = 0) => {
57849
57912
  }
57850
57913
  return new MqttCodecError({ message: "malformed variable byte integer" });
57851
57914
  };
57915
+ var utf82 = new TextEncoder();
57852
57916
  var encodeUtf8String = (value4) => {
57853
- const encoded = new TextEncoder().encode(value4);
57917
+ const encoded = utf82.encode(value4);
57854
57918
  if (encoded.length > 65535) throw new RangeError("string too long");
57855
57919
  const out = new Uint8Array(2 + encoded.length);
57856
57920
  new DataView(out.buffer).setUint16(0, encoded.length);
@@ -58109,14 +58173,20 @@ var makeFrameReader = (maximumPacketSize = Number.POSITIVE_INFINITY) => {
58109
58173
  };
58110
58174
  var encodeConnect = (connect2) => {
58111
58175
  const flags = (connect2.username === void 0 ? 0 : 128) | (connect2.password === void 0 ? 0 : 64) | (connect2.will?.retain === true ? 32 : 0) | (connect2.will?.qos ?? 0) << 3 | (connect2.will === void 0 ? 0 : 4) | (connect2.cleanStart ? 2 : 0);
58112
- const body = new Writer2().string("MQTT").byte(5).byte(flags).u16(connect2.keepAliveSeconds).bytes(
58113
- encodeProperties((w) => {
58114
- w.byte(Property.SessionExpiryInterval).u32(connect2.sessionExpirySeconds);
58115
- if (connect2.maximumPacketSize !== void 0) w.byte(Property.MaximumPacketSize).u32(connect2.maximumPacketSize);
58116
- })
58117
- ).string(connect2.clientId);
58176
+ const v5 = (connect2.protocolVersion ?? 5) === 5;
58177
+ const body = new Writer2().string("MQTT").byte(v5 ? 5 : 4).byte(flags).u16(connect2.keepAliveSeconds);
58178
+ if (v5) {
58179
+ body.bytes(
58180
+ encodeProperties((w) => {
58181
+ w.byte(Property.SessionExpiryInterval).u32(connect2.sessionExpirySeconds);
58182
+ if (connect2.maximumPacketSize !== void 0) w.byte(Property.MaximumPacketSize).u32(connect2.maximumPacketSize);
58183
+ })
58184
+ );
58185
+ }
58186
+ body.string(connect2.clientId);
58118
58187
  if (connect2.will !== void 0) {
58119
- body.bytes(encodeProperties((w) => w.byte(Property.PayloadFormatIndicator).byte(1))).string(connect2.will.topic).binary(encoder9.encode(connect2.will.payload));
58188
+ if (v5) body.bytes(encodeProperties((w) => w.byte(Property.PayloadFormatIndicator).byte(1)));
58189
+ body.string(connect2.will.topic).binary(encoder9.encode(connect2.will.payload));
58120
58190
  }
58121
58191
  if (connect2.username !== void 0) body.string(connect2.username);
58122
58192
  if (connect2.password !== void 0) body.binary(encoder9.encode(connect2.password));
@@ -58125,16 +58195,17 @@ var encodeConnect = (connect2) => {
58125
58195
  var decodeConnect = (body) => decodeWith2(body, (r) => {
58126
58196
  const protocol = r.string();
58127
58197
  const level = r.byte();
58128
- if (protocol !== "MQTT" || level !== 5) {
58198
+ if (protocol !== "MQTT" || level !== 5 && level !== 4) {
58129
58199
  throw new MqttCodecError({ message: `unsupported protocol ${protocol} level ${level}` });
58130
58200
  }
58201
+ const v5 = level === 5;
58131
58202
  const flags = r.byte();
58132
58203
  const keepAliveSeconds = r.u16();
58133
- const properties = r.properties();
58204
+ const properties = v5 ? r.properties() : /* @__PURE__ */ new Map();
58134
58205
  const clientId = r.string();
58135
58206
  let will;
58136
58207
  if ((flags & 4) !== 0) {
58137
- r.properties();
58208
+ if (v5) r.properties();
58138
58209
  const topic = r.string();
58139
58210
  const payload = decoder4.decode(r.binary());
58140
58211
  will = { topic, payload, qos: flags >> 3 & 1 ? 1 : 0, retain: (flags & 32) !== 0 };
@@ -58144,6 +58215,7 @@ var decodeConnect = (body) => decodeWith2(body, (r) => {
58144
58215
  const expiry = properties.get(Property.SessionExpiryInterval);
58145
58216
  const maximumPacketSize = properties.get(Property.MaximumPacketSize);
58146
58217
  return {
58218
+ protocolVersion: v5 ? 5 : 4,
58147
58219
  clientId,
58148
58220
  keepAliveSeconds,
58149
58221
  cleanStart: (flags & 2) !== 0,
@@ -58154,26 +58226,39 @@ var decodeConnect = (body) => decodeWith2(body, (r) => {
58154
58226
  ...will === void 0 ? {} : { will }
58155
58227
  };
58156
58228
  });
58157
- var decodeConnack = (body) => decodeWith2(body, (r) => ({
58158
- sessionPresent: (r.byte() & 1) !== 0,
58159
- reasonCode: r.byte(),
58160
- properties: r.remaining > 0 ? r.properties() : /* @__PURE__ */ new Map()
58161
- }));
58162
- var encodeConnack = (reasonCode, properties = /* @__PURE__ */ new Map()) => packet(
58163
- PacketType.CONNACK,
58164
- 0,
58165
- new Writer2().byte(0).byte(reasonCode).bytes(
58166
- encodeProperties((w) => {
58167
- for (const [id2, value4] of properties) {
58168
- w.byte(id2);
58169
- const kind = propertyKinds[id2];
58170
- if (kind === "u16") w.u16(value4);
58171
- else if (kind === "u32") w.u32(value4);
58172
- else w.byte(value4);
58173
- }
58174
- })
58175
- ).toBytes()
58176
- );
58229
+ var returnCodeReasons = { 1: 132, 2: 133, 3: 136, 4: 134, 5: 135 };
58230
+ var reasonReturnCodes = { 132: 1, 133: 2, 136: 3, 134: 4, 135: 5 };
58231
+ var decodeConnack = (body, version2 = 5) => decodeWith2(body, (r) => {
58232
+ const sessionPresent = (r.byte() & 1) !== 0;
58233
+ const code = r.byte();
58234
+ if (version2 === 4) {
58235
+ return { sessionPresent, reasonCode: code === 0 ? 0 : returnCodeReasons[code] ?? 128, properties: /* @__PURE__ */ new Map() };
58236
+ }
58237
+ return { sessionPresent, reasonCode: code, properties: r.remaining > 0 ? r.properties() : /* @__PURE__ */ new Map() };
58238
+ });
58239
+ var refusesProtocolLevel = (connack) => connack.reasonCode === 132 || connack.reasonCode === 1;
58240
+ var encodeConnack = (reasonCode, properties = /* @__PURE__ */ new Map(), version2 = 5) => {
58241
+ if (version2 === 4) {
58242
+ const returnCode = reasonCode === 0 ? 0 : reasonReturnCodes[reasonCode] ?? 3;
58243
+ return packet(PacketType.CONNACK, 0, Uint8Array.of(0, returnCode));
58244
+ }
58245
+ return packet(
58246
+ PacketType.CONNACK,
58247
+ 0,
58248
+ new Writer2().byte(0).byte(reasonCode).bytes(
58249
+ encodeProperties((w) => {
58250
+ for (const [id2, value4] of properties) {
58251
+ w.byte(id2);
58252
+ const kind = propertyKinds[id2];
58253
+ if (kind === "u16") w.u16(value4);
58254
+ else if (kind === "u32") w.u32(value4);
58255
+ else w.byte(value4);
58256
+ }
58257
+ })
58258
+ ).toBytes()
58259
+ );
58260
+ };
58261
+ var encodeUnsupportedLevelConnack = () => packet(PacketType.CONNACK, 0, Uint8Array.of(0, 1));
58177
58262
  var connackReasonName = (code) => ({
58178
58263
  128: "unspecified error",
58179
58264
  129: "malformed packet",
@@ -58190,27 +58275,82 @@ var connackReasonName = (code) => ({
58190
58275
  151: "quota exceeded",
58191
58276
  159: "connection rate exceeded"
58192
58277
  })[code] ?? `reason code 0x${code.toString(16)}`;
58193
- var encodePublish = (publish2) => {
58194
- const body = new Writer2().string(publish2.topic);
58195
- if (publish2.qos > 0) body.u16(publish2.packetId ?? 0);
58196
- body.bytes(
58197
- encodeProperties((w) => {
58198
- w.byte(Property.PayloadFormatIndicator).byte(1);
58199
- if (publish2.messageExpirySeconds !== void 0) {
58200
- w.byte(Property.MessageExpiryInterval).u32(publish2.messageExpirySeconds);
58201
- }
58202
- if (publish2.responseTopic !== void 0) w.byte(Property.ResponseTopic).string(publish2.responseTopic);
58203
- if (publish2.correlationData !== void 0) w.byte(Property.CorrelationData).binary(publish2.correlationData);
58204
- })
58205
- ).bytes(publish2.payload);
58206
- return packet(PacketType.PUBLISH, publish2.qos << 1 | (publish2.retain ? 1 : 0), body.toBytes());
58278
+ var encodePublish = (publish2, version2 = 5) => {
58279
+ const topic = utf8String(publish2.topic);
58280
+ const withProperties = version2 === 5;
58281
+ const responseTopic = withProperties && publish2.responseTopic !== void 0 ? utf8String(publish2.responseTopic) : void 0;
58282
+ const expiry = withProperties ? publish2.messageExpirySeconds : void 0;
58283
+ const correlation = withProperties ? publish2.correlationData : void 0;
58284
+ let propertiesLength = 0;
58285
+ if (withProperties) {
58286
+ propertiesLength = 2;
58287
+ if (expiry !== void 0) propertiesLength += 5;
58288
+ if (responseTopic !== void 0) propertiesLength += 3 + responseTopic.length;
58289
+ if (correlation !== void 0) propertiesLength += 3 + correlation.length;
58290
+ }
58291
+ const bodyLength = 2 + topic.length + (publish2.qos > 0 ? 2 : 0) + (withProperties ? variableByteIntegerLength(propertiesLength) + propertiesLength : 0) + publish2.payload.length;
58292
+ const out = new Uint8Array(1 + variableByteIntegerLength(bodyLength) + bodyLength);
58293
+ out[0] = PacketType.PUBLISH << 4 | publish2.qos << 1 | (publish2.retain ? 1 : 0);
58294
+ let offset = writeVariableByteInteger(out, 1, bodyLength);
58295
+ offset = writeU16(out, offset, topic.length);
58296
+ out.set(topic, offset);
58297
+ offset += topic.length;
58298
+ if (publish2.qos > 0) offset = writeU16(out, offset, publish2.packetId ?? 0);
58299
+ if (withProperties) {
58300
+ offset = writeVariableByteInteger(out, offset, propertiesLength);
58301
+ out[offset++] = Property.PayloadFormatIndicator;
58302
+ out[offset++] = 1;
58303
+ if (expiry !== void 0) {
58304
+ out[offset++] = Property.MessageExpiryInterval;
58305
+ new DataView(out.buffer).setUint32(offset, expiry >>> 0);
58306
+ offset += 4;
58307
+ }
58308
+ if (responseTopic !== void 0) {
58309
+ out[offset++] = Property.ResponseTopic;
58310
+ offset = writeU16(out, offset, responseTopic.length);
58311
+ out.set(responseTopic, offset);
58312
+ offset += responseTopic.length;
58313
+ }
58314
+ if (correlation !== void 0) {
58315
+ out[offset++] = Property.CorrelationData;
58316
+ offset = writeU16(out, offset, correlation.length);
58317
+ out.set(correlation, offset);
58318
+ offset += correlation.length;
58319
+ }
58320
+ }
58321
+ out.set(publish2.payload, offset);
58322
+ return out;
58207
58323
  };
58208
- var decodePublish = (flags, body) => decodeWith2(body, (r) => {
58324
+ var utf8String = (value4) => {
58325
+ const bytes3 = encoder9.encode(value4);
58326
+ if (bytes3.length > 65535) throw new RangeError("string too long");
58327
+ return bytes3;
58328
+ };
58329
+ var variableByteIntegerLength = (value4) => {
58330
+ if (value4 > MAX_VARIABLE_BYTE_INTEGER) throw new RangeError(`value out of range: ${value4}`);
58331
+ return value4 < 128 ? 1 : value4 < 16384 ? 2 : value4 < 2097152 ? 3 : 4;
58332
+ };
58333
+ var writeVariableByteInteger = (out, offset, value4) => {
58334
+ let rest = value4;
58335
+ do {
58336
+ let byte = rest % 128;
58337
+ rest = Math.floor(rest / 128);
58338
+ if (rest > 0) byte |= 128;
58339
+ out[offset++] = byte;
58340
+ } while (rest > 0);
58341
+ return offset;
58342
+ };
58343
+ var writeU16 = (out, offset, value4) => {
58344
+ out[offset] = value4 >> 8 & 255;
58345
+ out[offset + 1] = value4 & 255;
58346
+ return offset + 2;
58347
+ };
58348
+ var decodePublish = (flags, body, version2 = 5) => decodeWith2(body, (r) => {
58209
58349
  const qos = flags >> 1 & 3;
58210
58350
  if (qos > 1) throw new MqttCodecError({ message: `QoS ${qos} is not supported` });
58211
58351
  const topic = r.string();
58212
58352
  const packetId = qos > 0 ? r.u16() : void 0;
58213
- const properties = r.properties();
58353
+ const properties = version2 === 5 ? r.properties() : /* @__PURE__ */ new Map();
58214
58354
  const expiry = properties.get(Property.MessageExpiryInterval);
58215
58355
  const responseTopic = properties.get(Property.ResponseTopic);
58216
58356
  const correlationData = properties.get(Property.CorrelationData);
@@ -58227,29 +58367,34 @@ var decodePublish = (flags, body) => decodeWith2(body, (r) => {
58227
58367
  });
58228
58368
  var pubackRefusesMessage = (reasonCode) => reasonCode === 135 || reasonCode === 144 || reasonCode === 149 || reasonCode === 153;
58229
58369
  var decodePuback = (body) => decodeWith2(body, (r) => ({ packetId: r.u16(), reasonCode: r.remaining > 0 ? r.byte() : 0 }));
58230
- var encodePuback = (packetId, reasonCode = 0) => packet(
58370
+ var encodePuback = (packetId, reasonCode = 0, version2 = 5) => version2 === 4 ? packet(PacketType.PUBACK, 0, new Writer2().u16(packetId).toBytes()) : packet(
58231
58371
  PacketType.PUBACK,
58232
58372
  0,
58233
58373
  new Writer2().u16(packetId).byte(reasonCode).bytes(encodeProperties(() => {
58234
58374
  })).toBytes()
58235
58375
  );
58236
- var encodeSubscribe = (subscribe2) => {
58237
- const body = new Writer2().u16(subscribe2.packetId).bytes(encodeProperties(() => {
58376
+ var encodeSubscribe = (subscribe2, version2 = 5) => {
58377
+ const body = new Writer2().u16(subscribe2.packetId);
58378
+ if (version2 === 5) body.bytes(encodeProperties(() => {
58238
58379
  }));
58239
58380
  for (const { filter: filter14, qos, retainAsPublished, noLocal } of subscribe2.subscriptions) {
58240
- body.string(filter14).byte(qos | (noLocal === true ? 4 : 0) | (retainAsPublished === true ? 8 : 0));
58381
+ const options3 = version2 === 5 ? qos | (noLocal === true ? 4 : 0) | (retainAsPublished === true ? 8 : 0) : qos;
58382
+ body.string(filter14).byte(options3);
58241
58383
  }
58242
58384
  return packet(PacketType.SUBSCRIBE, 2, body.toBytes());
58243
58385
  };
58244
- var decodeSubscribe = (body) => decodeWith2(body, (r) => {
58386
+ var decodeSubscribe = (body, version2 = 5) => decodeWith2(body, (r) => {
58245
58387
  const packetId = r.u16();
58246
- r.properties();
58388
+ if (version2 === 5) r.properties();
58247
58389
  const subscriptions = [];
58248
58390
  while (r.remaining > 0) {
58249
58391
  const filter14 = r.string();
58250
58392
  const options3 = r.byte();
58251
58393
  const qos = options3 & 3;
58252
58394
  if (qos > 1) throw new MqttCodecError({ message: `QoS ${qos} is not supported` });
58395
+ if (version2 === 4 && (options3 & 252) !== 0) {
58396
+ throw new MqttCodecError({ message: "reserved bits set in a subscription's options" });
58397
+ }
58253
58398
  subscriptions.push({
58254
58399
  filter: filter14,
58255
58400
  qos: qos === 1 ? 1 : 0,
@@ -58260,15 +58405,16 @@ var decodeSubscribe = (body) => decodeWith2(body, (r) => {
58260
58405
  if (subscriptions.length === 0) throw new MqttCodecError({ message: "SUBSCRIBE without a topic filter" });
58261
58406
  return { packetId, subscriptions };
58262
58407
  });
58263
- var encodeSuback = (suback) => packet(
58264
- PacketType.SUBACK,
58265
- 0,
58266
- new Writer2().u16(suback.packetId).bytes(encodeProperties(() => {
58267
- })).bytes(Uint8Array.from(suback.reasonCodes)).toBytes()
58268
- );
58269
- var decodeSuback = (body) => decodeWith2(body, (r) => {
58408
+ var encodeSuback = (suback, version2 = 5) => {
58409
+ const body = new Writer2().u16(suback.packetId);
58410
+ if (version2 === 5) body.bytes(encodeProperties(() => {
58411
+ }));
58412
+ const codes3 = version2 === 5 ? suback.reasonCodes : suback.reasonCodes.map((code) => code >= 128 ? 128 : code);
58413
+ return packet(PacketType.SUBACK, 0, body.bytes(Uint8Array.from(codes3)).toBytes());
58414
+ };
58415
+ var decodeSuback = (body, version2 = 5) => decodeWith2(body, (r) => {
58270
58416
  const packetId = r.u16();
58271
- r.properties();
58417
+ if (version2 === 5) r.properties();
58272
58418
  return { packetId, reasonCodes: [...r.rest()] };
58273
58419
  });
58274
58420
  var topicMatches = (filter14, topic) => {
@@ -58285,7 +58431,7 @@ var topicMatches = (filter14, topic) => {
58285
58431
  };
58286
58432
  var encodePingreq = () => Uint8Array.of(PacketType.PINGREQ << 4, 0);
58287
58433
  var encodePingresp = () => Uint8Array.of(PacketType.PINGRESP << 4, 0);
58288
- var encodeDisconnect = (reasonCode = 0) => reasonCode === 0 ? Uint8Array.of(PacketType.DISCONNECT << 4, 0) : packet(PacketType.DISCONNECT, 0, Uint8Array.of(reasonCode, 0));
58434
+ var encodeDisconnect = (reasonCode = 0, version2 = 5) => reasonCode === 0 || version2 === 4 ? Uint8Array.of(PacketType.DISCONNECT << 4, 0) : packet(PacketType.DISCONNECT, 0, Uint8Array.of(reasonCode, 0));
58289
58435
  var decodeDisconnect = (body) => decodeWith2(body, (r) => {
58290
58436
  const reasonCode = r.remaining > 0 ? r.byte() : 0;
58291
58437
  const reason = r.remaining > 0 ? r.properties().get(Property.ReasonString) : void 0;
@@ -58302,6 +58448,8 @@ var MqttRejected = class extends Schema_exports.TaggedError()("MqttRejected", {
58302
58448
  message: Schema_exports.String
58303
58449
  }) {
58304
58450
  };
58451
+ var MqttDowngrade = class extends Schema_exports.TaggedError()("MqttDowngrade", {}) {
58452
+ };
58305
58453
  var MqttPublishError = class extends Schema_exports.TaggedError()("MqttPublishError", {
58306
58454
  topic: Schema_exports.String,
58307
58455
  reason: Schema_exports.Literals(["unavailable", "rejected"]),
@@ -58322,7 +58470,7 @@ var countConnect3 = (outcome) => Metric_exports.update(Metric_exports.withAttrib
58322
58470
  var topicProblem = (topic) => {
58323
58471
  if (topic.length === 0) return "topic is empty";
58324
58472
  if (topic.includes("+") || topic.includes("#")) return "topic contains a wildcard";
58325
- if (encoder10.encode(topic).length > 65535) return "topic is longer than 65,535 bytes";
58473
+ if (topic.length > 65535 / 3 && encoder10.encode(topic).length > 65535) return "topic is longer than 65,535 bytes";
58326
58474
  return void 0;
58327
58475
  };
58328
58476
  var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, options3) {
@@ -58334,7 +58482,11 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58334
58482
  const maxDelay = Duration_exports.toMillis(Duration_exports.fromInputUnsafe(options3.reconnectDelay?.max ?? "15 seconds"));
58335
58483
  const connected = yield* Latch_exports.make(false);
58336
58484
  const firstDialDone = yield* Latch_exports.make(false);
58485
+ const firstDial = Deferred_exports.makeUnsafe();
58337
58486
  let session;
58487
+ let version2 = options3.protocolVersion === "3.1.1" ? 4 : 5;
58488
+ let lastTurn = Deferred_exports.makeUnsafe();
58489
+ Deferred_exports.doneUnsafe(lastTurn, Effect_exports.void);
58338
58490
  const runSession = (onConnected) => Effect_exports.scoped(
58339
58491
  Effect_exports.gen(function* () {
58340
58492
  const { pull } = yield* socket.reader;
@@ -58352,10 +58504,13 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58352
58504
  ),
58353
58505
  Deferred_exports.await(closed)
58354
58506
  );
58355
- const protocolError = (reasonCode, message) => write2(encodeDisconnect(reasonCode)).pipe(
58356
- Effect_exports.timeoutOrElse({ duration: "1 second", orElse: () => Effect_exports.void }),
58357
- Effect_exports.catchTag("MqttConnectionError", () => Effect_exports.void),
58358
- Effect_exports.andThen(Effect_exports.fail(new MqttConnectionError({ message })))
58507
+ const protocolError = (reasonCode, message) => (
58508
+ // 3.1.1 has no reason to send, and its DISCONNECT discards the will: there, only close (3.1.1 §4.8).
58509
+ (version2 === 4 ? Effect_exports.void : write2(encodeDisconnect(reasonCode))).pipe(
58510
+ Effect_exports.timeoutOrElse({ duration: "1 second", orElse: () => Effect_exports.void }),
58511
+ Effect_exports.catchTag("MqttConnectionError", () => Effect_exports.void),
58512
+ Effect_exports.andThen(Effect_exports.fail(new MqttConnectionError({ message })))
58513
+ )
58359
58514
  );
58360
58515
  const frames = makeFrameReader(maximumPacketSize);
58361
58516
  const nextPacket = Effect_exports.gen(function* () {
@@ -58381,8 +58536,10 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58381
58536
  (error2) => Effect_exports.fail(new MqttConnectionError({ message: describeSocketError(error2) }))
58382
58537
  )
58383
58538
  );
58539
+ const dialedWith = version2;
58384
58540
  yield* write2(
58385
58541
  encodeConnect({
58542
+ protocolVersion: dialedWith,
58386
58543
  clientId: options3.clientId,
58387
58544
  keepAliveSeconds,
58388
58545
  cleanStart: true,
@@ -58398,7 +58555,7 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58398
58555
  if (packet2.type !== PacketType.CONNACK) {
58399
58556
  return yield* new MqttConnectionError({ message: `expected CONNACK, got packet type ${packet2.type}` });
58400
58557
  }
58401
- const decoded = decodeConnack(packet2.body);
58558
+ const decoded = decodeConnack(packet2.body, dialedWith);
58402
58559
  if (Result_exports.isFailure(decoded)) {
58403
58560
  return yield* new MqttConnectionError({ message: `unreadable CONNACK: ${decoded.failure.message}` });
58404
58561
  }
@@ -58409,6 +58566,16 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58409
58566
  orElse: () => Effect_exports.fail(new MqttConnectionError({ message: "no CONNACK in time" }))
58410
58567
  })
58411
58568
  );
58569
+ if (dialedWith === 5 && refusesProtocolLevel(connack)) {
58570
+ if (options3.protocolVersion === "5") {
58571
+ return yield* new MqttRejected({
58572
+ reasonCode: 132,
58573
+ message: "broker refused the connection: it does not speak MQTT 5 (set mqtt.version to 3.1.1 or auto)"
58574
+ });
58575
+ }
58576
+ version2 = 4;
58577
+ return yield* new MqttDowngrade();
58578
+ }
58412
58579
  if (connack.reasonCode >= 128) {
58413
58580
  return yield* new MqttRejected({
58414
58581
  reasonCode: connack.reasonCode,
@@ -58422,11 +58589,23 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58422
58589
  if (props.get(Property.MaximumPacketSize) === 0) {
58423
58590
  return yield* protocolError(130, "broker sent Maximum Packet Size 0 in CONNACK, a protocol error");
58424
58591
  }
58592
+ const receiveMaximum = Math.min(numberProperty(props, Property.ReceiveMaximum, 65535), 1e3);
58593
+ const announcedPacketSize = props.get(Property.MaximumPacketSize);
58594
+ const effectiveKeepAlive = numberProperty(props, Property.ServerKeepAlive, keepAliveSeconds);
58425
58595
  const current = {
58596
+ version: dialedWith,
58597
+ info: {
58598
+ protocolVersion: dialedWith === 5 ? "5" : "3.1.1",
58599
+ receiveMaximum,
58600
+ maximumQoS: numberProperty(props, Property.MaximumQoS, 2) === 0 ? 0 : 1,
58601
+ retainAvailable: numberProperty(props, Property.RetainAvailable, 1) === 1,
58602
+ ...typeof announcedPacketSize === "number" ? { maximumPacketSize: announcedPacketSize } : {},
58603
+ keepAliveSeconds: effectiveKeepAlive
58604
+ },
58426
58605
  write: write2,
58427
58606
  inflight: /* @__PURE__ */ new Map(),
58428
58607
  // Receive Maximum bounds unacknowledged QoS 1 publishes (§3.2.2.3.3).
58429
- inflightLimit: yield* Semaphore_exports.make(Math.min(numberProperty(props, Property.ReceiveMaximum, 65535), 1e3)),
58608
+ inflightLimit: yield* Semaphore_exports.make(receiveMaximum),
58430
58609
  maximumQoS: numberProperty(props, Property.MaximumQoS, 2) === 0 ? 0 : 1,
58431
58610
  retainAvailable: numberProperty(props, Property.RetainAvailable, 1) === 1,
58432
58611
  maximumPacketSize: numberProperty(props, Property.MaximumPacketSize, Number.POSITIVE_INFINITY),
@@ -58435,7 +58614,6 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58435
58614
  pubackTimeouts: 0,
58436
58615
  droppedForSilence: false
58437
58616
  };
58438
- const effectiveKeepAlive = numberProperty(props, Property.ServerKeepAlive, keepAliveSeconds);
58439
58617
  const pingSeconds = effectiveKeepAlive > 0 ? effectiveKeepAlive : keepAliveSeconds;
58440
58618
  yield* Effect_exports.addFinalizer(
58441
58619
  (exit3) => Effect_exports.gen(function* () {
@@ -58468,6 +58646,7 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58468
58646
  yield* Effect_exports.logInfo("connected to MQTT broker").pipe(
58469
58647
  Effect_exports.annotateLogs({
58470
58648
  keepAlive: effectiveKeepAlive,
58649
+ ...dialedWith === 4 ? { mqtt: "3.1.1" } : {},
58471
58650
  ...failedBefore > 0 ? { failedDials: failedBefore } : {}
58472
58651
  })
58473
58652
  );
@@ -58476,7 +58655,7 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58476
58655
  if (subscriptions.length > 0) {
58477
58656
  const packetId = current.nextPacketId;
58478
58657
  current.nextPacketId = packetId % 65535 + 1;
58479
- yield* write2(encodeSubscribe({ packetId, subscriptions }));
58658
+ yield* write2(encodeSubscribe({ packetId, subscriptions }, dialedWith));
58480
58659
  }
58481
58660
  let lastReceived = yield* monotonicMillis;
58482
58661
  const readLoop2 = Effect_exports.gen(function* () {
@@ -58499,12 +58678,12 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58499
58678
  return yield* new MqttConnectionError({ message: `broker disconnected: ${reason}` });
58500
58679
  }
58501
58680
  case PacketType.PUBLISH: {
58502
- const publish3 = decodePublish(packet2.flags, packet2.body);
58681
+ const publish3 = decodePublish(packet2.flags, packet2.body, dialedWith);
58503
58682
  if (Result_exports.isFailure(publish3)) {
58504
58683
  return yield* protocolError(129, `unreadable PUBLISH: ${publish3.failure.message}`);
58505
58684
  }
58506
58685
  const { topic, payload, retain, packetId, messageExpirySeconds, responseTopic, correlationData } = publish3.success;
58507
- if (packetId !== void 0) yield* write2(encodePuback(packetId));
58686
+ if (packetId !== void 0) yield* write2(encodePuback(packetId, 0, dialedWith));
58508
58687
  if (options3.onMessage !== void 0) {
58509
58688
  yield* options3.onMessage({
58510
58689
  topic,
@@ -58518,7 +58697,7 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58518
58697
  break;
58519
58698
  }
58520
58699
  case PacketType.SUBACK: {
58521
- const suback = decodeSuback(packet2.body);
58700
+ const suback = decodeSuback(packet2.body, dialedWith);
58522
58701
  const refused = Result_exports.isSuccess(suback) ? subscriptions.filter((_, index2) => (suback.success.reasonCodes[index2] ?? 128) >= 128) : subscriptions;
58523
58702
  if (refused.length > 0) {
58524
58703
  yield* Effect_exports.logError(
@@ -58570,15 +58749,21 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58570
58749
  });
58571
58750
  while (true) {
58572
58751
  let connectedAt;
58573
- yield* runSession((at) => {
58752
+ const outcome = yield* runSession((at) => {
58574
58753
  connectedAt = at;
58754
+ Deferred_exports.doneUnsafe(firstDial, Effect_exports.void);
58575
58755
  unreachable = void 0;
58576
58756
  const dials = failedDials;
58577
58757
  failedDials = 0;
58578
58758
  return dials;
58579
58759
  }).pipe(
58580
58760
  Effect_exports.catchTags({
58581
- MqttRejected: (error2) => countConnect3("rejected").pipe(
58761
+ MqttDowngrade: () => Effect_exports.as(
58762
+ Effect_exports.logInfo("MQTT broker does not speak MQTT 5, connecting with MQTT 3.1.1"),
58763
+ "redial"
58764
+ ),
58765
+ MqttRejected: (error2) => Effect_exports.sync(() => Deferred_exports.doneUnsafe(firstDial, Effect_exports.fail(error2))).pipe(
58766
+ Effect_exports.andThen(countConnect3("rejected")),
58582
58767
  Effect_exports.andThen(
58583
58768
  dialFailed(
58584
58769
  `rejected ${error2.reasonCode}`,
@@ -58588,7 +58773,8 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58588
58773
  )
58589
58774
  )
58590
58775
  ),
58591
- MqttConnectionError: (error2) => connectedAt !== void 0 ? Effect_exports.logWarning("MQTT connection lost").pipe(Effect_exports.annotateLogs({ error: error2.message })) : countConnect3("failed").pipe(
58776
+ MqttConnectionError: (error2) => connectedAt !== void 0 ? Effect_exports.logWarning("MQTT connection lost").pipe(Effect_exports.annotateLogs({ error: error2.message })) : Effect_exports.sync(() => Deferred_exports.doneUnsafe(firstDial, Effect_exports.fail(error2))).pipe(
58777
+ Effect_exports.andThen(countConnect3("failed")),
58592
58778
  Effect_exports.andThen(
58593
58779
  dialFailed(
58594
58780
  "unreachable",
@@ -58600,6 +58786,7 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58600
58786
  )
58601
58787
  })
58602
58788
  );
58789
+ if (outcome === "redial") continue;
58603
58790
  yield* Latch_exports.open(firstDialDone);
58604
58791
  const heldFor = connectedAt === void 0 ? 0 : (yield* monotonicMillis) - connectedAt;
58605
58792
  failures = heldFor >= stableConnectionMs ? 0 : failures + 1;
@@ -58611,16 +58798,26 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58611
58798
  let sent = false;
58612
58799
  let blameless = false;
58613
58800
  let used;
58801
+ const previousTurn = lastTurn;
58802
+ const turn = Deferred_exports.makeUnsafe();
58803
+ lastTurn = turn;
58804
+ const passTurn = Effect_exports.sync(() => Deferred_exports.doneUnsafe(turn, Effect_exports.void));
58614
58805
  return Effect_exports.gen(function* () {
58615
58806
  const rejected3 = (message) => new MqttPublishError({ topic, reason: "rejected", message });
58616
58807
  const problem = topicProblem(topic);
58617
58808
  if (problem !== void 0) return yield* rejected3(problem);
58618
- yield* (options3.waitForConnection === false ? firstDialDone : connected).await.pipe(
58619
- Effect_exports.timeoutOrElse({
58620
- duration: publishTimeout,
58621
- orElse: () => Effect_exports.fail(new MqttConnectionError({ message: "not connected to the broker" }))
58622
- })
58623
- );
58809
+ const notConnected = () => new MqttConnectionError({ message: "not connected to the broker" });
58810
+ const withinPublishTimeout = Effect_exports.timeoutOrElse({
58811
+ duration: publishTimeout,
58812
+ orElse: () => Effect_exports.fail(notConnected())
58813
+ });
58814
+ if (options3.waitForConnection === false) {
58815
+ yield* firstDialDone.await.pipe(withinPublishTimeout);
58816
+ if (session === void 0) return yield* notConnected();
58817
+ yield* Deferred_exports.await(previousTurn).pipe(withinPublishTimeout);
58818
+ } else {
58819
+ yield* Deferred_exports.await(previousTurn).pipe(Effect_exports.andThen(connected.await), withinPublishTimeout);
58820
+ }
58624
58821
  const current = session;
58625
58822
  if (current === void 0) return yield* new MqttConnectionError({ message: "not connected to the broker" });
58626
58823
  used = current;
@@ -58632,11 +58829,11 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58632
58829
  const bytes3 = encoder10.encode(payload);
58633
58830
  const correlation = publishOptions.correlationData === void 0 ? {} : { correlationData: publishOptions.correlationData };
58634
58831
  if (qos === 0) {
58635
- const packet2 = encodePublish({ topic, payload: bytes3, qos: 0, retain, ...correlation });
58832
+ const packet2 = encodePublish({ topic, payload: bytes3, qos: 0, retain, ...correlation }, current.version);
58636
58833
  if (packet2.length > current.maximumPacketSize) {
58637
58834
  return yield* rejected3(`message exceeds the broker's ${current.maximumPacketSize} byte limit`);
58638
58835
  }
58639
- return yield* current.write(packet2);
58836
+ return yield* current.write(packet2).pipe(Effect_exports.ensuring(passTurn));
58640
58837
  }
58641
58838
  const reasonCode = yield* Semaphore_exports.withPermit(
58642
58839
  current.inflightLimit,
@@ -58644,14 +58841,17 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58644
58841
  let packetId = current.nextPacketId;
58645
58842
  while (current.inflight.has(packetId)) packetId = packetId % 65535 + 1;
58646
58843
  current.nextPacketId = packetId % 65535 + 1;
58647
- const packet2 = encodePublish({ topic, payload: bytes3, qos: 1, retain, packetId, ...correlation });
58844
+ const packet2 = encodePublish(
58845
+ { topic, payload: bytes3, qos: 1, retain, packetId, ...correlation },
58846
+ current.version
58847
+ );
58648
58848
  if (packet2.length > current.maximumPacketSize) {
58649
58849
  return yield* rejected3(`message exceeds the broker's ${current.maximumPacketSize} byte limit`);
58650
58850
  }
58651
58851
  const acked = yield* Deferred_exports.make();
58652
58852
  current.inflight.set(packetId, acked);
58653
58853
  return yield* Effect_exports.gen(function* () {
58654
- yield* current.write(packet2);
58854
+ yield* current.write(packet2).pipe(Effect_exports.ensuring(passTurn));
58655
58855
  sent = true;
58656
58856
  return yield* Deferred_exports.await(acked);
58657
58857
  }).pipe(Effect_exports.ensuring(Effect_exports.sync(() => current.inflight.delete(packetId))));
@@ -58680,6 +58880,7 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58680
58880
  return yield* new MqttPublishError({ topic, reason: "unavailable", message });
58681
58881
  }
58682
58882
  }).pipe(
58883
+ Effect_exports.ensuring(passTurn),
58683
58884
  Effect_exports.catchTag(
58684
58885
  "MqttConnectionError",
58685
58886
  (error2) => Effect_exports.fail(
@@ -58693,7 +58894,12 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58693
58894
  )
58694
58895
  );
58695
58896
  });
58696
- const client = { publish: publish2, isConnected: Effect_exports.sync(() => session !== void 0) };
58897
+ const client = {
58898
+ publish: publish2,
58899
+ isConnected: Effect_exports.sync(() => session !== void 0),
58900
+ connection: Effect_exports.sync(() => session?.info),
58901
+ firstDial: Deferred_exports.await(firstDial)
58902
+ };
58697
58903
  yield* Effect_exports.forkScoped(connectionLoop);
58698
58904
  return client;
58699
58905
  });
@@ -58791,6 +58997,7 @@ var MqttPublisher = (settings, options3 = {}) => Layer_exports.effect(
58791
58997
  const client = yield* makeMqttClient(socket, {
58792
58998
  ...clientOptions,
58793
58999
  clientId: settings.clientId ?? `ot-gateway-${hostname()}`,
59000
+ protocolVersion: settings.version,
58794
59001
  ...settings.username === void 0 ? {} : { username: settings.username },
58795
59002
  ...password === void 0 ? {} : { password },
58796
59003
  ...health === void 0 ? {} : { will: { topic: health.topic, payload: offlinePayload("connection-lost"), qos: 1, retain: true } },
@@ -58835,6 +59042,7 @@ var MqttPublisher = (settings, options3 = {}) => Layer_exports.effect(
58835
59042
 
58836
59043
  // ../../packages/mqtt/src/TestBroker.ts
58837
59044
  var makeBrokerControl = () => ({
59045
+ speaksMqtt5: true,
58838
59046
  connackReason: 0,
58839
59047
  connackProperties: /* @__PURE__ */ new Map(),
58840
59048
  ackPublishes: true,
@@ -58862,15 +59070,18 @@ var deliver = (subscriber, message, onSubscribe) => {
58862
59070
  if (packetId !== void 0) subscriber.nextPacketId = packetId % 65535 + 1;
58863
59071
  Queue_exports.offerUnsafe(
58864
59072
  subscriber.outgoing,
58865
- encodePublish({
58866
- topic: message.topic,
58867
- payload: encoder11.encode(message.payload),
58868
- qos,
58869
- retain,
58870
- ...packetId === void 0 ? {} : { packetId },
58871
- ...message.responseTopic === void 0 ? {} : { responseTopic: message.responseTopic },
58872
- ...message.correlationData === void 0 ? {} : { correlationData: message.correlationData }
58873
- })
59073
+ encodePublish(
59074
+ {
59075
+ topic: message.topic,
59076
+ payload: encoder11.encode(message.payload),
59077
+ qos,
59078
+ retain,
59079
+ ...packetId === void 0 ? {} : { packetId },
59080
+ ...message.responseTopic === void 0 ? {} : { responseTopic: message.responseTopic },
59081
+ ...message.correlationData === void 0 ? {} : { correlationData: message.correlationData }
59082
+ },
59083
+ subscriber.version
59084
+ )
58874
59085
  );
58875
59086
  };
58876
59087
  var accept = (control, message) => {
@@ -58894,6 +59105,7 @@ var serveConnection2 = (control) => Effect_exports.fnUntraced(
58894
59105
  let will;
58895
59106
  const subscriber = {
58896
59107
  clientId: void 0,
59108
+ version: 5,
58897
59109
  subscriptions: [],
58898
59110
  outgoing: yield* Queue_exports.unbounded(),
58899
59111
  nextPacketId: 1
@@ -58918,10 +59130,16 @@ var serveConnection2 = (control) => Effect_exports.fnUntraced(
58918
59130
  switch (split4.type) {
58919
59131
  case PacketType.CONNECT: {
58920
59132
  const connect2 = decodeConnect(split4.body);
59133
+ const unsupported3 = Result_exports.isFailure(connect2) ? connect2.failure.message.startsWith("unsupported protocol") : false;
59134
+ if (unsupported3 || Result_exports.isSuccess(connect2) && connect2.success.protocolVersion === 5 && !control.speaksMqtt5) {
59135
+ yield* writer.write(encodeUnsupportedLevelConnack());
59136
+ return;
59137
+ }
58921
59138
  if (Result_exports.isFailure(connect2)) return;
58922
59139
  const { password, ...rest } = connect2.success;
58923
59140
  control.connects.push({ ...rest, hasPassword: password !== void 0 });
58924
- yield* writer.write(encodeConnack(control.connackReason, control.connackProperties));
59141
+ subscriber.version = connect2.success.protocolVersion ?? 5;
59142
+ yield* writer.write(encodeConnack(control.connackReason, control.connackProperties, subscriber.version));
58925
59143
  if (control.connackReason >= 128) return;
58926
59144
  clientId = connect2.success.clientId;
58927
59145
  subscriber.clientId = clientId;
@@ -58930,7 +59148,7 @@ var serveConnection2 = (control) => Effect_exports.fnUntraced(
58930
59148
  break;
58931
59149
  }
58932
59150
  case PacketType.PUBLISH: {
58933
- const publish2 = decodePublish(split4.flags, split4.body);
59151
+ const publish2 = decodePublish(split4.flags, split4.body, subscriber.version);
58934
59152
  if (Result_exports.isFailure(publish2) || clientId === void 0) return;
58935
59153
  const { topic, qos, retain, packetId, responseTopic, correlationData } = publish2.success;
58936
59154
  const payload = decoder5.decode(publish2.success.payload);
@@ -58947,19 +59165,22 @@ var serveConnection2 = (control) => Effect_exports.fnUntraced(
58947
59165
  });
58948
59166
  }
58949
59167
  if (qos === 1 && packetId !== void 0 && control.ackPublishes) {
58950
- yield* writer.write(encodePuback(packetId, reasonCode));
59168
+ yield* writer.write(encodePuback(packetId, reasonCode, subscriber.version));
58951
59169
  }
58952
59170
  break;
58953
59171
  }
58954
59172
  case PacketType.SUBSCRIBE: {
58955
- const subscribe2 = decodeSubscribe(split4.body);
59173
+ const subscribe2 = decodeSubscribe(split4.body, subscriber.version);
58956
59174
  if (Result_exports.isFailure(subscribe2) || clientId === void 0) return;
58957
59175
  subscriber.subscriptions.push(...subscribe2.success.subscriptions);
58958
59176
  yield* writer.write(
58959
- encodeSuback({
58960
- packetId: subscribe2.success.packetId,
58961
- reasonCodes: subscribe2.success.subscriptions.map((subscription) => subscription.qos)
58962
- })
59177
+ encodeSuback(
59178
+ {
59179
+ packetId: subscribe2.success.packetId,
59180
+ reasonCodes: subscribe2.success.subscriptions.map((subscription) => subscription.qos)
59181
+ },
59182
+ subscriber.version
59183
+ )
58963
59184
  );
58964
59185
  const fresh2 = { ...subscriber, subscriptions: [...subscribe2.success.subscriptions] };
58965
59186
  for (const message of control.retainedMessages.values()) deliver(fresh2, message, true);
@@ -58986,7 +59207,7 @@ var serveConnection2 = (control) => Effect_exports.fnUntraced(
58986
59207
  split4 = frames.next();
58987
59208
  }
58988
59209
  if (split4._tag === "TooLarge") {
58989
- yield* writer.write(encodeDisconnect(149));
59210
+ if (subscriber.version === 5) yield* writer.write(encodeDisconnect(149));
58990
59211
  return;
58991
59212
  }
58992
59213
  if (split4._tag === "Invalid") return;
@@ -59145,7 +59366,8 @@ var demoConfig = (example, directory, options3) => {
59145
59366
  ...options3.public === void 0 ? {} : {
59146
59367
  mqtt: {
59147
59368
  url: `mqtt://${options3.public.broker.host}:${options3.public.broker.port}`,
59148
- clientId: `ot-gateway-${site}`
59369
+ clientId: `ot-gateway-${site}`,
59370
+ version: "auto"
59149
59371
  }
59150
59372
  },
59151
59373
  ...buffer4 === void 0 ? {} : { buffer: { ...buffer4, path: `${directory}/buffer.sqlite` } },
@@ -59218,6 +59440,48 @@ var csvField = (value4) => {
59218
59440
  var toCsv = (rows) => `${rows.map((fields) => fields.map(csvField).join(",")).join("\n")}
59219
59441
  `;
59220
59442
 
59443
+ // src/Output.ts
59444
+ var isJsonMode = (argv2) => argv2.includes("--json");
59445
+ var ResultConsole = Context_exports.Reference("@ot-gateway/gateway/ResultConsole", {
59446
+ defaultValue: () => void 0
59447
+ });
59448
+ var printResult = (text4) => Effect_exports.flatMap(
59449
+ ResultConsole,
59450
+ (results2) => results2 === void 0 ? Console_exports.log(text4) : Effect_exports.sync(() => {
59451
+ results2.log(text4);
59452
+ })
59453
+ );
59454
+ var printJson = (value4) => printResult(JSON.stringify(value4, null, 2));
59455
+ var stderrConsole = (base) => ({
59456
+ assert: (condition, ...args2) => base.assert(condition, ...args2),
59457
+ clear: () => base.clear(),
59458
+ count: (label2) => base.count(label2),
59459
+ countReset: (label2) => base.countReset(label2),
59460
+ debug: (...args2) => base.debug(...args2),
59461
+ dir: (...args2) => base.error(...args2),
59462
+ dirxml: (...args2) => base.error(...args2),
59463
+ error: (...args2) => base.error(...args2),
59464
+ group: (...args2) => base.group(...args2),
59465
+ groupCollapsed: (...args2) => base.groupCollapsed(...args2),
59466
+ groupEnd: () => base.groupEnd(),
59467
+ info: (...args2) => base.error(...args2),
59468
+ log: (...args2) => base.error(...args2),
59469
+ table: (data) => base.error(data),
59470
+ time: (label2) => base.time(label2),
59471
+ timeEnd: (label2) => base.timeEnd(label2),
59472
+ timeLog: (label2, ...args2) => base.timeLog(label2, ...args2),
59473
+ trace: (...args2) => base.trace(...args2),
59474
+ warn: (...args2) => base.warn(...args2)
59475
+ });
59476
+ var isUsageError = (error2) => error2._tag === "ShowHelp" && error2.errors.length > 0;
59477
+ var USAGE_EXIT_CODE = 2;
59478
+ var usageFailure = (error2) => ({
59479
+ ok: false,
59480
+ code: "usage",
59481
+ error: error2.errors.map((each) => each.message).join("; "),
59482
+ hint: `ot-gateway ${[...error2.commandPath.slice(1), "--help"].join(" ")} lists the commands and flags`
59483
+ });
59484
+
59221
59485
  // src/Discover.ts
59222
59486
  var LISTEN = "3 seconds";
59223
59487
  var TRUSTED_SOURCE = "a source you trust (commissioning sheet, device display, DHCP reservation)";
@@ -59356,10 +59620,7 @@ var discoverDrafts = (config, network, options3 = {}) => Effect_exports.gen(func
59356
59620
  const existing = config.devices.map((device) => device.id);
59357
59621
  return draftDevices(described.flat(), existing);
59358
59622
  }).pipe(Effect_exports.scoped);
59359
- var discover = (config, network, options3 = {}) => Effect_exports.flatMap(
59360
- discoverDrafts(config, network, options3),
59361
- (devices) => Console_exports.log(JSON.stringify({ devices }, null, 2))
59362
- );
59623
+ var discover = (config, network, options3 = {}) => Effect_exports.flatMap(discoverDrafts(config, network, options3), (devices) => printJson({ devices }));
59363
59624
  var pointColumn = (point) => slugify(point.name) === point.id && !/^[=+\-@\t\r]/.test(point.name) ? point.name : point.id;
59364
59625
  var draftPointsList = (drafts) => {
59365
59626
  const header = ["device", "point", "unit", "device_instance", "address", "object_type", "object_instance"];
@@ -60504,6 +60765,8 @@ var nextSteps = (path, config, folder = { written: [], kept: [] }) => {
60504
60765
  ];
60505
60766
  const commands2 = [
60506
60767
  ...folderPath === "." ? [] : [[`cd ${folderPath}`, "the gateway's folder"]],
60768
+ // Before anything is started: a wrong URL, port or password shows here, not later as a stale gateway.
60769
+ [`ot-gateway broker${argument}`, `check that ${config.mqtt.url} answers, with a message there and back`],
60507
60770
  ...devices,
60508
60771
  ...compose5 ? [
60509
60772
  ["docker compose up -d", "start it in Docker, restarted after a crash or a reboot"],
@@ -61711,8 +61974,8 @@ var HttpClientError = class extends (/* @__PURE__ */ TaggedError2("HttpClientErr
61711
61974
  var formatReason = (tag2) => tag2.endsWith("Error") ? tag2.slice(0, -5) : tag2;
61712
61975
  var formatMessage = (reason, description, info2) => description ? `${reason}: ${description} (${info2})` : `${reason} error (${info2})`;
61713
61976
  var formatMethodAndUrl = (request3) => `${request3.method} ${redactUrl(request3.url)}`;
61714
- var reasonToJSON = (reason, json3) => ({
61715
- ...json3,
61977
+ var reasonToJSON = (reason, json4) => ({
61978
+ ...json4,
61716
61979
  request: {
61717
61980
  _id: "HttpClientRequest",
61718
61981
  method: reason.request.method,
@@ -69619,7 +69882,7 @@ function makePayloadStreamDecoder(schema2, options3) {
69619
69882
  return (request3) => readBody(request3).pipe(pipeThroughChannel(decode8({
69620
69883
  ignoreEmptyLines: true,
69621
69884
  maxLineBytes
69622
- })), mapEffect2((json3) => decodeElement(json3)), mapError6((error2) => {
69885
+ })), mapEffect2((json4) => decodeElement(json4)), mapError6((error2) => {
69623
69886
  if (HttpApiPayloadTooLarge.is(error2)) return error2;
69624
69887
  if (!isNdjsonError(error2)) return new HttpApiSchemaError({
69625
69888
  kind: "Payload",
@@ -70478,7 +70741,7 @@ function makeStreamBodyDecoder(streamSchema, options3) {
70478
70741
  description: `NDJSON line exceeds maxElementBytes of ${maxElementBytes} bytes`
70479
70742
  })
70480
70743
  });
70481
- }), mapEffect2((json3) => decodeElement(json3)));
70744
+ }), mapEffect2((json4) => decodeElement(json4)));
70482
70745
  }
70483
70746
  const decoder6 = makeSseDecoder(streamSchema, options3);
70484
70747
  return (response, sseOptions) => decodeSseStream(response.stream, streamSchema, decoder6(sseOptions));
@@ -71386,9 +71649,114 @@ var fetchGatewayStatus = (url) => HttpApiClient_exports.make(OtGatewayApi, { bas
71386
71649
  );
71387
71650
  var statusReport = Effect_exports.fn("statusReport")(function* (url, options3 = {}) {
71388
71651
  const status3 = yield* fetchGatewayStatus(url);
71389
- yield* Console_exports.log(options3.json === true ? JSON.stringify(status3, null, 2) : formatStatus(status3));
71652
+ yield* options3.json === true ? printJson(status3) : Console_exports.log(formatStatus(status3));
71390
71653
  });
71391
71654
 
71655
+ // src/Broker.ts
71656
+ var DIAL_TIMEOUT = "15 seconds";
71657
+ var ROUND_TRIP_TIMEOUT = "5 seconds";
71658
+ var BrokerCommandError = class extends Schema_exports.TaggedError()("BrokerCommandError", {
71659
+ message: Schema_exports.String
71660
+ }) {
71661
+ };
71662
+ var randomSuffix = Effect_exports.map(Random_exports.nextIntBetween(0, 16777215), (value4) => value4.toString(16).padStart(6, "0"));
71663
+ var brokerClient = Effect_exports.fn("brokerClient")(function* (settings, role, options3 = {}) {
71664
+ const address = yield* parseBrokerUrl(settings.url);
71665
+ const password = settings.passwordEnv === void 0 ? void 0 : yield* Config_exports.Redacted(settings.passwordEnv);
71666
+ const openTimeout2 = "10 seconds";
71667
+ const socket = address.tls ? yield* makeTls({ host: address.host, port: address.port, servername: address.host, openTimeout: openTimeout2 }) : yield* makeNet({ host: address.host, port: address.port, openTimeout: openTimeout2 });
71668
+ return yield* makeMqttClient(socket, {
71669
+ ...options3,
71670
+ clientId: `ot-gateway-${role}-${yield* randomSuffix}`,
71671
+ protocolVersion: settings.version,
71672
+ ...settings.username === void 0 ? {} : { username: settings.username },
71673
+ ...password === void 0 ? {} : { password }
71674
+ });
71675
+ });
71676
+ var firstDialOf = (client, url) => client.firstDial.pipe(
71677
+ Effect_exports.timeoutOrElse({
71678
+ duration: DIAL_TIMEOUT,
71679
+ orElse: () => Effect_exports.fail(new MqttConnectionError({ message: `no answer within ${DIAL_TIMEOUT}` }))
71680
+ }),
71681
+ Effect_exports.mapError(
71682
+ (error2) => (
71683
+ // The socket's message starts with "could not connect" itself: say it once, with the URL.
71684
+ new BrokerCommandError({
71685
+ message: `could not connect to ${url}: ${error2.message.replace(/^could not connect(: )?/, "")}`
71686
+ })
71687
+ )
71688
+ )
71689
+ );
71690
+ var brokerWarnings = (info2, roundTripMs, topic) => [
71691
+ ...info2.protocolVersion === "3.1.1" ? [
71692
+ "MQTT 3.1.1: the broker announces no limits, commands get no correlation data and messages no expiry (docs/configuration.md, mqtt.version)"
71693
+ ] : [],
71694
+ ...info2.retainAvailable ? [] : ["the broker keeps no retained messages: $meta and health reach only clients connected at the time"],
71695
+ ...info2.maximumQoS === 0 ? ["the broker allows QoS 0 only: nothing confirms that a message arrived, so the buffer cannot help"] : [],
71696
+ ...roundTripMs === void 0 ? [
71697
+ `a message to ${topic} did not come back within ${ROUND_TRIP_TIMEOUT}: the broker's ACL may not let this user publish or subscribe there`
71698
+ ] : []
71699
+ ];
71700
+ var checkBroker = Effect_exports.fn("checkBroker")(function* (config) {
71701
+ const topic = `${config.site}/${config.building}/$gateway/${config.id}/check/${yield* randomSuffix}`;
71702
+ const payload = "ot-gateway broker check";
71703
+ const received = yield* Deferred_exports.make();
71704
+ const client = yield* brokerClient(config.mqtt, "check", {
71705
+ subscriptions: [{ filter: topic, qos: 1 }],
71706
+ onMessage: (message) => message.topic === topic ? Effect_exports.flatMap(
71707
+ Effect_exports.clockWith((clock) => clock.currentTimeMillis),
71708
+ (now2) => Deferred_exports.succeed(received, now2)
71709
+ ).pipe(Effect_exports.asVoid) : Effect_exports.void
71710
+ });
71711
+ yield* firstDialOf(client, config.mqtt.url);
71712
+ const info2 = yield* client.connection;
71713
+ if (info2 === void 0) {
71714
+ return yield* new BrokerCommandError({ message: `connected to ${config.mqtt.url}, then lost the connection` });
71715
+ }
71716
+ const sentAt = yield* Effect_exports.clockWith((clock) => clock.currentTimeMillis);
71717
+ yield* client.publish(topic, payload, { qos: 1 }).pipe(
71718
+ Effect_exports.mapError(
71719
+ (error2) => new BrokerCommandError({ message: `${config.mqtt.url} did not take a message: ${error2.message}` })
71720
+ )
71721
+ );
71722
+ const arrivedAt = yield* Deferred_exports.await(received).pipe(Effect_exports.timeoutOption(ROUND_TRIP_TIMEOUT));
71723
+ const roundTripMs = Option_exports.match(arrivedAt, {
71724
+ onNone: () => void 0,
71725
+ onSome: (at) => Math.max(0, at - sentAt)
71726
+ });
71727
+ const report = {
71728
+ ok: true,
71729
+ broker: config.mqtt.url,
71730
+ ...info2,
71731
+ ...roundTripMs === void 0 ? {} : { roundTripMs },
71732
+ roundTripTopic: topic,
71733
+ warnings: brokerWarnings(info2, roundTripMs, topic)
71734
+ };
71735
+ return report;
71736
+ }, Effect_exports.scoped);
71737
+ var sizeText = (bytes3) => bytes3 >= 1024 * 1024 ? `${Math.round(bytes3 / 1024 / 1024)} MiB` : bytes3 >= 1024 ? `${Math.round(bytes3 / 1024)} KiB` : `${bytes3} B`;
71738
+ var formatBrokerReport = (report) => [
71739
+ `${report.broker}: connected with MQTT ${report.protocolVersion}`,
71740
+ ` allows QoS ${report.maximumQoS}, ${report.retainAvailable ? "retained messages" : "NO retained messages"}, ${report.receiveMaximum} in flight, ${report.maximumPacketSize === void 0 ? "packets of any size" : `packets up to ${sizeText(report.maximumPacketSize)}`}, keep-alive ${report.keepAliveSeconds} s`,
71741
+ report.roundTripMs === void 0 ? ` round trip: NO ANSWER within ${ROUND_TRIP_TIMEOUT}` : ` round trip: ${report.roundTripMs} ms (QoS 1, through ${report.roundTripTopic})`,
71742
+ ...report.warnings.map((warning) => ` warning: ${warning}`)
71743
+ ].join("\n");
71744
+ var publishOnce = Effect_exports.fn("publishOnce")(function* (config, topic, payload, options3) {
71745
+ const client = yield* brokerClient(config.mqtt, "publish");
71746
+ yield* firstDialOf(client, config.mqtt.url);
71747
+ yield* client.publish(topic, payload, { qos: options3.qos, retain: options3.retain }).pipe(Effect_exports.mapError((error2) => new BrokerCommandError({ message: `${topic}: ${error2.message}` })));
71748
+ return {
71749
+ ok: true,
71750
+ broker: config.mqtt.url,
71751
+ topic,
71752
+ bytes: new TextEncoder().encode(payload).length,
71753
+ qos: options3.qos,
71754
+ retain: options3.retain,
71755
+ cleared: options3.retain && payload === ""
71756
+ };
71757
+ }, Effect_exports.scoped);
71758
+ var formatPublished = (result4) => result4.cleared ? `cleared the retained message on ${result4.topic}` : `published ${result4.bytes} byte(s) to ${result4.topic} (QoS ${result4.qos}${result4.retain ? ", retained" : ""})`;
71759
+
71392
71760
  // src/Watch.ts
71393
71761
  var MAX_PAYLOAD = 300;
71394
71762
  var watchFilter = (config) => `${config.site}/${config.building}/#`;
@@ -71399,22 +71767,22 @@ var formatMessage2 = (message, at) => {
71399
71767
  const payload = flat.length > MAX_PAYLOAD ? `${flat.slice(0, MAX_PAYLOAD)}\u2026` : flat;
71400
71768
  return `${time2} ${message.retain ? "retained " : ""}${message.topic} ${payload}`;
71401
71769
  };
71770
+ var messageRecord = (message, at) => {
71771
+ let payload = message.payload;
71772
+ try {
71773
+ payload = JSON.parse(message.payload);
71774
+ } catch {
71775
+ }
71776
+ return JSON.stringify({ at: at.toISOString(), topic: message.topic, retained: message.retain, payload });
71777
+ };
71402
71778
  var watch3 = Effect_exports.fn("watch")(function* (config, options3 = {}) {
71403
- const address = yield* parseBrokerUrl(config.mqtt.url);
71404
- const password = config.mqtt.passwordEnv === void 0 ? void 0 : yield* Config_exports.Redacted(config.mqtt.passwordEnv);
71405
71779
  const filter14 = options3.topic ?? watchFilter(config);
71406
- const openTimeout2 = "10 seconds";
71407
- const socket = address.tls ? yield* makeTls({ host: address.host, port: address.port, servername: address.host, openTimeout: openTimeout2 }) : yield* makeNet({ host: address.host, port: address.port, openTimeout: openTimeout2 });
71408
- const suffix = (yield* Random_exports.nextIntBetween(0, 16777215)).toString(16).padStart(6, "0");
71409
- yield* makeMqttClient(socket, {
71410
- clientId: `ot-gateway-watch-${suffix}`,
71411
- ...config.mqtt.username === void 0 ? {} : { username: config.mqtt.username },
71412
- ...password === void 0 ? {} : { password },
71780
+ yield* brokerClient(config.mqtt, "watch", {
71413
71781
  subscriptions: [{ filter: filter14, qos: 0, retainAsPublished: true }],
71414
71782
  onConnect: () => Console_exports.error(
71415
71783
  `watching ${filter14} on ${config.mqtt.url} (${options3.seconds === void 0 ? "Ctrl-C to stop" : `for ${options3.seconds} s`})`
71416
71784
  ),
71417
- onMessage: (message) => Console_exports.log(formatMessage2(message, /* @__PURE__ */ new Date()))
71785
+ onMessage: (message) => options3.json === true ? printResult(messageRecord(message, /* @__PURE__ */ new Date())) : Console_exports.log(formatMessage2(message, /* @__PURE__ */ new Date()))
71418
71786
  });
71419
71787
  yield* Console_exports.error(`connecting to ${config.mqtt.url}\u2026`);
71420
71788
  if (options3.seconds === void 0) return yield* Effect_exports.never;
@@ -75017,8 +75385,8 @@ function jsonReplacer(key5, value4) {
75017
75385
  return value4;
75018
75386
  }
75019
75387
  var jsonBody = (data) => {
75020
- const json3 = JSON.stringify(data);
75021
- return text2(json3.includes("null") || json3.includes('"bytesValue":') ? JSON.stringify(data, jsonReplacer) : json3, "application/json");
75388
+ const json4 = JSON.stringify(data);
75389
+ return text2(json4.includes("null") || json4.includes('"bytesValue":') ? JSON.stringify(data, jsonReplacer) : json4, "application/json");
75022
75390
  };
75023
75391
  var layerJson = /* @__PURE__ */ succeed6(OtlpSerialization, {
75024
75392
  traces: (spans) => jsonBody(spans),
@@ -76177,12 +76545,7 @@ var jsonFlag = Flag_exports.Boolean("json").pipe(
76177
76545
  Flag_exports.withDefault(false)
76178
76546
  );
76179
76547
  var errorText = (error2) => error2 instanceof Error ? error2.message : String(error2);
76180
- var jsonFailure = (json3, fields = {}) => (effect2) => json3 ? effect2.pipe(
76181
- Effect_exports.tapError(
76182
- (error2) => Console_exports.log(JSON.stringify({ ok: false, ...fields, error: errorText(error2) }, null, 2))
76183
- )
76184
- ) : effect2;
76185
- var printJson = (value4) => Console_exports.log(JSON.stringify(value4, null, 2));
76548
+ var jsonFailure = (json4, fields = {}) => (effect2) => json4 ? effect2.pipe(Effect_exports.tapError((error2) => printJson({ ok: false, ...fields, error: errorText(error2) }))) : effect2;
76186
76549
  var dryRunFlag = (description) => Flag_exports.Boolean("dry-run").pipe(Flag_exports.withDescription(description), Flag_exports.withDefault(false));
76187
76550
  var runConfigured = Effect_exports.fn("runConfigured")(function* (config) {
76188
76551
  const version2 = yield* readVersion;
@@ -76217,9 +76580,9 @@ var run9 = Command_exports.make(
76217
76580
  var check2 = Command_exports.make(
76218
76581
  "check",
76219
76582
  { config: configPath, json: jsonFlag },
76220
- ({ config, json: json3 }) => loadConfig(config).pipe(
76221
- Effect_exports.flatMap((decoded) => json3 ? printJson(configSummary(decoded)) : Console_exports.log(describeConfig(decoded))),
76222
- jsonFailure(json3, { path: config })
76583
+ ({ config, json: json4 }) => loadConfig(config).pipe(
76584
+ Effect_exports.flatMap((decoded) => json4 ? printJson(configSummary(decoded)) : Console_exports.log(describeConfig(decoded))),
76585
+ jsonFailure(json4, { path: config })
76223
76586
  )
76224
76587
  ).pipe(Command_exports.withDescription("Validate a config without connecting to anything; lists every mistake with its path"));
76225
76588
  var discoverCommand = Command_exports.make(
@@ -76239,10 +76602,10 @@ var discoverCommand = Command_exports.make(
76239
76602
  json: jsonFlag
76240
76603
  },
76241
76604
  // The draft is JSON already; --json makes a failure JSON too.
76242
- ({ config, pointsList, address, json: json3 }) => Effect_exports.flatMap(loadConfig(config), (decoded) => {
76605
+ ({ config, pointsList, address, json: json4 }) => Effect_exports.flatMap(loadConfig(config), (decoded) => {
76243
76606
  const options3 = { address: Option_exports.getOrUndefined(address) };
76244
76607
  return Option_exports.isSome(pointsList) ? discoverToPointsList(decoded, pointsList.value, void 0, options3) : discover(decoded, void 0, options3);
76245
- }).pipe(jsonFailure(json3, { path: config }))
76608
+ }).pipe(jsonFailure(json4, { path: config }))
76246
76609
  ).pipe(
76247
76610
  Command_exports.withDescription(
76248
76611
  "Find BACnet devices through the config's bacnet settings and print a draft of their devices entries, read-only"
@@ -76315,9 +76678,9 @@ var init2 = Command_exports.make(
76315
76678
  Flag_exports.withDefault(false)
76316
76679
  )
76317
76680
  },
76318
- ({ directory, json: json3, ...given }) => Effect_exports.gen(function* () {
76319
- const interactive = !json3 && isInteractive(given.yes, process.stdin.isTTY);
76320
- if (!given.yes && !json3 && !interactive) {
76681
+ ({ directory, json: json4, ...given }) => Effect_exports.gen(function* () {
76682
+ const interactive = !json4 && isInteractive(given.yes, process.stdin.isTTY);
76683
+ if (!given.yes && !json4 && !interactive) {
76321
76684
  yield* Console_exports.error(
76322
76685
  "no terminal, so init asks nothing: the flags answer and the defaults fill the rest (--help lists the flags)"
76323
76686
  );
@@ -76328,7 +76691,7 @@ var init2 = Command_exports.make(
76328
76691
  if (written === void 0) return yield* Console_exports.log(`kept ${config} as it is`);
76329
76692
  const folder = yield* writeFolderFiles(config, written, { dryRun: flags.dryRun });
76330
76693
  const files = { ...folder, written: [config, ...folder.written] };
76331
- if (json3) {
76694
+ if (json4) {
76332
76695
  return yield* printJson({
76333
76696
  ...configSummary(written),
76334
76697
  dryRun: flags.dryRun,
@@ -76349,7 +76712,7 @@ var init2 = Command_exports.make(
76349
76712
  yield* Console_exports.log(describeConfig(written));
76350
76713
  yield* Console_exports.log(nextSteps(config, written, files));
76351
76714
  }).pipe(
76352
- jsonFailure(json3),
76715
+ jsonFailure(json4),
76353
76716
  Effect_exports.catchTag(
76354
76717
  "QuitError",
76355
76718
  () => Console_exports.error("init cancelled, nothing written").pipe(Effect_exports.andThen(Effect_exports.sync(() => process.exitCode = 1)))
@@ -76382,14 +76745,14 @@ var importCommand = Command_exports.make(
76382
76745
  dryRun: dryRunFlag("Check the list and print its devices instead of adding them to the config"),
76383
76746
  json: jsonFlag
76384
76747
  },
76385
- ({ list, config, dryRun, json: json3 }) => Effect_exports.gen(function* () {
76748
+ ({ list, config, dryRun, json: json4 }) => Effect_exports.gen(function* () {
76386
76749
  const { added, config: written } = yield* importPointsList(list, config, { dryRun });
76387
76750
  const points2 = added.reduce((total, device) => total + device.points.length, 0);
76388
- if (json3) return yield* printJson({ ok: true, dryRun, path: config, points: points2, devices: added });
76751
+ if (json4) return yield* printJson({ ok: true, dryRun, path: config, points: points2, devices: added });
76389
76752
  if (written === void 0) return yield* printJson({ devices: added });
76390
76753
  yield* Console_exports.log(`added ${added.length} device(s) with ${points2} point(s) to ${config}, none writable`);
76391
76754
  yield* Console_exports.log(describeConfig(written));
76392
- }).pipe(jsonFailure(json3, { path: config }))
76755
+ }).pipe(jsonFailure(json4, { path: config }))
76393
76756
  ).pipe(
76394
76757
  Command_exports.withDescription(
76395
76758
  "Add the devices of a points list (CSV: device, point, host, register, type, unit, \u2026) to the config"
@@ -76402,7 +76765,7 @@ var importCommand = Command_exports.make(
76402
76765
  var schemaCommand = Command_exports.make(
76403
76766
  "schema",
76404
76767
  { json: jsonFlag },
76405
- ({ json: json3 }) => Console_exports.log(json3 ? JSON.stringify(pointsListSchema(), null, 2) : describePointsListSchema())
76768
+ ({ json: json4 }) => json4 ? printJson(pointsListSchema()) : Console_exports.log(describePointsListSchema())
76406
76769
  ).pipe(Command_exports.withDescription("The points list's columns, rules and allowed values"));
76407
76770
  var templateCommand = Command_exports.make(
76408
76771
  "template",
@@ -76430,9 +76793,9 @@ var fromEdeCommand = Command_exports.make(
76430
76793
  var profilesList = Command_exports.make(
76431
76794
  "list",
76432
76795
  { json: jsonFlag },
76433
- ({ json: json3 }) => Effect_exports.gen(function* () {
76796
+ ({ json: json4 }) => Effect_exports.gen(function* () {
76434
76797
  const profiles2 = yield* libraryProfiles();
76435
- if (json3) {
76798
+ if (json4) {
76436
76799
  return yield* printJson(
76437
76800
  profiles2.map(({ id: id2, vendor, model, verified, points: points2 }) => ({
76438
76801
  id: id2,
@@ -76449,7 +76812,7 @@ var profilesList = Command_exports.make(
76449
76812
  (profile) => `${profile.id.padEnd(width3)}${profile.vendor} ${profile.model}, ${profile.points.length} points${profile.verified ? "" : ", from its register map (not yet checked on a device)"}`
76450
76813
  ).join("\n")
76451
76814
  );
76452
- }).pipe(jsonFailure(json3))
76815
+ }).pipe(jsonFailure(json4))
76453
76816
  ).pipe(Command_exports.withDescription("The device profiles a points list can name in its profile column"));
76454
76817
  var profilesShow = Command_exports.make(
76455
76818
  "show",
@@ -76457,19 +76820,21 @@ var profilesShow = Command_exports.make(
76457
76820
  profile: Argument_exports.String("profile").pipe(Argument_exports.withDescription("A profile id, or a path ending in .json")),
76458
76821
  json: jsonFlag
76459
76822
  },
76460
- ({ profile, json: json3 }) => Effect_exports.gen(function* () {
76823
+ ({ profile, json: json4 }) => Effect_exports.gen(function* () {
76461
76824
  const found = yield* resolveProfile(profile, { relativeTo: process.cwd() });
76462
- if (json3) return yield* printJson(found);
76825
+ if (json4) return yield* printJson(found);
76463
76826
  yield* Console_exports.log(describeProfile(found));
76464
- }).pipe(jsonFailure(json3))
76827
+ }).pipe(jsonFailure(json4))
76465
76828
  ).pipe(
76466
76829
  Command_exports.withDescription("One profile's points: names, registers, types and units"),
76830
+ // `get`, as other CLIs name reading one thing.
76831
+ Command_exports.withAlias("get"),
76467
76832
  Command_exports.withExamples([{ command: "ot-gateway profiles show eastron-sdm630", description: "The SDM630's points" }])
76468
76833
  );
76469
76834
  var profilesSchema = Command_exports.make(
76470
76835
  "schema",
76471
76836
  { json: jsonFlag },
76472
- ({ json: json3 }) => Console_exports.log(json3 ? JSON.stringify(profileJsonSchema(), null, 2) : describeProfileFormat())
76837
+ ({ json: json4 }) => json4 ? printJson(profileJsonSchema()) : Console_exports.log(describeProfileFormat())
76473
76838
  ).pipe(Command_exports.withDescription("The profile format, to write one from a register map"));
76474
76839
  var profiles = Command_exports.make("profiles").pipe(
76475
76840
  Command_exports.withDescription("Device profiles: a Modbus model's registers, named once and reused by points lists"),
@@ -76494,18 +76859,82 @@ var watchCommand = Command_exports.make(
76494
76859
  (seconds3) => `--seconds takes 1 or more, not ${seconds3}`
76495
76860
  ),
76496
76861
  Flag_exports.optional
76862
+ ),
76863
+ json: Flag_exports.Boolean("json").pipe(
76864
+ Flag_exports.withDescription("One JSON object per message and line (NDJSON): at, topic, retained, payload"),
76865
+ Flag_exports.withDefault(false)
76497
76866
  )
76498
76867
  },
76499
- ({ config, topic, seconds: seconds3 }) => Effect_exports.flatMap(
76868
+ ({ config, topic, seconds: seconds3, json: json4 }) => Effect_exports.flatMap(
76500
76869
  loadConfig(config),
76501
- (decoded) => watch3(decoded, { topic: Option_exports.getOrUndefined(topic), seconds: Option_exports.getOrUndefined(seconds3) })
76502
- )
76870
+ (decoded) => watch3(decoded, { topic: Option_exports.getOrUndefined(topic), seconds: Option_exports.getOrUndefined(seconds3), json: json4 })
76871
+ ).pipe(jsonFailure(json4, { path: config }))
76503
76872
  ).pipe(
76504
76873
  Command_exports.withDescription("Print what arrives at the config's broker under its site and building, as it arrives"),
76505
76874
  Command_exports.withExamples([
76506
76875
  { command: "ot-gateway watch", description: "Watch the broker in ot-gateway.json" },
76507
76876
  { command: "ot-gateway watch --topic 'my-site/main/ahu-1/#'", description: "Only one device" },
76508
- { command: "ot-gateway watch --seconds 10", description: "Ten seconds of it, then stop" }
76877
+ { command: "ot-gateway watch --seconds 10", description: "Ten seconds of it, then stop" },
76878
+ { command: "ot-gateway watch --seconds 10 --json", description: "The same as JSON lines, for scripts and agents" }
76879
+ ])
76880
+ );
76881
+ var brokerCommand = Command_exports.make(
76882
+ "broker",
76883
+ { config: configPath, json: jsonFlag },
76884
+ ({ config, json: json4 }) => loadConfig(config).pipe(
76885
+ Effect_exports.flatMap(checkBroker),
76886
+ Effect_exports.flatMap((report) => json4 ? printJson(report) : Console_exports.log(formatBrokerReport(report))),
76887
+ jsonFailure(json4, { path: config })
76888
+ )
76889
+ ).pipe(
76890
+ Command_exports.withDescription(
76891
+ "Connect to the config's broker: the MQTT it speaks (5 or 3.1.1), what it allows, and a message there and back"
76892
+ ),
76893
+ Command_exports.withExamples([
76894
+ { command: "ot-gateway broker", description: "Check the broker in ot-gateway.json" },
76895
+ { command: "ot-gateway broker /etc/ot-gateway/gateway.json --json", description: "Another config, as JSON" }
76896
+ ])
76897
+ );
76898
+ var publishCommand = Command_exports.make(
76899
+ "publish",
76900
+ {
76901
+ topic: Argument_exports.String("topic").pipe(Argument_exports.withDescription("The topic, without wildcards")),
76902
+ payload: Argument_exports.String("payload").pipe(
76903
+ Argument_exports.withDescription("The message; empty when left out"),
76904
+ Argument_exports.withDefault("")
76905
+ ),
76906
+ config: Flag_exports.String("config").pipe(
76907
+ Flag_exports.withDescription("Path of the gateway's JSON config"),
76908
+ Flag_exports.withDefault("ot-gateway.json")
76909
+ ),
76910
+ retain: Flag_exports.Boolean("retain").pipe(
76911
+ Flag_exports.withDescription(
76912
+ "Ask the broker to keep it for later subscribers; an empty retained message clears the topic"
76913
+ ),
76914
+ Flag_exports.withDefault(false)
76915
+ ),
76916
+ qos: Flag_exports.ChoiceWithValue("qos", [
76917
+ ["0", 0],
76918
+ ["1", 1]
76919
+ ]).pipe(
76920
+ Flag_exports.withDescription("0 sends and forgets, 1 waits until the broker confirmed it"),
76921
+ Flag_exports.withDefault(1)
76922
+ ),
76923
+ json: jsonFlag
76924
+ },
76925
+ ({ topic, payload, config, retain, qos, json: json4 }) => loadConfig(config).pipe(
76926
+ Effect_exports.flatMap((decoded) => publishOnce(decoded, topic, payload, { retain, qos })),
76927
+ Effect_exports.flatMap((result4) => json4 ? printJson(result4) : Console_exports.log(formatPublished(result4))),
76928
+ jsonFailure(json4, { topic })
76929
+ )
76930
+ ).pipe(
76931
+ Command_exports.withDescription("Send one message to the config's broker, as the gateway's user"),
76932
+ Command_exports.withExamples([
76933
+ { command: "ot-gateway publish my-site/main/test hello", description: "A message, QoS 1" },
76934
+ {
76935
+ command: "ot-gateway publish 'my-site/main/old-device/temp/$meta' --retain",
76936
+ description: "Clear a retained message the broker keeps for a device that is gone"
76937
+ }
76509
76938
  ])
76510
76939
  );
76511
76940
  var status2 = Command_exports.make(
@@ -76517,10 +76946,10 @@ var status2 = Command_exports.make(
76517
76946
  ),
76518
76947
  json: jsonFlag
76519
76948
  },
76520
- ({ url, json: json3 }) => statusReport(url, { json: json3 }).pipe(jsonFailure(json3, { url }))
76949
+ ({ url, json: json4 }) => statusReport(url, { json: json4 }).pipe(jsonFailure(json4, { url }))
76521
76950
  ).pipe(Command_exports.withDescription("The running gateway's status: its broker, buffer and one line per device"));
76522
76951
  var rootDescription = [
76523
- "OT Gateway: Modbus TCP and BACnet/IP in, MQTT 5 out, safe commands back",
76952
+ "OT Gateway: Modbus TCP and BACnet/IP in, MQTT 5 or 3.1.1 out, safe commands back",
76524
76953
  "",
76525
76954
  " For AI agents: nothing asks without a terminal, and --json prints results and failures as JSON.",
76526
76955
  " points schema --json the points list's columns: translate any list or EDE file into it",
@@ -76528,6 +76957,7 @@ var rootDescription = [
76528
76957
  " import <list> --dry-run --json check a points list, row by row",
76529
76958
  " init <folder> --dry-run --json the folder init would write (with --site, --broker, --points <list>)",
76530
76959
  " check --json every mistake in a config, with its path",
76960
+ " broker --json the broker: MQTT version, limits, a round trip",
76531
76961
  " status --json the running gateway, device by device"
76532
76962
  ].join("\n");
76533
76963
  var cli = Command_exports.make("ot-gateway").pipe(
@@ -76542,6 +76972,8 @@ var cli = Command_exports.make("ot-gateway").pipe(
76542
76972
  points,
76543
76973
  profiles,
76544
76974
  watchCommand,
76975
+ brokerCommand,
76976
+ publishCommand,
76545
76977
  status2
76546
76978
  ])
76547
76979
  );
@@ -76555,21 +76987,32 @@ var subcommands = /* @__PURE__ */ new Set([
76555
76987
  "points",
76556
76988
  "profiles",
76557
76989
  "watch",
76990
+ "broker",
76991
+ "publish",
76558
76992
  "status"
76559
76993
  ]);
76560
- var toCliArgs = (argv) => {
76561
- const [first] = argv;
76994
+ var toCliArgs = (argv2) => {
76995
+ const [first] = argv2;
76562
76996
  if (first !== void 0 && (subcommands.has(first) || first.startsWith("-") && !legacyFlags.has(first))) {
76563
- return argv;
76997
+ return argv2;
76998
+ }
76999
+ if (first !== void 0 && !legacyFlags.has(first) && !looksLikePath(first) && !argv2.some((arg) => legacyFlags.has(arg))) {
77000
+ return argv2;
76564
77001
  }
76565
77002
  for (const flag of legacyFlags) {
76566
- if (argv.includes(flag)) return [flag.slice(2), ...argv.filter((arg) => arg !== flag)];
77003
+ if (argv2.includes(flag)) return [flag.slice(2), ...argv2.filter((arg) => arg !== flag)];
76567
77004
  }
76568
- return ["run", ...argv];
77005
+ return ["run", ...argv2];
76569
77006
  };
76570
77007
  var legacyFlags = /* @__PURE__ */ new Set(["--check", "--discover"]);
77008
+ var looksLikePath = (arg) => arg.includes("/") || arg.includes("\\") || arg.includes(".");
76571
77009
  var cliVersion = (version2) => version2.replace(/^v(?=\d)/, "");
76572
- var runCli = (argv) => Effect_exports.flatMap(readVersion, (version2) => Command_exports.runWith(cli, { version: cliVersion(version2) })(toCliArgs(argv)));
77010
+ var runCli = (argv2) => {
77011
+ const args2 = toCliArgs(argv2);
77012
+ const program = Effect_exports.flatMap(readVersion, (version2) => Command_exports.runWith(cli, { version: cliVersion(version2) })(args2));
77013
+ return longRunning.has(args2[0] ?? "") ? program : Effect_exports.provideService(program, References_exports.MinimumLogLevel, "Warn");
77014
+ };
77015
+ var longRunning = /* @__PURE__ */ new Set(["run", "demo"]);
76573
77016
 
76574
77017
  // src/EnvFile.ts
76575
77018
  import { readFileSync } from "node:fs";
@@ -76592,6 +77035,12 @@ var loadEnvFile = (file3 = envFileName, env = process.env) => {
76592
77035
  // src/Shutdown.ts
76593
77036
  var gatewayTeardown = (exit3, onExit5) => {
76594
77037
  if (Exit_exports.isFailure(exit3) && Cause_exports.hasInterruptsOnly(exit3.cause)) return onExit5(0);
77038
+ if (Exit_exports.isFailure(exit3)) {
77039
+ const error2 = Cause_exports.findError(exit3.cause);
77040
+ if (Result_exports.isSuccess(error2) && CliError_exports.isCliError(error2.success) && isUsageError(error2.success)) {
77041
+ return onExit5(USAGE_EXIT_CODE);
77042
+ }
77043
+ }
76595
77044
  return Runtime_exports.defaultTeardown(exit3, onExit5);
76596
77045
  };
76597
77046
 
@@ -76601,15 +77050,23 @@ var reportFailure = (cause) => {
76601
77050
  if (Cause_exports.hasInterruptsOnly(cause)) return Effect_exports.void;
76602
77051
  const error2 = Cause_exports.findError(cause);
76603
77052
  if (Result_exports.isFailure(error2) || Cause_exports.hasDies(cause)) return Effect_exports.logError(cause);
76604
- if (CliError_exports.isCliError(error2.success)) return Effect_exports.void;
76605
- return Effect_exports.logError(error2.success.message);
77053
+ if (CliError_exports.isCliError(error2.success)) {
77054
+ return json3 && isUsageError(error2.success) ? printJson(usageFailure(error2.success)) : Effect_exports.void;
77055
+ }
77056
+ return json3 ? Effect_exports.void : Effect_exports.logError(error2.success.message);
76606
77057
  };
76607
77058
  loadEnvFile();
76608
77059
  var extraEnvFile = process.env["OT_GATEWAY_ENV_FILE"];
76609
77060
  if (extraEnvFile !== void 0 && extraEnvFile !== "") loadEnvFile(extraEnvFile);
76610
- var program = runCli(process.argv.slice(2));
76611
- program.pipe(
77061
+ var argv = process.argv.slice(2);
77062
+ var json3 = isJsonMode(argv);
77063
+ runCli(argv).pipe(
76612
77064
  Effect_exports.tapCause(reportFailure),
77065
+ // --json: stdout is the JSON result alone (Output.ts), so help, banners and progress go to stderr.
77066
+ json3 ? (effect2) => effect2.pipe(
77067
+ Effect_exports.updateService(Console_exports.Console, stderrConsole),
77068
+ Effect_exports.provideService(ResultConsole, globalThis.console)
77069
+ ) : identity,
76613
77070
  // Logs, the final failure among them, go to stderr: stdout is for results, so `check --json | jq` gets JSON only.
76614
77071
  Effect_exports.provideService(Logger_exports.LogToStderr, true),
76615
77072
  Effect_exports.provide(layer11),