@ceralive/modem-control 0.1.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.
Files changed (108) hide show
  1. package/package.json +31 -0
  2. package/src/backend/at-lease.test.ts +106 -0
  3. package/src/backend/at-lease.ts +158 -0
  4. package/src/backend/cell-info.test.ts +154 -0
  5. package/src/backend/cell-info.ts +160 -0
  6. package/src/backend/constants.ts +35 -0
  7. package/src/backend/device-classifier.test.ts +168 -0
  8. package/src/backend/device-classifier.ts +240 -0
  9. package/src/backend/enrichment.ts +96 -0
  10. package/src/backend/features.test.ts +158 -0
  11. package/src/backend/features.ts +179 -0
  12. package/src/backend/identity-ladder.test.ts +117 -0
  13. package/src/backend/identity-ladder.ts +221 -0
  14. package/src/backend/identity-registry.test.ts +89 -0
  15. package/src/backend/identity-registry.ts +151 -0
  16. package/src/backend/index.ts +221 -0
  17. package/src/backend/lifecycle-interlock.ts +38 -0
  18. package/src/backend/managed-objects.ts +108 -0
  19. package/src/backend/mapping.ts +160 -0
  20. package/src/backend/mm-backend.ts +191 -0
  21. package/src/backend/mm-mutations.ts +228 -0
  22. package/src/backend/modem-actor.test.ts +95 -0
  23. package/src/backend/modem-actor.ts +112 -0
  24. package/src/backend/nm-auto-apn.ts +161 -0
  25. package/src/backend/nm-gsm-fields.ts +122 -0
  26. package/src/backend/nmcli-nm-port.ts +228 -0
  27. package/src/backend/nmcli-runner.ts +52 -0
  28. package/src/backend/observer.ts +297 -0
  29. package/src/backend/power-contract.test.ts +40 -0
  30. package/src/backend/power-contract.ts +83 -0
  31. package/src/backend/recovery-attribution.test.ts +102 -0
  32. package/src/backend/recovery-attribution.ts +86 -0
  33. package/src/backend/recovery-budget.test.ts +64 -0
  34. package/src/backend/recovery-budget.ts +84 -0
  35. package/src/backend/recovery-ladder.test.ts +257 -0
  36. package/src/backend/recovery-ladder.ts +249 -0
  37. package/src/backend/router-ethernet.test.ts +71 -0
  38. package/src/backend/router-ethernet.ts +90 -0
  39. package/src/backend/row-store.ts +105 -0
  40. package/src/backend/signal-setup.ts +112 -0
  41. package/src/backend/sim-unlock.ts +193 -0
  42. package/src/backend/transition-preconditions.ts +149 -0
  43. package/src/backend/usage/accounting.test.ts +147 -0
  44. package/src/backend/usage/accounting.ts +123 -0
  45. package/src/backend/usage/billing-cycle.test.ts +62 -0
  46. package/src/backend/usage/billing-cycle.ts +45 -0
  47. package/src/backend/usage/boot-id.ts +18 -0
  48. package/src/backend/usage/index.ts +37 -0
  49. package/src/backend/usage/proc-net-dev.test.ts +56 -0
  50. package/src/backend/usage/proc-net-dev.ts +77 -0
  51. package/src/backend/usage/sampler.test.ts +219 -0
  52. package/src/backend/usage/sampler.ts +228 -0
  53. package/src/backend/usage/store.test.ts +148 -0
  54. package/src/backend/usage/store.ts +177 -0
  55. package/src/backend/usb-enumerator.test.ts +87 -0
  56. package/src/backend/usb-enumerator.ts +181 -0
  57. package/src/backend/usb-mode-transition.test.ts +323 -0
  58. package/src/backend/usb-mode-transition.ts +253 -0
  59. package/src/domain/brand.ts +29 -0
  60. package/src/domain/errors.ts +77 -0
  61. package/src/domain/guards.test.ts +218 -0
  62. package/src/domain/guards.ts +144 -0
  63. package/src/domain/identity.test.ts +83 -0
  64. package/src/domain/identity.ts +165 -0
  65. package/src/domain/index.ts +12 -0
  66. package/src/domain/policy.ts +137 -0
  67. package/src/domain/snapshot.test.ts +266 -0
  68. package/src/domain/snapshot.ts +120 -0
  69. package/src/domain/state.ts +189 -0
  70. package/src/index.test.ts +6 -0
  71. package/src/index.ts +15 -0
  72. package/src/ports/README.md +61 -0
  73. package/src/ports/forbidden-surface.test.ts +80 -0
  74. package/src/ports/index.ts +16 -0
  75. package/src/ports/modem-manager.ts +72 -0
  76. package/src/ports/network-manager.ts +87 -0
  77. package/src/ports/observation.ts +48 -0
  78. package/src/ports/ops.ts +60 -0
  79. package/src/ports/ops.type-test.ts +39 -0
  80. package/src/ports/receipts.test.ts +153 -0
  81. package/src/ports/receipts.ts +43 -0
  82. package/src/ports/reconcile.test.ts +152 -0
  83. package/src/ports/reconcile.ts +338 -0
  84. package/src/ports/router.ts +29 -0
  85. package/src/redact.test.ts +82 -0
  86. package/src/redact.ts +73 -0
  87. package/src/transport/README.md +65 -0
  88. package/src/transport/codec.test.ts +118 -0
  89. package/src/transport/codec.ts +240 -0
  90. package/src/transport/conformance-python.test.ts +152 -0
  91. package/src/transport/conformance-same-lib.test.ts +115 -0
  92. package/src/transport/dbus-native-lib.d.ts +19 -0
  93. package/src/transport/dbus-native.ts +85 -0
  94. package/src/transport/errors.ts +74 -0
  95. package/src/transport/index.ts +30 -0
  96. package/src/transport/no-library-leak.test.ts +50 -0
  97. package/src/transport/reliability.test.ts +173 -0
  98. package/src/transport/signature.ts +110 -0
  99. package/src/transport/test-support/fake-service.ts +143 -0
  100. package/src/transport/test-support/independent-producer.py +110 -0
  101. package/src/transport/test-support/private-bus.ts +66 -0
  102. package/src/transport/transport.ts +439 -0
  103. package/src/transport/types.ts +118 -0
  104. package/src/usb-mode/catalog-schema.test.ts +181 -0
  105. package/src/usb-mode/catalog-schema.ts +113 -0
  106. package/src/usb-mode/catalog.ts +60 -0
  107. package/src/usb-mode/certified-catalog.json +67 -0
  108. package/src/usb-mode/index.ts +27 -0
