@crvouga/mockingbird-runtime 0.0.0-stage → 0.0.1

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.
Files changed (81) hide show
  1. package/README.md +131 -2
  2. package/dist/adapter-node.d.ts +2521 -0
  3. package/dist/adapter-node.js +6920 -0
  4. package/dist/adapter-node.js.map +7 -0
  5. package/dist/admin-ui.js +25 -0
  6. package/dist/admin-ui.js.map +7 -0
  7. package/dist/chunk-2KDYLZXC.js +118 -0
  8. package/dist/chunk-2KDYLZXC.js.map +7 -0
  9. package/dist/chunk-2Y25NPCV.js +1289 -0
  10. package/dist/chunk-2Y25NPCV.js.map +7 -0
  11. package/dist/chunk-4SAK6MQT.js +246 -0
  12. package/dist/chunk-4SAK6MQT.js.map +7 -0
  13. package/dist/chunk-ANCCZFF2.js +778 -0
  14. package/dist/chunk-ANCCZFF2.js.map +7 -0
  15. package/dist/chunk-EBGYPQPA.js +198 -0
  16. package/dist/chunk-EBGYPQPA.js.map +7 -0
  17. package/dist/chunk-EQLY2YOA.js +274 -0
  18. package/dist/chunk-EQLY2YOA.js.map +7 -0
  19. package/dist/chunk-G62YDIIJ.js +7664 -0
  20. package/dist/chunk-G62YDIIJ.js.map +7 -0
  21. package/dist/chunk-HU6IOAFC.js +437 -0
  22. package/dist/chunk-HU6IOAFC.js.map +7 -0
  23. package/dist/chunk-RNAHPNUJ.js +97 -0
  24. package/dist/chunk-RNAHPNUJ.js.map +7 -0
  25. package/dist/chunk-UP4QOSFD.js +87 -0
  26. package/dist/chunk-UP4QOSFD.js.map +7 -0
  27. package/dist/chunk-XNS34BPF.js +2489 -0
  28. package/dist/chunk-XNS34BPF.js.map +7 -0
  29. package/dist/core.d.ts +356 -0
  30. package/dist/core.js +51 -0
  31. package/dist/core.js.map +7 -0
  32. package/dist/crypto-XS5XCMRJ.js +21 -0
  33. package/dist/crypto-XS5XCMRJ.js.map +7 -0
  34. package/dist/helpers-UD7CG4WQ.js +18 -0
  35. package/dist/helpers-UD7CG4WQ.js.map +7 -0
  36. package/dist/http-codec.d.ts +72 -0
  37. package/dist/http-codec.js +25 -0
  38. package/dist/http-codec.js.map +7 -0
  39. package/dist/http-provider.d.ts +3243 -0
  40. package/dist/http-provider.js +37920 -0
  41. package/dist/http-provider.js.map +7 -0
  42. package/dist/index.d.ts +10 -0
  43. package/dist/index.js +23 -0
  44. package/dist/index.js.map +7 -0
  45. package/dist/mqtt-broker/node.d.ts +632 -0
  46. package/dist/mqtt-broker/node.js +355 -0
  47. package/dist/mqtt-broker/node.js.map +7 -0
  48. package/dist/mqtt-broker.d.ts +990 -0
  49. package/dist/mqtt-broker.js +913 -0
  50. package/dist/mqtt-broker.js.map +7 -0
  51. package/dist/openapi-metadata.d.ts +290 -0
  52. package/dist/openapi-metadata.js +28 -0
  53. package/dist/openapi-metadata.js.map +7 -0
  54. package/dist/openapi.d.ts +252 -0
  55. package/dist/openapi.js +45 -0
  56. package/dist/openapi.js.map +7 -0
  57. package/dist/preview/artifacts.d.ts +19 -0
  58. package/dist/preview/artifacts.js +40 -0
  59. package/dist/preview/artifacts.js.map +7 -0
  60. package/dist/preview/bridge.d.ts +21 -0
  61. package/dist/preview/bridge.js +9 -0
  62. package/dist/preview/bridge.js.map +7 -0
  63. package/dist/preview/harness.d.ts +12 -0
  64. package/dist/preview/harness.js +65 -0
  65. package/dist/preview/harness.js.map +7 -0
  66. package/dist/preview/host.d.ts +30 -0
  67. package/dist/preview/host.js +70 -0
  68. package/dist/preview/host.js.map +7 -0
  69. package/dist/service/admin.d.ts +106 -0
  70. package/dist/service/admin.js +340 -0
  71. package/dist/service/admin.js.map +7 -0
  72. package/dist/service.d.ts +2665 -0
  73. package/dist/service.js +264 -0
  74. package/dist/service.js.map +7 -0
  75. package/dist/sqlite.d.ts +69 -0
  76. package/dist/sqlite.js +19 -0
  77. package/dist/sqlite.js.map +7 -0
  78. package/dist/ui.d.ts +37 -0
  79. package/dist/ui.js +702 -0
  80. package/dist/ui.js.map +7 -0
  81. package/package.json +135 -4