@@ -0,0 +1,85 @@
1
+ // Internal typed facade over the `@httptoolkit/dbus-native` CommonJS module.
2
+ //
3
+ // The library ships a `types.d.ts` that covers only a fraction of the surface we use
4
+ // (no `invoke`, `addMatch`, `connection`, or `messageType`), so we describe the exact
5
+ // parts we depend on here and cast once, at this single boundary. NOTHING in this file
6
+ // is re-exported from the package's public entry (`../index.ts`): the raw library types
7
+ // stay quarantined behind the transport seam. See `./README.md` for why this library
8
+ // was chosen and the documented fallback (`@particle/dbus-next`).
9
+
10
+ import * as dbusNativeModule from '@httptoolkit/dbus-native';
11
+
12
+ // A D-Bus message as the library marshals/unmarshals it.
13
+ export interface RawMessage {
14
+ type?: number;
15
+ path?: string;
16
+ interface?: string;
17
+ member?: string;
18
+ destination?: string;
19
+ sender?: string;
20
+ signature?: string;
21
+ body?: unknown[];
22
+ errorName?: string;
23
+ serial?: number;
24
+ replySerial?: number;
25
+ }
26
+
27
+ // The context (`this`) the library binds when it invokes a reply callback. `signature`
28
+ // is the reply's own D-Bus signature — the promisified `invoke` drops this and collapses
29
+ // multi-value bodies, which is why we always call `invoke` with an explicit callback.
30
+ export interface ReplyContext {
31
+ signature?: string;
32
+ message?: RawMessage;
33
+ }
34
+
35
+ export type ReplyCallback = (this: ReplyContext, error: unknown, ...body: unknown[]) => void;
36
+
37
+ // The underlying stream/EventEmitter. We drive reconnect off its lifecycle events and
38
+ // assert on `listenerCount` in the leak test, so both are part of the facade.
39
+ export interface RawConnection {
40
+ on(event: string, handler: (...args: unknown[]) => void): void;
41
+ once(event: string, handler: (...args: unknown[]) => void): void;
42
+ removeListener(event: string, handler: (...args: unknown[]) => void): void;
43
+ removeAllListeners(event?: string): void;
44
+ listenerCount(event: string): number;
45
+ end(): void;
46
+ }
47
+
48
+ export interface RawBus {
49
+ connection: RawConnection;
50
+ invoke(message: RawMessage, callback: ReplyCallback): void;
51
+ addMatch(rule: string): Promise<unknown>;
52
+ removeMatch(rule: string): Promise<unknown>;
53
+ disconnect(): Promise<void>;
54
+ }
55
+
56
+ export interface CreateClientOptions {
57
+ busAddress?: string;
58
+ socket?: string;
59
+ // Return 64-bit `x`/`t` fields as Long.js objects instead of lossy numbers. The
60
+ // transport always sets this so `codec.decodeBody` can convert them to `bigint`.
61
+ ReturnLongjs?: boolean;
62
+ direct?: boolean;
63
+ }
64
+
65
+ export interface DbusNativeModule {
66
+ createClient(options: CreateClientOptions): RawBus;
67
+ messageType: {
68
+ invalid: number;
69
+ methodCall: number;
70
+ methodReturn: number;
71
+ error: number;
72
+ signal: number;
73
+ };
74
+ }
75
+
76
+ // Bun/Node CJS interop: `import *` yields the module namespace whose `default` (when
77
+ // present) is `module.exports`. One cast confines the untyped surface to this line.
78
+ const resolved = ((dbusNativeModule as { default?: unknown }).default ??
79
+ dbusNativeModule) as unknown as DbusNativeModule;
80
+
81
+ export const messageType = resolved.messageType;
82
+
83
+ export function createClient(options: CreateClientOptions): RawBus {
84
+ return resolved.createClient(options);
85
+ }
@@ -0,0 +1,74 @@
1
+ // Typed error taxonomy for the D-Bus transport seam.
2
+ //
3
+ // Wire data crossing the transport boundary is never compile-time checked, so every
4
+ // failure mode that a caller (or the A3.x D-Bus backend) must branch on is a real,
5
+ // exported class — never a bare thrown string or a generic Error.
6
+
7
+ export class TransportError extends Error {
8
+ constructor(message: string, options?: ErrorOptions) {
9
+ super(message, options);
10
+ this.name = 'TransportError';
11
+ }
12
+ }
13
+
14
+ // A D-Bus signature contained a type this transport refuses to handle. The only such
15
+ // type today is `h` (UNIX_FD / file-descriptor passing): the transport never marshals
16
+ // or unmarshals a file descriptor, so encountering `h` in an outgoing call signature,
17
+ // a reply signature, a signal signature, or nested inside a variant throws this rather
18
+ // than silently dropping or coercing the descriptor.
19
+ export class UnsupportedSignatureError extends TransportError {
20
+ readonly signature: string;
21
+ readonly unsupportedType: string;
22
+
23
+ constructor(signature: string, unsupportedType: string) {
24
+ super(
25
+ `D-Bus signature "${signature}" contains unsupported type "${unsupportedType}": ` +
26
+ 'UNIX_FD / file-descriptor passing is not supported by this transport',
27
+ );
28
+ this.name = 'UnsupportedSignatureError';
29
+ this.signature = signature;
30
+ this.unsupportedType = unsupportedType;
31
+ }
32
+ }
33
+
34
+ // A 64-bit field (`x` INT64 / `t` UINT64) was handed a JavaScript `number` on encode.
35
+ // A `number` cannot carry the full 64-bit range without silent precision loss above
36
+ // 2^53, so the transport requires a `bigint` for these fields and refuses `number`
37
+ // loudly instead of corrupting the value on the wire.
38
+ export class BigIntRequiredError extends TransportError {
39
+ readonly signature: string;
40
+ readonly received: string;
41
+
42
+ constructor(signature: string, received: unknown) {
43
+ super(
44
+ `D-Bus 64-bit field "${signature}" requires a bigint, received ${typeof received} ` +
45
+ `(${String(received)}): a JS number silently loses precision above 2^53`,
46
+ );
47
+ this.name = 'BigIntRequiredError';
48
+ this.signature = signature;
49
+ this.received = typeof received;
50
+ }
51
+ }
52
+
53
+ // A 64-bit value was outside the range representable by its signed/unsigned field.
54
+ export class SixtyFourBitRangeError extends TransportError {
55
+ readonly signature: string;
56
+ readonly value: bigint;
57
+
58
+ constructor(signature: string, value: bigint) {
59
+ super(`Value ${value} is out of range for 64-bit D-Bus field "${signature}"`);
60
+ this.name = 'SixtyFourBitRangeError';
61
+ this.signature = signature;
62
+ this.value = value;
63
+ }
64
+ }
65
+
66
+ // The bus connection dropped (or was never established) while a method call was
67
+ // in-flight or pending. The call rejects with this instead of hanging forever; the
68
+ // transport's own reconnect loop keeps running independently.
69
+ export class DisconnectedError extends TransportError {
70
+ constructor(message = 'D-Bus connection is not established') {
71
+ super(message);
72
+ this.name = 'DisconnectedError';
73
+ }
74
+ }
@@ -0,0 +1,30 @@
1
+ // Public surface of the D-Bus transport seam.
2
+ //
3
+ // This is the ONLY module the rest of `@ceralive/modem-control` (and the A3.x D-Bus
4
+ // backend) imports from `./transport`. Every type here is the transport's own — no
5
+ // `@httptoolkit/dbus-native` type is re-exported, so swapping the underlying library
6
+ // (documented fallback: `@particle/dbus-next`) is invisible to callers. See README.md.
7
+
8
+ export {
9
+ BigIntRequiredError,
10
+ DisconnectedError,
11
+ SixtyFourBitRangeError,
12
+ TransportError,
13
+ UnsupportedSignatureError,
14
+ } from './errors';
15
+ export { createDbusTransport } from './transport';
16
+ export type {
17
+ DbusTransport,
18
+ DbusTransportOptions,
19
+ DbusValue,
20
+ DbusVariant,
21
+ MethodCall,
22
+ MethodReply,
23
+ ReconnectOptions,
24
+ SignalEvent,
25
+ SignalListener,
26
+ SignalSpec,
27
+ Subscription,
28
+ TransportEvent,
29
+ } from './types';
30
+ export { isVariant, variant } from './types';
@@ -0,0 +1,50 @@
1
+ // Guard: the `@httptoolkit/dbus-native` library must never surface in a public export.
2
+ //
3
+ // The package entry (`control/src/index.ts`) and the transport seam's own public entry
4
+ // (`./index.ts`) may reference the library only through the quarantined facade
5
+ // (`./dbus-native.ts`) — never re-export it. Swapping the underlying library (documented
6
+ // fallback `@particle/dbus-next`) must stay invisible to every caller.
7
+
8
+ import { expect, test } from 'bun:test';
9
+ import { join } from 'node:path';
10
+ import * as transportPublic from './index';
11
+
12
+ // A single-quoted module specifier — the shape of a real import/export, distinct from a
13
+ // prose mention of the library in a comment (those use backticks).
14
+ const LIBRARY_IMPORT = "'@httptoolkit/dbus-native'";
15
+ const transportDir = import.meta.dir;
16
+ const controlSrcDir = join(transportDir, '..');
17
+
18
+ test('the package entry does not import or re-export the D-Bus library', async () => {
19
+ const source = await Bun.file(join(controlSrcDir, 'index.ts')).text();
20
+ expect(source).not.toContain(LIBRARY_IMPORT);
21
+ });
22
+
23
+ test('the transport public entry does not import or re-export the D-Bus library', async () => {
24
+ const source = await Bun.file(join(transportDir, 'index.ts')).text();
25
+ expect(source).not.toContain(LIBRARY_IMPORT);
26
+ });
27
+
28
+ test('only the quarantined facade imports the D-Bus library from production modules', async () => {
29
+ const productionModules = ['transport.ts', 'codec.ts', 'signature.ts', 'errors.ts', 'types.ts'];
30
+ for (const moduleName of productionModules) {
31
+ const source = await Bun.file(join(transportDir, moduleName)).text();
32
+ expect(source).not.toContain(LIBRARY_IMPORT);
33
+ }
34
+ });
35
+
36
+ test('the transport public surface exposes only the seam\u2019s own values', () => {
37
+ const exported = Object.keys(transportPublic).sort();
38
+ expect(exported).toEqual(
39
+ [
40
+ 'BigIntRequiredError',
41
+ 'DisconnectedError',
42
+ 'SixtyFourBitRangeError',
43
+ 'TransportError',
44
+ 'UnsupportedSignatureError',
45
+ 'createDbusTransport',
46
+ 'isVariant',
47
+ 'variant',
48
+ ].sort(),
49
+ );
50
+ });
@@ -0,0 +1,173 @@
1
+ // Reliability tests for the transport seam: reconnect after a bus restart, a ≥5000-event
2
+ // signal stream, late replies, and a 100-cycle subscribe/unsubscribe leak check.
3
+ //
4
+ // These run against dedicated private `dbus-daemon` instances (not the outer session
5
+ // bus): the reconnect test must kill and respawn its bus, which is only safe on a bus we
6
+ // own. That also makes this file self-contained — it needs no `dbus-run-session`.
7
+
8
+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
9
+ import type { DbusTransport } from './index';
10
+ import { createDbusTransport } from './index';
11
+ import {
12
+ FAKE_IFACE,
13
+ FAKE_PATH,
14
+ type FakeService,
15
+ startFakeService,
16
+ TICK_MEMBER,
17
+ } from './test-support/fake-service';
18
+ import { PrivateBus } from './test-support/private-bus';
19
+
20
+ const HAS_DBUS_DAEMON = Bun.which('dbus-daemon') !== null;
21
+
22
+ const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
23
+
24
+ async function waitFor(predicate: () => boolean, timeoutMs: number, label: string): Promise<void> {
25
+ const deadline = Date.now() + timeoutMs;
26
+ while (Date.now() < deadline) {
27
+ if (predicate()) {
28
+ return;
29
+ }
30
+ await sleep(10);
31
+ }
32
+ throw new Error(`timed out after ${timeoutMs}ms waiting for ${label}`);
33
+ }
34
+
35
+ const tickSpec = { interface: FAKE_IFACE, member: TICK_MEMBER, path: FAKE_PATH };
36
+
37
+ describe.skipIf(!HAS_DBUS_DAEMON)('transport reliability (shared private bus)', () => {
38
+ let bus: PrivateBus;
39
+ let fake: FakeService;
40
+ let transport: DbusTransport;
41
+
42
+ beforeAll(async () => {
43
+ bus = new PrivateBus();
44
+ await bus.start();
45
+ fake = await startFakeService({ socket: bus.socket });
46
+ transport = createDbusTransport({ socket: bus.socket });
47
+ await transport.connect();
48
+ });
49
+
50
+ afterAll(async () => {
51
+ await transport.disconnect();
52
+ await fake.stop();
53
+ await bus.stop();
54
+ });
55
+
56
+ test('a late reply (reply delayed 600ms) still resolves the call correctly', async () => {
57
+ const reply = await transport.callMethod({
58
+ destination: fake.busName,
59
+ path: FAKE_PATH,
60
+ interface: FAKE_IFACE,
61
+ member: 'SlowPing',
62
+ signature: 'u',
63
+ args: [600],
64
+ });
65
+ expect(reply.body[0]).toBe('pong');
66
+ });
67
+
68
+ test('a ≥5000-event signal stream is delivered completely, in order, as exact bigints', async () => {
69
+ const total = 5000;
70
+ const received: bigint[] = [];
71
+ const subscription = await transport.subscribeSignal(tickSpec, (event) => {
72
+ received.push(event.body[0] as bigint);
73
+ });
74
+
75
+ for (let seq = 0; seq < total; seq += 1) {
76
+ fake.emitTick(BigInt(seq));
77
+ }
78
+
79
+ await waitFor(() => received.length >= total, 20_000, `${total} tick signals`);
80
+ expect(received.length).toBe(total);
81
+ expect(received[0]).toBe(0n);
82
+ expect(received[total - 1]).toBe(BigInt(total - 1));
83
+ // Order and exactness across the whole stream.
84
+ let ordered = true;
85
+ for (let i = 0; i < total; i += 1) {
86
+ if (received[i] !== BigInt(i)) {
87
+ ordered = false;
88
+ break;
89
+ }
90
+ }
91
+ expect(ordered).toBe(true);
92
+
93
+ await subscription.unsubscribe();
94
+ });
95
+
96
+ test('100 subscribe/unsubscribe cycles leave no leaked listener', async () => {
97
+ const baseline = transport.subscriptionCount();
98
+ for (let cycle = 0; cycle < 100; cycle += 1) {
99
+ const subscription = await transport.subscribeSignal(tickSpec, () => undefined);
100
+ await subscription.unsubscribe();
101
+ }
102
+ expect(transport.subscriptionCount()).toBe(baseline);
103
+
104
+ // Behavioural proof: after all those cycles a fresh subscriber receives each signal
105
+ // exactly once — a leaked listener from an earlier cycle would double-deliver.
106
+ let deliveries = 0;
107
+ const subscription = await transport.subscribeSignal(tickSpec, () => {
108
+ deliveries += 1;
109
+ });
110
+ fake.emitTick(1n);
111
+ await waitFor(() => deliveries >= 1, 3_000, 'one tick after leak cycles');
112
+ await sleep(100);
113
+ expect(deliveries).toBe(1);
114
+ await subscription.unsubscribe();
115
+ });
116
+ });
117
+
118
+ test.skipIf(!HAS_DBUS_DAEMON)(
119
+ 'transport reconnects and resubscribes after a bus restart without a consumer-facing crash',
120
+ async () => {
121
+ const bus = new PrivateBus();
122
+ await bus.start();
123
+ let fake = await startFakeService({ socket: bus.socket });
124
+ const transport = createDbusTransport({
125
+ socket: bus.socket,
126
+ reconnect: { initialDelayMs: 25, maxDelayMs: 200 },
127
+ });
128
+
129
+ const events: string[] = [];
130
+ let consumerError: unknown = null;
131
+ transport.on('disconnected', () => events.push('disconnected'));
132
+ transport.on('reconnected', () => events.push('reconnected'));
133
+ transport.on('error', (error) => {
134
+ consumerError = error;
135
+ });
136
+
137
+ await transport.connect();
138
+
139
+ const ticks: bigint[] = [];
140
+ const subscription = await transport.subscribeSignal(tickSpec, (event) => {
141
+ ticks.push(event.body[0] as bigint);
142
+ });
143
+
144
+ fake.emitTick(11n);
145
+ await waitFor(() => ticks.includes(11n), 3_000, 'pre-restart tick');
146
+
147
+ // Kill the bus mid-flight; the old fake dies with it.
148
+ bus.kill();
149
+ await waitFor(() => events.includes('disconnected'), 5_000, 'disconnected event');
150
+
151
+ // Bring the bus back at the same socket; the transport must reconnect on its own.
152
+ await bus.start();
153
+ await waitFor(() => events.includes('reconnected'), 15_000, 'reconnected event');
154
+
155
+ // A fresh producer on the restored bus; the transport auto-resubscribed, so its
156
+ // signal must arrive without the caller re-subscribing.
157
+ fake = await startFakeService({ socket: bus.socket });
158
+ fake.emitTick(22n);
159
+ await waitFor(() => ticks.includes(22n), 8_000, 'post-reconnect tick (resubscribe)');
160
+
161
+ expect(events).toContain('disconnected');
162
+ expect(events).toContain('reconnected');
163
+ expect(ticks).toContain(11n);
164
+ expect(ticks).toContain(22n);
165
+ expect(consumerError).toBeNull();
166
+
167
+ await subscription.unsubscribe();
168
+ await transport.disconnect();
169
+ await fake.stop();
170
+ await bus.stop();
171
+ },
172
+ 30_000,
173
+ );
@@ -0,0 +1,110 @@
1
+ // D-Bus signature parsing and support checks.
2
+ //
3
+ // We keep our own tiny recursive-descent parser rather than reaching into the
4
+ // underlying library's internal `lib/signature.js`: the parsed tree drives our
5
+ // signature-aware encode/decode (below) and the tree shape is part of this seam's
6
+ // contract, not the library's. The node shape intentionally mirrors the library's
7
+ // (`{ type, child }`) so a tree the library hands us inside a decoded variant can be
8
+ // re-serialised with `signatureFromNode` without a translation step.
9
+
10
+ import { UnsupportedSignatureError } from './errors';
11
+
12
+ export interface SignatureNode {
13
+ readonly type: string;
14
+ readonly child: readonly SignatureNode[];
15
+ }
16
+
17
+ const CONTAINER_CLOSE: Record<string, string> = {
18
+ '{': '}',
19
+ '(': ')',
20
+ };
21
+
22
+ // Every basic and container type char D-Bus defines. `h` (UNIX_FD) is deliberately
23
+ // listed as *known* so the parser accepts it structurally — we reject it explicitly in
24
+ // `assertSupportedSignature` with a typed error rather than as a vague parse failure.
25
+ const KNOWN_TYPES = new Set('ybnqiuxtdsogarvhe{}()'.split(''));
26
+
27
+ // UNIX_FD: file-descriptor passing. Unsupported everywhere in this transport.
28
+ const UNSUPPORTED_TYPE = 'h';
29
+
30
+ // Throws UnsupportedSignatureError if the signature contains `h` anywhere (including
31
+ // nested inside arrays, structs, dict entries, or variants). Signatures are pure type
32
+ // strings, so a plain character scan is exact.
33
+ export function assertSupportedSignature(signature: string): void {
34
+ const index = signature.indexOf(UNSUPPORTED_TYPE);
35
+ if (index !== -1) {
36
+ throw new UnsupportedSignatureError(signature, UNSUPPORTED_TYPE);
37
+ }
38
+ }
39
+
40
+ // Parse a full signature (which may contain several top-level complete types) into a
41
+ // flat list of nodes.
42
+ export function parseSignature(signature: string): SignatureNode[] {
43
+ let index = 0;
44
+
45
+ function next(): string | null {
46
+ if (index < signature.length) {
47
+ const char = signature[index] as string;
48
+ index += 1;
49
+ return char;
50
+ }
51
+ return null;
52
+ }
53
+
54
+ function parseOne(char: string): SignatureNode {
55
+ if (!KNOWN_TYPES.has(char)) {
56
+ throw new Error(`Unknown D-Bus type "${char}" in signature "${signature}"`);
57
+ }
58
+
59
+ const children: SignatureNode[] = [];
60
+ switch (char) {
61
+ case 'a': {
62
+ const element = next();
63
+ if (element === null) {
64
+ throw new Error(`Bad signature "${signature}": array with no element type`);
65
+ }
66
+ children.push(parseOne(element));
67
+ return { type: 'a', child: children };
68
+ }
69
+ case '{':
70
+ case '(': {
71
+ const close = CONTAINER_CLOSE[char];
72
+ let element = next();
73
+ while (element !== null && element !== close) {
74
+ children.push(parseOne(element));
75
+ element = next();
76
+ }
77
+ if (element === null) {
78
+ throw new Error(`Bad signature "${signature}": unterminated "${char}"`);
79
+ }
80
+ return { type: char, child: children };
81
+ }
82
+ default:
83
+ return { type: char, child: children };
84
+ }
85
+ }
86
+
87
+ const nodes: SignatureNode[] = [];
88
+ let char = next();
89
+ while (char !== null) {
90
+ nodes.push(parseOne(char));
91
+ char = next();
92
+ }
93
+ return nodes;
94
+ }
95
+
96
+ // Re-serialise a single parsed node back to its signature string. Used to recover the
97
+ // inner signature of a decoded variant, whose contained type the library hands us as a
98
+ // parse tree rather than a string.
99
+ export function signatureFromNode(node: SignatureNode): string {
100
+ switch (node.type) {
101
+ case 'a':
102
+ return `a${signatureFromNode(node.child[0] as SignatureNode)}`;
103
+ case '(':
104
+ return `(${node.child.map(signatureFromNode).join('')})`;
105
+ case '{':
106
+ return `{${node.child.map(signatureFromNode).join('')}}`;
107
+ default:
108
+ return node.type;
109
+ }
110
+ }
@@ -0,0 +1,143 @@
1
+ // Minimal fake D-Bus service built on the SAME `@httptoolkit/dbus-native` library, for
2
+ // the half-(a) conformance tests. It is deliberately tiny — a handful of echo/describe
3
+ // methods and one signal — NOT the MM-faithful object model (root ObjectManager, Modem /
4
+ // Modem3gpp interfaces, SIM objects, bearer tripwires); that richer fake is task A2.3.
5
+ //
6
+ // The service runs with `ReturnLongjs: true` so 64-bit values it receives survive as
7
+ // Long objects and re-marshal losslessly on echo. Decode-direction methods return fixed,
8
+ // hand-built values in the library's native encode shape; encode-direction methods report
9
+ // back a canonical string of what they received, so the tests never depend on this
10
+ // transport's own codec to judge it.
11
+
12
+ import * as dbusNativeModule from '@httptoolkit/dbus-native';
13
+
14
+ export const FAKE_BUS_NAME = 'tv.ceralive.ModemStackFake';
15
+ export const FAKE_PATH = '/tv/ceralive/fake';
16
+ export const FAKE_IFACE = 'tv.ceralive.ModemStackFake.Conformance';
17
+ export const TICK_MEMBER = 'Tick';
18
+
19
+ export const INT64_MAX = 2n ** 63n - 1n;
20
+ export const UINT64_MAX = 2n ** 64n - 1n;
21
+
22
+ type MethodImpl = (...args: unknown[]) => unknown;
23
+
24
+ interface FakeBus {
25
+ connection: {
26
+ on(event: string, handler: (...args: unknown[]) => void): void;
27
+ once(event: string, handler: (...args: unknown[]) => void): void;
28
+ removeListener(event: string, handler: (...args: unknown[]) => void): void;
29
+ };
30
+ requestName(name: string, flags: number): Promise<unknown>;
31
+ setMethodCallHandler(
32
+ path: string,
33
+ iface: string,
34
+ member: string,
35
+ handler: [MethodImpl, string],
36
+ ): void;
37
+ sendSignal(path: string, iface: string, member: string, signature: string, args: unknown[]): void;
38
+ disconnect(): Promise<void>;
39
+ }
40
+
41
+ interface FakeModule {
42
+ createClient(options: { busAddress?: string; socket?: string; ReturnLongjs?: boolean }): FakeBus;
43
+ }
44
+
45
+ const fakeModule = ((dbusNativeModule as { default?: unknown }).default ??
46
+ dbusNativeModule) as unknown as FakeModule;
47
+
48
+ // Fixed GetManagedObjects reply in library-native encode shape: object path → interface
49
+ // name → property name → variant [signature, value]. Exercises the real MM
50
+ // `a{oa{sa{sv}}}` nesting plus a 64-bit variant (t = 2^64-1) and a string variant.
51
+ function managedObjectsValue(): unknown {
52
+ return [
53
+ [
54
+ '/org/freedesktop/ModemManager1/Modem/0',
55
+ [
56
+ [
57
+ 'org.freedesktop.ModemManager1.Modem',
58
+ [
59
+ ['SupportedCapabilities', ['t', UINT64_MAX.toString()]],
60
+ ['SignalQuality', ['u', 87]],
61
+ ['DeviceIdentifier', ['s', 'fake-device-0']],
62
+ ],
63
+ ],
64
+ ],
65
+ ],
66
+ ];
67
+ }
68
+
69
+ export interface FakeService {
70
+ readonly busName: string;
71
+ emitTick(seq: bigint): void;
72
+ stop(): Promise<void>;
73
+ }
74
+
75
+ export interface FakeServiceOptions {
76
+ readonly busAddress?: string;
77
+ readonly socket?: string;
78
+ }
79
+
80
+ export async function startFakeService(options: FakeServiceOptions): Promise<FakeService> {
81
+ const clientOptions: { busAddress?: string; socket?: string; ReturnLongjs?: boolean } = {
82
+ ReturnLongjs: true,
83
+ };
84
+ if (options.socket !== undefined) {
85
+ clientOptions.socket = options.socket;
86
+ } else if (options.busAddress !== undefined) {
87
+ clientOptions.busAddress = options.busAddress;
88
+ }
89
+
90
+ const bus = fakeModule.createClient(clientOptions);
91
+
92
+ await new Promise<void>((resolve, reject) => {
93
+ const onConnect = (): void => {
94
+ bus.connection.removeListener('error', onError);
95
+ resolve();
96
+ };
97
+ const onError = (error: unknown): void => {
98
+ bus.connection.removeListener('connect', onConnect);
99
+ reject(error instanceof Error ? error : new Error(String(error)));
100
+ };
101
+ bus.connection.once('connect', onConnect);
102
+ bus.connection.once('error', onError);
103
+ });
104
+
105
+ // After connect, swallow late socket errors so a killed bus (reconnect test) does not
106
+ // surface an unhandled EventEmitter 'error' from this helper's dead connection.
107
+ bus.connection.on('error', () => undefined);
108
+
109
+ const define = (member: string, impl: MethodImpl, resultSignature: string): void => {
110
+ bus.setMethodCallHandler(FAKE_PATH, FAKE_IFACE, member, [impl, resultSignature]);
111
+ };
112
+
113
+ define('Ping', () => 'pong', 's');
114
+ // The library awaits a Promise returned by a handler, so this replies after a delay —
115
+ // used to prove a late reply still resolves the caller's method call.
116
+ define(
117
+ 'SlowPing',
118
+ (delayMs) => new Promise((resolve) => setTimeout(() => resolve('pong'), Number(delayMs))),
119
+ 's',
120
+ );
121
+ define('GetManagedObjects', () => managedObjectsValue(), 'a{oa{sa{sv}}}');
122
+ define('GetInt64', () => INT64_MAX.toString(), 'x');
123
+ define('GetUint64', () => UINT64_MAX.toString(), 't');
124
+ // Echo re-marshals the received Long — an exact 64-bit round-trip through the daemon.
125
+ define('EchoInt64', (value) => value, 'x');
126
+ define('EchoUint64', (value) => value, 't');
127
+ // Describe reports the received value's exact decimal string, judging the transport's
128
+ // encode without re-encoding anything.
129
+ define('DescribeInt64', (value) => String(value), 's');
130
+ define('DescribeUint64', (value) => String(value), 's');
131
+
132
+ await bus.requestName(FAKE_BUS_NAME, 0);
133
+
134
+ return {
135
+ busName: FAKE_BUS_NAME,
136
+ emitTick(seq: bigint): void {
137
+ bus.sendSignal(FAKE_PATH, FAKE_IFACE, TICK_MEMBER, 't', [seq.toString()]);
138
+ },
139
+ async stop(): Promise<void> {
140
+ await bus.disconnect().catch(() => undefined);
141
+ },
142
+ };
143
+ }