@@ -0,0 +1,990 @@
1
+ /**
2
+ * The single source of time for a service.
3
+ *
4
+ * Every timestamp a mock writes reads from here, so a suite moves time instead of
5
+ * sleeping: appointment windows, result delays and expiries become reachable in
6
+ * milliseconds. A frozen clock also makes timestamps reproducible from a seed.
7
+ */
8
+ type ClockState = {
9
+ /** Current epoch milliseconds. */
10
+ now: number;
11
+ /** True while time does not advance on its own. */
12
+ frozen: boolean;
13
+ /** Milliseconds a running clock adds to its underlying source. `0` while frozen. */
14
+ offsetMs: number;
15
+ };
16
+ type Clock = {
17
+ now(): number;
18
+ /** Pin the clock to an exact instant, keeping it frozen if it already was. */
19
+ set(epochMs: number): void;
20
+ /** Move the clock forward, or back with a negative delta. */
21
+ advance(deltaMs: number): void;
22
+ /** Stop time at the current instant. */
23
+ freeze(): void;
24
+ /** Resume from the current instant. */
25
+ unfreeze(): void;
26
+ /** Drop back to the underlying source, live. */
27
+ reset(): void;
28
+ state(): ClockState;
29
+ };
30
+
31
+ /**
32
+ * A deliberate failure injected in front of an operation.
33
+ *
34
+ * This is how a suite reaches the vendor's failure modes without the vendor: the
35
+ * quota error that only appears when a shared sandbox is full, the 429 that only
36
+ * appears under load, the 5xx that proves a retry path works.
37
+ *
38
+ * A rule has three parts. What it **matches** (`operationId`, `method`, `path`, …), **when**
39
+ * it fires among the matching requests (`after`, `every`, `count`, `rate`, `from`, `until`),
40
+ * and what it **does** (`status`, `delay`, `timeout`, `drop`, `truncate`, `effect`).
41
+ */
42
+ type FaultRule = {
43
+ /** Stable id, so a suite can retire exactly the rule it added. Unique within a namespace. */
44
+ id: string;
45
+ /** Fault only this operation. Omit to match every operation. */
46
+ operationId?: string;
47
+ /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
48
+ method?: string;
49
+ /** Fault only this exact path. */
50
+ path?: string;
51
+ /** Fault only paths starting with this prefix. Omit to match every path. */
52
+ pathPrefix?: string;
53
+ /** Fault only paths matching this regular expression (JavaScript syntax, unanchored). */
54
+ pathPattern?: string;
55
+ /** Fault only requests carrying these headers. `"*"` matches any value. */
56
+ requestHeaders?: Record<string, string>;
57
+ /** Fault only requests carrying these query parameters. `"*"` matches any value. */
58
+ query?: Record<string, string>;
59
+ /**
60
+ * Fault only requests whose JSON body carries these fields. Each key is a dotted path into
61
+ * the parsed body (`"patient_details.email"`; a number steps into an array, `"items.0.sku"`)
62
+ * and each value is what the field must equal: a string, number, boolean or `null`, compared
63
+ * strictly (`3` is not `"3"`). `"*"` matches any value that is present. A request whose body
64
+ * is missing, is not JSON, or is not a JSON object never matches. Not `body`, which is the
65
+ * response a rule injects.
66
+ */
67
+ requestBody?: Record<string, RequestBodyValue>;
68
+ /**
69
+ * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
70
+ * an in-process caller usually wants, and what a parallel worker usually does not:
71
+ * rules added through `POST /__admin/faults` default to the calling namespace.
72
+ */
73
+ namespace?: string;
74
+ /** Let this many matching requests through first. */
75
+ after?: number;
76
+ /** Then fault only every nth matching request: `3` faults the 3rd, 6th, 9th. */
77
+ every?: number;
78
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
79
+ count?: number;
80
+ /** Fault this fraction of the remaining requests, `0`–`1`, drawn from the seed. Default `1`. */
81
+ rate?: number;
82
+ /**
83
+ * Fault only from this instant on the namespace clock. A duration (`"5m"`) counts from the
84
+ * clock when the rule was added. Listed as epoch ms.
85
+ */
86
+ from?: Instant | Duration;
87
+ /** Stop faulting at this instant on the namespace clock. A duration counts from when added. */
88
+ until?: Instant | Duration;
89
+ /**
90
+ * Status of the injected response. Omit for a rule that only delays, times out, drops,
91
+ * truncates, or switches on an `effect`: the request then still reaches the service.
92
+ */
93
+ status?: number;
94
+ /** Response body, serialized as JSON. A string is sent as-is. */
95
+ body?: unknown;
96
+ /** Response headers. */
97
+ headers?: Record<string, string>;
98
+ /** Hold the response back this long. Listed as `delayMs`. */
99
+ delay?: Duration;
100
+ /** `delay`, in milliseconds. */
101
+ delayMs?: number;
102
+ /** Alias of `delayMs`. */
103
+ latencyMs?: number;
104
+ /** Extra seeded delay in `[0, jitter]`. Listed as `jitterMs`. */
105
+ jitter?: Duration;
106
+ jitterMs?: number;
107
+ /**
108
+ * Never answer: hold the request this long, then drop the connection. Listed as
109
+ * `timeoutMs`. With virtual time the wait is spent on the mock clock.
110
+ */
111
+ timeout?: Duration;
112
+ timeoutMs?: number;
113
+ /**
114
+ * Drop the connection instead of answering: an in-process `fetch` rejects with a
115
+ * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
116
+ */
117
+ drop?: boolean;
118
+ /**
119
+ * Cut the response body off after this many bytes: the status and headers arrive, then
120
+ * the connection dies mid-body.
121
+ */
122
+ truncate?: number;
123
+ /**
124
+ * A named service behaviour to switch on for the matching request instead of (or
125
+ * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
126
+ * read it with `faultEffects(request)`.
127
+ */
128
+ effect?: string;
129
+ /** Parameters for `effect`. */
130
+ params?: Record<string, unknown>;
131
+ /** The preset this rule was expanded from, if any. */
132
+ fromPreset?: string;
133
+ };
134
+ /** What a field of the request body must equal in {@link FaultRule.requestBody}. */
135
+ type RequestBodyValue = string | number | boolean | null;
136
+ /** A fault that fired for one request. */
137
+ type FaultHit = {
138
+ id: string;
139
+ /** The injected response; absent when the rule only delays, drops, or sets an effect. */
140
+ response?: Response;
141
+ drop?: boolean;
142
+ /** Set with `drop` when the rule held the request for its `timeout` first. */
143
+ timeout?: boolean;
144
+ /** Bytes of response body to let through before the connection dies. */
145
+ truncate?: number;
146
+ effect?: {
147
+ name: string;
148
+ params: Record<string, unknown>;
149
+ };
150
+ };
151
+ /**
152
+ * A named, documented fault a suite switches on by name
153
+ * (`POST /__admin/faults {"preset": "rate_limited"}`): one or more rules, and optionally a
154
+ * webhook delivery fault.
155
+ */
156
+ type FaultPreset = {
157
+ description: string;
158
+ rules?: Omit<FaultRule, "id">[];
159
+ webhook?: {
160
+ mode: "duplicate" | "reorder" | "drop";
161
+ count?: number;
162
+ };
163
+ };
164
+ /** What a request looks like to the fault matcher. */
165
+ type FaultCandidate = {
166
+ operationId: string | undefined;
167
+ method: string;
168
+ path: string;
169
+ namespace: string;
170
+ /** Request headers and query, for rules that match on them. */
171
+ headers?: Headers;
172
+ query?: URLSearchParams;
173
+ /**
174
+ * The request body parsed as JSON, read only when a rule matches on `requestBody`. Resolve
175
+ * `undefined` for a body that is missing or not JSON. It must leave the request readable.
176
+ */
177
+ readJson?: () => Promise<unknown>;
178
+ /** The namespace clock, for `from` / `until`. Rules with a window are skipped without it. */
179
+ now?: number;
180
+ /** How to spend a delay for this request. Default: the registry's own sleep. */
181
+ wait?: (ms: number) => Promise<void>;
182
+ };
183
+ /** A stored rule and how often it was consulted. */
184
+ type FaultListing = FaultRule & {
185
+ /** Faults left before the rule retires. `null` when it has no `count`. */
186
+ remaining: number | null;
187
+ /** Times the rule faulted a request. */
188
+ hits: number;
189
+ /** Requests that matched the rule, faulted or not. */
190
+ seen: number;
191
+ };
192
+ /** A namespace's own rules, with their counters, in the order they are tried. */
193
+ type FaultSnapshot = {
194
+ /**
195
+ * `position` is how many `"*"` rules are tried before the rule, which is what its place
196
+ * in the order means to a request and holds in any process.
197
+ */
198
+ rules: (FaultListing & {
199
+ position?: number;
200
+ })[];
201
+ /** How many `fault_<n>` ids the namespace has handed out. */
202
+ nextId?: number;
203
+ };
204
+ type FaultRegistry = {
205
+ snapshot(namespace: string): FaultSnapshot;
206
+ /** Add a rule, or replace the rule with the same id in the same namespace. */
207
+ add(rule: FaultRule): FaultRule;
208
+ /** The next unused `fault_<n>` id in `namespace`. */
209
+ nextId(namespace: string): string;
210
+ /** Every rule, or the rules a namespace's requests can hit: its own and the global ones. */
211
+ list(namespace?: string): FaultListing[];
212
+ get(id: string, namespace?: string): FaultListing | undefined;
213
+ /** Remove a rule by id: from `namespace` (its own, then a global one), or wherever it is. */
214
+ remove(id: string, namespace?: string): boolean;
215
+ /** Remove every rule, or one namespace's own rules. */
216
+ clear(namespace?: string): void;
217
+ /** Replace a namespace's own rules with a snapshot's, wherever the snapshot was taken. */
218
+ restore(namespace: string, state: FaultSnapshot): void;
219
+ /**
220
+ * Every fault this request should get, in rule order, stopping at the first that answers
221
+ * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
222
+ * each matching rule's remaining uses.
223
+ */
224
+ take(candidate: FaultCandidate): Promise<FaultHit[]>;
225
+ /**
226
+ * Fire these rules at one request without storing them: no matching, no schedule, in order,
227
+ * stopping at the first that answers or drops. Jitter draws from the namespace's stream.
228
+ */
229
+ fire(rules: readonly FaultRule[], candidate: FaultCandidate): Promise<FaultHit[]>;
230
+ };
231
+
232
+ /**
233
+ * The admin controls every mock shares, as one document.
234
+ *
235
+ * The same shape is accepted in three places, and means the same thing in each:
236
+ *
237
+ * - at boot: `createRuntime({ adminControls })`, `serve --admin-controls`,
238
+ * `MOCKINGBIRD_ADMIN_CONTROLS`
239
+ * - over HTTP: `PUT /__admin/controls`
240
+ * - per request: the `x-mockingbird-*` headers in {@link CONTROL_HEADERS}
241
+ *
242
+ * Every control is deterministic: given the same seed, clock and requests, a mock answers
243
+ * the same bytes. Nothing here reads the wall clock or `Math.random`.
244
+ */
245
+ /** Milliseconds, or a string like `"250ms"`, `"2s"`, `"15m"`, `"1h"`, `"3d"`. */
246
+ type Duration = number | string;
247
+ /** Epoch milliseconds, or an ISO-8601 string. */
248
+ type Instant = number | string;
249
+
250
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
251
+ type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
252
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
253
+ type SqliteRunResult$1 = {
254
+ changes: number;
255
+ lastInsertRowid: number | bigint;
256
+ };
257
+ /**
258
+ * Prepared statement bound to a {@link SqliteClient}.
259
+ *
260
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
261
+ */
262
+ interface SqliteStatement$1 {
263
+ run(...params: SqliteValue$1[]): SqliteRunResult$1;
264
+ all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
265
+ get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
266
+ }
267
+ /**
268
+ * Sync SQLite client port owned by Mockingbird.
269
+ *
270
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
271
+ * `bun:sqlite` instances all work when they expose this surface.
272
+ */
273
+ interface SqliteClient$1 {
274
+ exec(sql: string): void;
275
+ prepare(sql: string): SqliteStatement$1;
276
+ transaction<T>(fn: () => T): T;
277
+ }
278
+
279
+ type AdminRequest = {
280
+ request: Request;
281
+ url: URL;
282
+ /** `:param` segments of the matched route. */
283
+ params: Record<string, string>;
284
+ /** Namespace the request targets: `?namespace=`, then the header, then the default. */
285
+ namespace: string;
286
+ /** Parsed JSON body, or `undefined` when there is none. */
287
+ body: unknown;
288
+ };
289
+ type AdminRoute = (request: AdminRequest) => Response | Promise<Response>;
290
+ /**
291
+ * Service-specific admin routes, keyed `METHOD /path` relative to `/__admin`, with
292
+ * `:param` segments — e.g. `"POST /orders/:id/transition"`.
293
+ */
294
+ type AdminRoutes = Record<string, AdminRoute>;
295
+
296
+ /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
297
+ type CredentialRegistry = {
298
+ set(credential: string, namespace: string): void;
299
+ get(credential: string): string | undefined;
300
+ remove(credential: string): boolean;
301
+ clear(): void;
302
+ entries(): {
303
+ credential: string;
304
+ namespace: string;
305
+ }[];
306
+ };
307
+
308
+ /** Every stored record carries a monotonically increasing sequence for stable ordering. */
309
+ type Stored<T> = {
310
+ seq: number;
311
+ value: T;
312
+ };
313
+ type ListRecordsOptions<T> = {
314
+ /** Keep only records passing the predicate. */
315
+ where?: (value: T, seq: number) => boolean;
316
+ /** Sort order; default newest first. */
317
+ order?: "newest" | "oldest";
318
+ };
319
+ /**
320
+ * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
321
+ * sequence, never by id lexicographic order, so list semantics stay stable.
322
+ */
323
+ declare class Collection<T> {
324
+ private readonly sqlite;
325
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
326
+ readonly namespace: string;
327
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
328
+ readonly collectionName: string;
329
+ private readonly statements;
330
+ private prepare;
331
+ constructor(sqlite: SqliteClient$1,
332
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
333
+ namespace: string,
334
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
335
+ collectionName: string);
336
+ private bumpCollectionSeq;
337
+ nextSequence(): number;
338
+ get(id: string): T | undefined;
339
+ has(id: string): boolean;
340
+ /** Insert a new record, assigning it the next sequence number. */
341
+ insert(id: string, value: T): Stored<T>;
342
+ /** Replace an existing record's value, keeping its position. */
343
+ update(id: string, value: T): Stored<T> | undefined;
344
+ delete(id: string): boolean;
345
+ /** How many records the collection holds, without reading them. */
346
+ count(): number;
347
+ list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
348
+ id: string;
349
+ }>;
350
+ }
351
+
352
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
353
+ type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
354
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
355
+ type SqliteRunResult = {
356
+ changes: number;
357
+ lastInsertRowid: number | bigint;
358
+ };
359
+ /**
360
+ * Prepared statement bound to a {@link SqliteClient}.
361
+ *
362
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
363
+ */
364
+ interface SqliteStatement {
365
+ run(...params: SqliteValue[]): SqliteRunResult;
366
+ all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
367
+ get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
368
+ }
369
+ /**
370
+ * Sync SQLite client port owned by Mockingbird.
371
+ *
372
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
373
+ * `bun:sqlite` instances all work when they expose this surface.
374
+ */
375
+ interface SqliteClient {
376
+ exec(sql: string): void;
377
+ prepare(sql: string): SqliteStatement;
378
+ transaction<T>(fn: () => T): T;
379
+ }
380
+
381
+ /** A malformed packet or protocol violation, carrying the reason code a server answers with. */
382
+ declare class MqttProtocolError extends Error {
383
+ readonly reasonCode: number;
384
+ constructor(reasonCode: number, message: string);
385
+ }
386
+ /** Properties (2.2.2.2), by the specification's names in camelCase. */
387
+ type Properties = {
388
+ payloadFormatIndicator?: number;
389
+ messageExpiryInterval?: number;
390
+ contentType?: string;
391
+ responseTopic?: string;
392
+ correlationData?: Uint8Array;
393
+ /** PUBLISH may carry several; SUBSCRIBE carries at most one. */
394
+ subscriptionIdentifiers?: number[];
395
+ sessionExpiryInterval?: number;
396
+ assignedClientIdentifier?: string;
397
+ serverKeepAlive?: number;
398
+ authenticationMethod?: string;
399
+ authenticationData?: Uint8Array;
400
+ requestProblemInformation?: number;
401
+ willDelayInterval?: number;
402
+ requestResponseInformation?: number;
403
+ responseInformation?: string;
404
+ serverReference?: string;
405
+ reasonString?: string;
406
+ receiveMaximum?: number;
407
+ topicAliasMaximum?: number;
408
+ topicAlias?: number;
409
+ maximumQoS?: number;
410
+ retainAvailable?: number;
411
+ userProperties?: [string, string][];
412
+ maximumPacketSize?: number;
413
+ wildcardSubscriptionAvailable?: number;
414
+ subscriptionIdentifierAvailable?: number;
415
+ sharedSubscriptionAvailable?: number;
416
+ };
417
+ type QoS = 0 | 1 | 2;
418
+ type Will = {
419
+ topic: string;
420
+ payload: Uint8Array;
421
+ qos: QoS;
422
+ retain: boolean;
423
+ properties: Properties;
424
+ };
425
+ type SubscriptionRequest = {
426
+ topicFilter: string;
427
+ qos: QoS;
428
+ noLocal: boolean;
429
+ retainAsPublished: boolean;
430
+ retainHandling: number;
431
+ };
432
+ type ConnectPacket = {
433
+ type: "connect";
434
+ protocolName: string;
435
+ protocolVersion: number;
436
+ cleanStart: boolean;
437
+ keepAlive: number;
438
+ properties: Properties;
439
+ clientId: string;
440
+ will?: Will;
441
+ username?: string;
442
+ password?: Uint8Array;
443
+ };
444
+ type ConnackPacket = {
445
+ type: "connack";
446
+ sessionPresent: boolean;
447
+ reasonCode: number;
448
+ properties: Properties;
449
+ };
450
+ type PublishPacket = {
451
+ type: "publish";
452
+ topic: string;
453
+ payload: Uint8Array;
454
+ qos: QoS;
455
+ retain: boolean;
456
+ dup: boolean;
457
+ /** Present when `qos` is 1 or 2. */
458
+ packetId?: number;
459
+ properties: Properties;
460
+ };
461
+ type AckPacket = {
462
+ type: "puback" | "pubrec" | "pubrel" | "pubcomp";
463
+ packetId: number;
464
+ reasonCode: number;
465
+ properties: Properties;
466
+ };
467
+ type SubscribePacket = {
468
+ type: "subscribe";
469
+ packetId: number;
470
+ properties: Properties;
471
+ subscriptions: SubscriptionRequest[];
472
+ };
473
+ type SubackPacket = {
474
+ type: "suback" | "unsuback";
475
+ packetId: number;
476
+ properties: Properties;
477
+ reasonCodes: number[];
478
+ };
479
+ type UnsubscribePacket = {
480
+ type: "unsubscribe";
481
+ packetId: number;
482
+ properties: Properties;
483
+ topicFilters: string[];
484
+ };
485
+ type PingPacket = {
486
+ type: "pingreq" | "pingresp";
487
+ };
488
+ type DisconnectPacket = {
489
+ type: "disconnect";
490
+ reasonCode: number;
491
+ properties: Properties;
492
+ };
493
+ type AuthPacket = {
494
+ type: "auth";
495
+ reasonCode: number;
496
+ properties: Properties;
497
+ };
498
+ type Packet = ConnectPacket | ConnackPacket | PublishPacket | AckPacket | SubscribePacket | SubackPacket | UnsubscribePacket | PingPacket | DisconnectPacket | AuthPacket;
499
+ /** Largest value a Variable Byte Integer holds (1.5.5). */
500
+ declare const MAX_VARIABLE_BYTE_INTEGER = 268435455;
501
+ /** Encode one control packet, fixed header included. */
502
+ declare const encodePacket: (packet: Packet) => Uint8Array;
503
+ /**
504
+ * The MQTT 3.1.1 CONNACK that refuses a protocol level this broker does not speak
505
+ * (return code 0x01, "unacceptable protocol version"): a 3.x client cannot parse a v5 CONNACK.
506
+ */
507
+ declare const LEGACY_UNSUPPORTED_VERSION_CONNACK: Uint8Array;
508
+ /** Decode exactly one control packet. Throws {@link MqttProtocolError} when it is not one. */
509
+ declare const decodePacket: (bytes: Uint8Array) => Packet;
510
+ /**
511
+ * Reassembles control packets from a byte stream, in whatever chunks the transport delivers.
512
+ * Chunks are held as they come and each packet's bytes are copied once, when it is complete,
513
+ * so a large packet in many small chunks costs time linear in its size.
514
+ */
515
+ declare class PacketReader {
516
+ private readonly maxPacketSize;
517
+ private chunks;
518
+ /** Bytes of `chunks[0]` already consumed. */
519
+ private head;
520
+ /** Bytes held and not yet consumed. */
521
+ private buffered;
522
+ /** `maxPacketSize` is the Maximum Packet Size this endpoint advertised (3.2.2.3.6). */
523
+ constructor(maxPacketSize?: number);
524
+ /**
525
+ * The complete packets `chunk` finishes, as raw bytes and decoded. A packet that cannot be
526
+ * decoded stops the stream: its error is returned after the packets before it.
527
+ */
528
+ push(chunk: Uint8Array): {
529
+ packets: Packet[];
530
+ error?: MqttProtocolError;
531
+ };
532
+ /** Up to the first `count` held bytes, without consuming them. */
533
+ private peek;
534
+ /** Consume the first `length` held bytes into a fresh array (decoded packets keep views of it). */
535
+ private take;
536
+ }
537
+
538
+ /**
539
+ * The MQTT 5 broker engine: sessions, subscriptions, QoS 1 flows, offline queues and expiry.
540
+ *
541
+ * It is transport-free and timer-free. Bytes arrive through {@link Connection.receive} and
542
+ * leave through a {@link Transport}; time is whatever `now()` returns, and everything that
543
+ * depends on it (session expiry, connection expiry) is settled by {@link Broker.sweep}, which
544
+ * every entry point runs first. A suite therefore moves a virtual clock instead of sleeping.
545
+ *
546
+ * Everything durable lives in `Collection`s, so reset and Timeline checkpoints cover it. Only
547
+ * the live connections are held in memory.
548
+ *
549
+ * What a vendor decides differently (who may connect, which topics, limits, reason codes for
550
+ * a refusal) comes in through {@link BrokerPolicy}.
551
+ */
552
+
553
+ type JsonValue = string | number | boolean | null | JsonValue[] | {
554
+ [key: string]: JsonValue;
555
+ };
556
+ /** The byte pipe to one client. A listener implements it over a socket. */
557
+ type Transport = {
558
+ send(bytes: Uint8Array): void;
559
+ /** Flush what was sent, then close: the peer sees an orderly end. */
560
+ close(): void;
561
+ /** Drop the connection at once, as a network failure does. */
562
+ destroy(): void;
563
+ };
564
+ /** How a client reached the broker, for a policy that reads it. */
565
+ type TransportInfo = {
566
+ kind: "tcp" | "websocket" | "memory";
567
+ /** Request path of a WebSocket upgrade. */
568
+ path?: string;
569
+ };
570
+ /** What a listener feeds: the other half of a {@link Transport}. */
571
+ type Connection = {
572
+ receive(chunk: Uint8Array): void;
573
+ /** The transport is gone: the peer closed it or the network failed. */
574
+ closed(): void;
575
+ };
576
+ type ConnectRequest = {
577
+ clientId: string;
578
+ /** True when the client sent an empty identifier and `clientId` was assigned. */
579
+ assigned: boolean;
580
+ username: string | undefined;
581
+ password: Uint8Array | undefined;
582
+ cleanStart: boolean;
583
+ keepAlive: number;
584
+ properties: Properties;
585
+ transport: TransportInfo;
586
+ };
587
+ type ConnectDecision = {
588
+ ok: true;
589
+ /** Kept with the session and handed back to {@link BrokerPolicy.authorize}. */
590
+ principal?: JsonValue;
591
+ /** Epoch ms after which the server drops the connection (a token's expiry). */
592
+ connectionExpiresAt?: number;
593
+ } | {
594
+ ok: false;
595
+ reasonCode: number;
596
+ };
597
+ type AuthorizeRequest = {
598
+ /** `receive` is asked once per delivery, for vendors that authorize it separately. */
599
+ action: "publish" | "subscribe" | "receive";
600
+ /** The Topic Name, or the Topic Filter for `subscribe`. */
601
+ topic: string;
602
+ qos: QoS;
603
+ retain: boolean;
604
+ clientId: string;
605
+ username: string | null;
606
+ principal: JsonValue | null;
607
+ };
608
+ /** Where one vendor's broker differs from another's. Every member is read at use time. */
609
+ type BrokerPolicy = {
610
+ authenticate(request: ConnectRequest): ConnectDecision | Promise<ConnectDecision>;
611
+ authorize(request: AuthorizeRequest): boolean;
612
+ /** What a denied PUBLISH or SUBSCRIBE does: answer `Not authorized`, or also disconnect. */
613
+ denyAction(): "ignore" | "disconnect";
614
+ /** A reason code refuses a CONNECT for its client identifier. */
615
+ checkClientId?(clientId: string): number | undefined;
616
+ /** The identifier assigned to a client that sent none, from a deterministic 16-character token. */
617
+ assignClientId(token: string): string;
618
+ /** A reason code rejects a well-formed Topic Name the vendor does not accept. */
619
+ checkTopicName?(topic: string): number | undefined;
620
+ /** A reason code rejects a well-formed Topic Filter the vendor does not accept. */
621
+ checkTopicFilter?(filter: string): number | undefined;
622
+ /** The Session Expiry Interval (seconds) granted for the one a client asked for. */
623
+ sessionExpiry(requested: number): number;
624
+ /** The keep alive the server imposes, when it differs from the client's. */
625
+ serverKeepAlive?(requested: number): number | undefined;
626
+ /**
627
+ * Vendor values for the CONNACK: Maximum Packet Size, Topic Alias Maximum, Receive Maximum,
628
+ * Wildcard Subscription Available, Subscription Identifier Available.
629
+ */
630
+ connackProperties(): Properties;
631
+ /** Largest PUBLISH payload accepted from a client; larger ones disconnect it. */
632
+ maxPayloadBytes?: number;
633
+ /** QoS 1 messages in flight to one client at a time. */
634
+ maxInflight: number;
635
+ /** What a session keeps while its client is away. */
636
+ queue: {
637
+ storeQos0: boolean;
638
+ maxLength?: number;
639
+ };
640
+ /** PUBACK reason code for a publish no subscription matched. */
641
+ pubackNoMatchingSubscribers: number;
642
+ /** A SUBSCRIBE asking for QoS 2: grant QoS 1, or send no SUBACK at all. */
643
+ qos2Subscribe: "downgrade" | "ignore";
644
+ /** Whether `a/#` matches `a` (MQTT 5.0 4.7.1.2 says it does). */
645
+ multiLevelWildcardMatchesParent: boolean;
646
+ /** DISCONNECT reason code when `connectionExpiresAt` passes. */
647
+ connectionExpiredReason: number;
648
+ };
649
+ /** Never expires (3.1.2.11.2). */
650
+ declare const SESSION_NEVER_EXPIRES = 4294967295;
651
+ type SessionRecord = {
652
+ clientId: string;
653
+ username: string | null;
654
+ principal: JsonValue | null;
655
+ /** Seconds the session outlives its connection. */
656
+ sessionExpiryInterval: number;
657
+ createdAt: number;
658
+ connectedAt: number;
659
+ /** `null` while a connection holds the session. */
660
+ disconnectedAt: number | null;
661
+ /** Epoch ms the session is discarded at; `null` while connected, or when it never expires. */
662
+ expiresAt: number | null;
663
+ connectionExpiresAt: number | null;
664
+ /** The live connection holding the session; a stale id marks a connection lost to a restore. */
665
+ connectionId: string | null;
666
+ receiveMaximum: number;
667
+ maximumPacketSize: number | null;
668
+ transport: TransportInfo["kind"];
669
+ };
670
+ type SubscriptionRecord = {
671
+ clientId: string;
672
+ topicFilter: string;
673
+ /** Granted QoS. */
674
+ qos: 0 | 1;
675
+ noLocal: boolean;
676
+ retainAsPublished: boolean;
677
+ retainHandling: number;
678
+ subscriptionIdentifier: number | null;
679
+ };
680
+ /** Application message properties a broker forwards unaltered (3.3.2.3). */
681
+ type ForwardedProperties = {
682
+ payloadFormatIndicator?: number;
683
+ messageExpiryInterval?: number;
684
+ contentType?: string;
685
+ responseTopic?: string;
686
+ /** base64. */
687
+ correlationData?: string;
688
+ userProperties?: [string, string][];
689
+ };
690
+ type QueuedMessage = {
691
+ clientId: string;
692
+ topic: string;
693
+ /** base64. */
694
+ payload: string;
695
+ qos: 0 | 1;
696
+ properties: ForwardedProperties;
697
+ subscriptionIdentifiers: number[];
698
+ /** `inflight` once sent at QoS 1 and not yet acknowledged. */
699
+ state: "queued" | "inflight";
700
+ packetId: number | null;
701
+ enqueuedAt: number;
702
+ };
703
+ /** Who published. */
704
+ type PublishSource = "mqtt" | "http" | "admin";
705
+ /** One publish as the log keeps it: metadata only, never the payload. */
706
+ type PublishRecord = {
707
+ /** 1 for the first publish since the last reset, counting ones the log has dropped. */
708
+ sequence: number;
709
+ topic: string;
710
+ qos: QoS;
711
+ bytes: number;
712
+ source: PublishSource;
713
+ /** The publishing client, for `mqtt`. */
714
+ clientId: string | null;
715
+ /** Sessions the message was delivered or queued to. */
716
+ matched: number;
717
+ at: string;
718
+ };
719
+ type TransportCut = {
720
+ target: string;
721
+ since: number;
722
+ };
723
+ type ClientInfo = {
724
+ clientId: string;
725
+ username: string | null;
726
+ connected: boolean;
727
+ transport: TransportInfo["kind"];
728
+ sessionExpiryInterval: number;
729
+ connectedAt: string;
730
+ disconnectedAt: string | null;
731
+ expiresAt: string | null;
732
+ subscriptions: number;
733
+ queued: number;
734
+ inflight: number;
735
+ };
736
+ type PublishInput = {
737
+ topic: string;
738
+ payload: Uint8Array;
739
+ qos: QoS;
740
+ properties?: Properties;
741
+ };
742
+ type BrokerOptions = {
743
+ sqlite: SqliteClient;
744
+ /** Storage namespace; brokers with different namespaces share nothing. */
745
+ namespace: string;
746
+ now: () => number;
747
+ policy: BrokerPolicy;
748
+ };
749
+ /** Most publishes the metadata log keeps; older rows are dropped. */
750
+ declare const PUBLISH_LOG_SIZE = 1000;
751
+ type ConnectionState = "connecting" | "authenticating" | "open" | "closed";
752
+ declare class BrokerConnection implements Connection {
753
+ readonly id: string;
754
+ readonly transport: Transport;
755
+ readonly info: TransportInfo;
756
+ private readonly broker;
757
+ state: ConnectionState;
758
+ clientId: string;
759
+ readonly aliases: Map<number, string>;
760
+ readonly backlog: Packet[];
761
+ private readonly reader;
762
+ private lastPacketId;
763
+ constructor(id: string, transport: Transport, info: TransportInfo, broker: Broker, maxPacketSize: number | undefined);
764
+ /** Read through a getter so a handler closing the connection mid-loop is seen. */
765
+ private get gone();
766
+ receive(chunk: Uint8Array): void;
767
+ closed(): void;
768
+ send(packet: Packet): void;
769
+ /** The next Packet Identifier not in `used` (2.2.1). */
770
+ nextPacketId(used: ReadonlySet<number>): number;
771
+ }
772
+ declare class Broker {
773
+ readonly sessions: Collection<SessionRecord>;
774
+ readonly subscriptions: Collection<SubscriptionRecord>;
775
+ readonly queue: Collection<QueuedMessage>;
776
+ readonly publishes: Collection<PublishRecord>;
777
+ readonly cuts: Collection<TransportCut>;
778
+ readonly counters: Collection<{
779
+ value: number;
780
+ }>;
781
+ private readonly ids;
782
+ private readonly now;
783
+ private readonly policy;
784
+ /** Connections holding a session, by client identifier. */
785
+ private readonly live;
786
+ /** Every transport not yet closed, including ones still before their CONNACK. */
787
+ private readonly open;
788
+ private connectionCount;
789
+ private sweeping;
790
+ constructor(options: BrokerOptions);
791
+ /** Attach a new client transport. Feed the returned {@link Connection} what it receives. */
792
+ connect(transport: Transport, info?: TransportInfo): Connection;
793
+ /** Open transports right now, including ones that have not sent CONNECT. */
794
+ get connections(): number;
795
+ /**
796
+ * Drop every transport without touching stored sessions: the process is going away, or the
797
+ * stored state is about to be replaced. A session whose connection vanished this way starts
798
+ * its expiry at the next {@link sweep}.
799
+ */
800
+ dropConnections(): void;
801
+ /**
802
+ * Settle everything the clock decides: discard expired sessions, start the expiry of
803
+ * sessions whose connection was lost, and drop connections whose credential expired.
804
+ */
805
+ sweep(): void;
806
+ /**
807
+ * Publish from the server side (an HTTP API, an admin injection). Returns how many sessions
808
+ * the message was delivered or queued to. No client ACL applies; `receive` authorization does.
809
+ */
810
+ publish(input: PublishInput, source?: PublishSource): number;
811
+ /**
812
+ * End a client's session as an administrator does: disconnect it with `reasonCode` and
813
+ * discard the session, its subscriptions and its queue. False when no such session exists.
814
+ */
815
+ kick(clientId: string, reasonCode?: number): boolean;
816
+ /**
817
+ * Send a connected client a DISCONNECT and close its connection. The session stays, under
818
+ * its own expiry. False when the client is not connected.
819
+ */
820
+ disconnect(clientId: string, reasonCode?: number): boolean;
821
+ /**
822
+ * Cut the transport of one client, or of every client: live connections die without a
823
+ * DISCONNECT and new CONNECTs are dropped unanswered until {@link restoreTransport}.
824
+ * Sessions are left to their own expiry. Returns how many connections were dropped.
825
+ */
826
+ cutTransport(clientId?: string): number;
827
+ /** Let one client, or with no argument every client, connect again. */
828
+ restoreTransport(clientId?: string): void;
829
+ /** Targets currently cut: client identifiers, or `*` for every client. */
830
+ transportCuts(): string[];
831
+ clients(): ClientInfo[];
832
+ subscriptionList(clientId?: string): SubscriptionRecord[];
833
+ /** The last {@link PUBLISH_LOG_SIZE} publishes, oldest first. */
834
+ publishLog(): PublishRecord[];
835
+ /** Publishes since the last reset, including ones the log no longer holds. */
836
+ publishCount(): number;
837
+ /** @internal Called by a connection for each decoded packet. */
838
+ accept(connection: BrokerConnection, packet: Packet): void;
839
+ /** @internal A protocol violation: answer with `reasonCode` and close. */
840
+ fail(connection: BrokerConnection, reasonCode: number): void;
841
+ /** @internal The transport is gone, or was just closed by the broker. */
842
+ detach(connection: BrokerConnection, keepSession?: boolean): void;
843
+ /** The session's connection ended at `at`: discard it, or start its expiry (4.1). */
844
+ private endConnection;
845
+ private destroySession;
846
+ /** Send DISCONNECT with `reasonCode`, close the transport, and settle the session. */
847
+ private shutdown;
848
+ private isCut;
849
+ private onConnect;
850
+ private openSession;
851
+ /** 4.4: resend what was sent and never acknowledged, then whatever queued up meanwhile. */
852
+ private resume;
853
+ private onDisconnect;
854
+ private onPublish;
855
+ private onPuback;
856
+ private onSubscribe;
857
+ private onUnsubscribe;
858
+ private route;
859
+ private deliver;
860
+ /** Send as much of a client's queue as its Receive Maximum allows (4.9). */
861
+ private pump;
862
+ private sendMessage;
863
+ private record;
864
+ }
865
+ /**
866
+ * Hold a new transport until its CONNECT arrives, ask `select` which broker it belongs to
867
+ * (a tenant chosen by username or client identifier), and attach it there. A transport whose
868
+ * first packet is not a CONNECT, is larger than {@link MAX_ROUTED_CONNECT_BYTES}, or that
869
+ * `select` turns away, is dropped.
870
+ */
871
+ declare const routeConnection: (transport: Transport, select: (connect: ConnectPacket) => Broker | undefined, info?: TransportInfo) => Connection;
872
+
873
+ /**
874
+ * MQTT 5.0 reason codes (2.4), by the specification's names.
875
+ * https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901031
876
+ */
877
+ declare const ReasonCode: {
878
+ /** Also "Normal disconnection" and "Granted QoS 0". */
879
+ readonly Success: 0;
880
+ readonly GrantedQoS1: 1;
881
+ readonly GrantedQoS2: 2;
882
+ readonly NoMatchingSubscribers: 16;
883
+ readonly NoSubscriptionExisted: 17;
884
+ readonly UnspecifiedError: 128;
885
+ readonly MalformedPacket: 129;
886
+ readonly ProtocolError: 130;
887
+ readonly ImplementationSpecificError: 131;
888
+ readonly UnsupportedProtocolVersion: 132;
889
+ readonly ClientIdentifierNotValid: 133;
890
+ readonly BadUserNameOrPassword: 134;
891
+ readonly NotAuthorized: 135;
892
+ readonly ServerUnavailable: 136;
893
+ readonly ServerBusy: 137;
894
+ readonly Banned: 138;
895
+ readonly ServerShuttingDown: 139;
896
+ readonly BadAuthenticationMethod: 140;
897
+ readonly KeepAliveTimeout: 141;
898
+ readonly SessionTakenOver: 142;
899
+ readonly TopicFilterInvalid: 143;
900
+ readonly TopicNameInvalid: 144;
901
+ readonly PacketIdentifierInUse: 145;
902
+ readonly PacketIdentifierNotFound: 146;
903
+ readonly ReceiveMaximumExceeded: 147;
904
+ readonly TopicAliasInvalid: 148;
905
+ readonly PacketTooLarge: 149;
906
+ readonly MessageRateTooHigh: 150;
907
+ readonly QuotaExceeded: 151;
908
+ readonly AdministrativeAction: 152;
909
+ readonly PayloadFormatInvalid: 153;
910
+ readonly RetainNotSupported: 154;
911
+ readonly QoSNotSupported: 155;
912
+ readonly UseAnotherServer: 156;
913
+ readonly ServerMoved: 157;
914
+ readonly SharedSubscriptionsNotSupported: 158;
915
+ readonly ConnectionRateExceeded: 159;
916
+ readonly MaximumConnectTime: 160;
917
+ readonly SubscriptionIdentifiersNotSupported: 161;
918
+ readonly WildcardSubscriptionsNotSupported: 162;
919
+ };
920
+ type ReasonCodeName = keyof typeof ReasonCode;
921
+
922
+ /**
923
+ * What every MQTT emulator's runtime needs around its brokers, written once: the admin routes
924
+ * that inspect and steer a broker, a clock that settles expiries when a suite moves it, CONNECT
925
+ * faults, and how a transport finds its namespace.
926
+ */
927
+
928
+ /** The path MQTT over WebSocket is served on (EMQX's `mqtt_path`, AWS IoT's `/mqtt`). */
929
+ declare const MQTT_WEBSOCKET_PATH = "/mqtt";
930
+ /**
931
+ * What an MQTT CONNECT is called in fault rules, since it is not an HTTP operation:
932
+ * `POST /__admin/faults {"operationId": "MqttConnect", "effect": "connack", "params": {"reasonCode": 135}}`.
933
+ */
934
+ declare const MQTT_CONNECT_OPERATION = "MqttConnect";
935
+ /** A fault preset that refuses CONNECT with `reasonCode`. */
936
+ declare const connackPreset: (reasonCode: number, description: string) => FaultPreset;
937
+ /**
938
+ * The reason code a fault rule armed for the next CONNECT in `namespace`, if any. Consumes one
939
+ * use of each matching rule, as an HTTP request does.
940
+ */
941
+ declare const takeConnackFault: (faults: FaultRegistry, namespace: string) => Promise<number | undefined>;
942
+ /** A clock that reports every jump, so expiries are settled the moment a suite moves time. */
943
+ declare const observeClock: (clock: Clock, moved: () => void) => Clock;
944
+ /**
945
+ * Whether an HTTP path is the MQTT WebSocket endpoint: `/mqtt`, or `<adminPrefix>/ns/<name>/mqtt`
946
+ * to select a namespace. `undefined` when it is neither.
947
+ */
948
+ declare const webSocketNamespace: (pathname: string, adminPrefix: string) => {
949
+ namespace: string | undefined;
950
+ } | undefined;
951
+ /**
952
+ * The namespace a CONNECT belongs to when its transport named none: the one
953
+ * `PUT /__admin/credentials` maps its username to, then its client identifier, then the default.
954
+ */
955
+ declare const connectNamespace: (credentials: CredentialRegistry, connect: Pick<ConnectPacket, "username" | "clientId">, username?: string | undefined) => string;
956
+ /**
957
+ * Admin routes over one namespace's broker: inspect clients, subscriptions and publish
958
+ * metadata; inject raw payloads; cut and restore the transport; force a disconnect.
959
+ */
960
+ declare const brokerAdminRoutes: (brokerOf: (namespace: string) => Broker) => AdminRoutes;
961
+
962
+ /**
963
+ * Topic Names and Topic Filters (MQTT 5.0 section 4.7).
964
+ * https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901241
965
+ */
966
+ /** UTF-8 length, which is what every MQTT string limit counts. */
967
+ declare const utf8Length: (value: string) => number;
968
+ /** A Topic Name a PUBLISH may carry: well formed and free of wildcard characters (4.7.1). */
969
+ declare const isValidTopicName: (topic: string) => boolean;
970
+ /**
971
+ * A Topic Filter a SUBSCRIBE may carry: `#` only as the whole last level, `+` only as a whole
972
+ * level (4.7.1.2, 4.7.1.3).
973
+ */
974
+ declare const isValidTopicFilter: (filter: string) => boolean;
975
+ /** `$share/{ShareName}/{filter}` (4.8.2). */
976
+ declare const isSharedSubscription: (filter: string) => boolean;
977
+ /**
978
+ * Whether `filter` matches `topic`. `topic` is compared level by level as literal text, so a
979
+ * caller may also ask whether one filter covers another's exact spelling.
980
+ *
981
+ * 4.7.2: a filter starting with a wildcard does not match a Topic Name starting with `$`.
982
+ * 4.7.1.2: `sport/#` also matches `sport`; a vendor that excludes the parent level passes
983
+ * `parentLevel: false`.
984
+ */
985
+ declare const topicMatches: (filter: string, topic: string, options?: {
986
+ parentLevel?: boolean;
987
+ }) => boolean;
988
+
989
+ export { Broker, LEGACY_UNSUPPORTED_VERSION_CONNACK, MAX_VARIABLE_BYTE_INTEGER, MQTT_CONNECT_OPERATION, MQTT_WEBSOCKET_PATH, MqttProtocolError, PUBLISH_LOG_SIZE, PacketReader, ReasonCode, SESSION_NEVER_EXPIRES, brokerAdminRoutes, connackPreset, connectNamespace, decodePacket, encodePacket, isSharedSubscription, isValidTopicFilter, isValidTopicName, observeClock, routeConnection, takeConnackFault, topicMatches, utf8Length, webSocketNamespace };
990
+ export type { AckPacket, AuthPacket, AuthorizeRequest, BrokerOptions, BrokerPolicy, ClientInfo, ConnackPacket, ConnectDecision, ConnectPacket, ConnectRequest, Connection, DisconnectPacket, JsonValue, Packet, PingPacket, Properties, PublishInput, PublishPacket, PublishRecord, PublishSource, QoS, QueuedMessage, ReasonCodeName, SessionRecord, SubackPacket, SubscribePacket, SubscriptionRecord, SubscriptionRequest, Transport, TransportCut, TransportInfo, UnsubscribePacket, Will };