Skip to content

Commit 99fe63d

Browse files
committed
style: reformat code with prettier
1 parent 412ff31 commit 99fe63d

File tree

14 files changed

+187
-234
lines changed

14 files changed

+187
-234
lines changed

src/APIClient.ts

Lines changed: 46 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { WebSocket } from "ws";
1+
import { WebSocket } from 'ws';
22
import type {
33
APICommand,
44
APIError,
@@ -8,11 +8,10 @@ import type {
88
APIResultError,
99
APISimStartParams,
1010
PinReadResponse,
11-
} from "./APITypes.js";
12-
import { readVersion } from "./readVersion.js";
11+
} from './APITypes.js';
12+
import { readVersion } from './readVersion.js';
1313

14-
const DEFAULT_SERVER =
15-
process.env.WOKWI_CLI_SERVER ?? "wss://wokwi.com/api/ws/beta";
14+
const DEFAULT_SERVER = process.env.WOKWI_CLI_SERVER ?? 'wss://wokwi.com/api/ws/beta';
1615
const retryDelays = [1000, 2000, 5000, 10000, 20000];
1716

1817
export class APIClient {
@@ -33,7 +32,10 @@ export class APIClient {
3332
onEvent?: (event: APIEvent) => void;
3433
onError?: (error: APIError) => void;
3534

36-
constructor(readonly token: string, readonly server = DEFAULT_SERVER) {
35+
constructor(
36+
readonly token: string,
37+
readonly server = DEFAULT_SERVER,
38+
) {
3739
this.socket = this.createSocket(token, server);
3840
this.connected = this.connectSocket(this.socket);
3941
}
@@ -43,60 +45,51 @@ export class APIClient {
4345
return new WebSocket(server, {
4446
headers: {
4547
Authorization: `Bearer ${token}`,
46-
"User-Agent": `wokwi-cli/${version} (${sha})`,
48+
'User-Agent': `wokwi-cli/${version} (${sha})`,
4749
},
4850
});
4951
}
5052

5153
private async connectSocket(socket: WebSocket) {
5254
await new Promise((resolve, reject) => {
53-
socket.addEventListener("message", ({ data }) => {
54-
if (typeof data === "string") {
55+
socket.addEventListener('message', ({ data }) => {
56+
if (typeof data === 'string') {
5557
const message = JSON.parse(data);
5658
this.processMessage(message);
5759
} else {
58-
console.error("Unsupported binary message");
60+
console.error('Unsupported binary message');
5961
}
6062
});
61-
this.socket.addEventListener("open", resolve);
62-
this.socket.on("unexpected-response", (req, res) => {
63+
this.socket.addEventListener('open', resolve);
64+
this.socket.on('unexpected-response', (req, res) => {
6365
this.closed = true;
6466
this.socket.close();
6567
const RequestTimeout = 408;
6668
const ServiceUnavailable = 503;
67-
if (
68-
res.statusCode === ServiceUnavailable ||
69-
res.statusCode === RequestTimeout
70-
) {
69+
if (res.statusCode === ServiceUnavailable || res.statusCode === RequestTimeout) {
7170
console.warn(
72-
`Connection to ${this.server} failed: ${res.statusMessage ?? ""} (${
73-
res.statusCode
74-
}).`
71+
`Connection to ${this.server} failed: ${res.statusMessage ?? ''} (${res.statusCode}).`,
7572
);
7673
resolve(this.retryConnection());
7774
} else {
7875
reject(
7976
new Error(
80-
`Error connecting to ${this.server}: ${res.statusCode} ${
81-
res.statusMessage ?? ""
82-
}`
83-
)
77+
`Error connecting to ${this.server}: ${res.statusCode} ${res.statusMessage ?? ''}`,
78+
),
8479
);
8580
}
8681
});
87-
this.socket.addEventListener("error", (event) => {
88-
reject(
89-
new Error(`Error connecting to ${this.server}: ${event.message}`)
90-
);
82+
this.socket.addEventListener('error', (event) => {
83+
reject(new Error(`Error connecting to ${this.server}: ${event.message}`));
9184
});
92-
this.socket.addEventListener("close", (event) => {
85+
this.socket.addEventListener('close', (event) => {
9386
if (this.closed) {
9487
return;
9588
}
9689

9790
const message = `Connection to ${this.server} closed unexpectedly: code ${event.code}`;
9891
if (this.onError) {
99-
this.onError({ type: "error", message });
92+
this.onError({ type: 'error', message });
10093
} else {
10194
console.error(message);
10295
}
@@ -121,66 +114,64 @@ export class APIClient {
121114
}
122115

123116
async fileUpload(name: string, content: string | ArrayBuffer) {
124-
if (typeof content === "string") {
125-
return await this.sendCommand("file:upload", { name, text: content });
117+
if (typeof content === 'string') {
118+
return await this.sendCommand('file:upload', { name, text: content });
126119
} else {
127-
return await this.sendCommand("file:upload", {
120+
return await this.sendCommand('file:upload', {
128121
name,
129-
binary: Buffer.from(content).toString("base64"),
122+
binary: Buffer.from(content).toString('base64'),
130123
});
131124
}
132125
}
133126

134127
async simStart(params: APISimStartParams) {
135128
this._running = false;
136-
return await this.sendCommand("sim:start", params);
129+
return await this.sendCommand('sim:start', params);
137130
}
138131

139132
async simPause() {
140-
return await this.sendCommand("sim:pause");
133+
return await this.sendCommand('sim:pause');
141134
}
142135

143136
async simResume(pauseAfter?: number) {
144137
this._running = true;
145-
return await this.sendCommand("sim:resume", { pauseAfter });
138+
return await this.sendCommand('sim:resume', { pauseAfter });
146139
}
147140

148141
async simRestart({ pause }: { pause?: boolean } = {}) {
149-
return await this.sendCommand("sim:restart", { pause });
142+
return await this.sendCommand('sim:restart', { pause });
150143
}
151144

152145
async simStatus() {
153-
return await this.sendCommand<{ running: boolean; nanos: number }>(
154-
"sim:status"
155-
);
146+
return await this.sendCommand<{ running: boolean; nanos: number }>('sim:status');
156147
}
157148

158149
async serialMonitorListen() {
159-
return await this.sendCommand("serial-monitor:listen");
150+
return await this.sendCommand('serial-monitor:listen');
160151
}
161152

162153
async serialMonitorWrite(bytes: number[] | Uint8Array) {
163-
return await this.sendCommand("serial-monitor:write", {
154+
return await this.sendCommand('serial-monitor:write', {
164155
bytes: Array.from(bytes),
165156
});
166157
}
167158

168159
async framebufferRead(partId: string) {
169-
return await this.sendCommand<{ png: string }>("framebuffer:read", {
160+
return await this.sendCommand<{ png: string }>('framebuffer:read', {
170161
id: partId,
171162
});
172163
}
173164

174165
async controlSet(partId: string, control: string, value: number) {
175-
return await this.sendCommand("control:set", {
166+
return await this.sendCommand('control:set', {
176167
part: partId,
177168
control,
178169
value,
179170
});
180171
}
181172

182173
async pinRead(partId: string, pin: string) {
183-
return await this.sendCommand<PinReadResponse>("pin:read", {
174+
return await this.sendCommand<PinReadResponse>('pin:read', {
184175
part: partId,
185176
pin,
186177
});
@@ -191,7 +182,7 @@ export class APIClient {
191182
const id = this.lastId++;
192183
this.pendingCommands.set(id.toString(), [resolve, reject]);
193184
const message: APICommand = {
194-
type: "command",
185+
type: 'command',
195186
command,
196187
params,
197188
id: id.toString(),
@@ -210,47 +201,44 @@ export class APIClient {
210201

211202
processMessage(message: APIError | APIHello | APIEvent | APIResponse) {
212203
switch (message.type) {
213-
case "error":
204+
case 'error':
214205
if (this.onError) {
215206
this.onError(message);
216207
}
217-
console.error("API Error:", message.message);
208+
console.error('API Error:', message.message);
218209
if (this.pendingCommands.size > 0) {
219210
const [, reject] = this.pendingCommands.values().next().value;
220211
reject(new Error(message.message));
221212
}
222213
break;
223214

224-
case "hello":
215+
case 'hello':
225216
if (message.protocolVersion !== 1) {
226-
console.warn(
227-
"Unsupported Wokwi API protocol version",
228-
message.protocolVersion
229-
);
217+
console.warn('Unsupported Wokwi API protocol version', message.protocolVersion);
230218
}
231219
this.onConnected?.(message);
232220
break;
233221

234-
case "event":
222+
case 'event':
235223
this.processEvent(message);
236224
break;
237225

238-
case "response":
226+
case 'response':
239227
this.processResponse(message);
240228
break;
241229
}
242230
}
243231

244232
processEvent(message: APIEvent) {
245-
if (message.event === "sim:pause") {
233+
if (message.event === 'sim:pause') {
246234
this._running = false;
247235
}
248236
this._lastNanos = message.nanos;
249237
this.onEvent?.(message);
250238
}
251239

252240
processResponse(message: APIResponse) {
253-
const id = message.id ?? "";
241+
const id = message.id ?? '';
254242
const [resolve, reject] = this.pendingCommands.get(id) ?? [];
255243
if (resolve && reject) {
256244
this.pendingCommands.delete(id);
@@ -261,7 +249,7 @@ export class APIClient {
261249
resolve(message.result);
262250
}
263251
} else {
264-
console.error("Unknown response", message);
252+
console.error('Unknown response', message);
265253
}
266254
}
267255

src/TestScenario.ts

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
import chalkTemplate from "chalk-template";
2-
import type { APIClient } from "./APIClient.js";
3-
import type { EventManager } from "./EventManager.js";
1+
import chalkTemplate from 'chalk-template';
2+
import type { APIClient } from './APIClient.js';
3+
import type { EventManager } from './EventManager.js';
44

55
export interface IScenarioCommand {
66
validate?(params: any): boolean;
77
run(scenario: TestScenario, client: APIClient, params: any): Promise<void>;
88
}
99

10-
const validStepKeys = ["name"];
10+
const validStepKeys = ['name'];
1111

1212
export interface IStepDefinition {
1313
name?: string;
@@ -30,7 +30,7 @@ export class TestScenario {
3030

3131
constructor(
3232
readonly scenario: IScenarioDefinition,
33-
readonly eventManager: EventManager
33+
readonly eventManager: EventManager,
3434
) {}
3535

3636
registerCommands(commands: Record<string, IScenarioCommand>) {
@@ -43,7 +43,7 @@ export class TestScenario {
4343
throw new Error(`Scenario name is missing`);
4444
}
4545

46-
if (typeof scenario.name !== "string") {
46+
if (typeof scenario.name !== 'string') {
4747
throw new Error(`Scenario name must be a string`);
4848
}
4949

@@ -56,15 +56,12 @@ export class TestScenario {
5656
}
5757

5858
for (const step of scenario.steps) {
59-
if (typeof step !== "object") {
59+
if (typeof step !== 'object') {
6060
throw new Error(`Scenario step must be an object`);
6161
}
6262

6363
for (const key of Object.keys(step)) {
64-
if (
65-
!validStepKeys.includes(key) &&
66-
!Object.keys(this.handlers).includes(key)
67-
) {
64+
if (!validStepKeys.includes(key) && !Object.keys(this.handlers).includes(key)) {
6865
throw new Error(`Invalid scenario step key: ${key}`);
6966
}
7067
}
@@ -96,7 +93,7 @@ export class TestScenario {
9693
return;
9794
}
9895
}
99-
console.error("Unknown key in step: ", step);
96+
console.error('Unknown key in step: ', step);
10097
process.exit(1);
10198
}
10299

@@ -110,9 +107,7 @@ export class TestScenario {
110107

111108
async resume() {
112109
await this.client?.simResume(
113-
this.eventManager.timeToNextEvent >= 0
114-
? this.eventManager.timeToNextEvent
115-
: undefined
110+
this.eventManager.timeToNextEvent >= 0 ? this.eventManager.timeToNextEvent : undefined,
116111
);
117112
}
118113
}

src/config.ts

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import { parse as tomlParse } from "@iarna/toml";
2-
import type { WokwiTOML } from "./WokwiConfig.js";
1+
import { parse as tomlParse } from '@iarna/toml';
2+
import type { WokwiTOML } from './WokwiConfig.js';
33

44
export async function parseConfig(data: string, configRoot: string) {
5-
const tomlSource = data.replace(/\r\n/g, "\n");
5+
const tomlSource = data.replace(/\r\n/g, '\n');
66
try {
77
const tomlData = tomlParse(tomlSource);
88
if (tomlData?.wokwi) {
@@ -12,16 +12,14 @@ export async function parseConfig(data: string, configRoot: string) {
1212
throw new Error(`Unsupported wokwi.toml version: ${wokwi.version}`);
1313
}
1414

15-
if (typeof wokwi.firmware !== "string" || typeof wokwi.elf !== "string") {
16-
throw new Error("Firmware and ELF paths must be strings");
15+
if (typeof wokwi.firmware !== 'string' || typeof wokwi.elf !== 'string') {
16+
throw new Error('Firmware and ELF paths must be strings');
1717
}
1818

1919
return wokwiConfig;
2020
}
21-
throw new Error("Missing `[wokwi]` section in wokwi.toml");
21+
throw new Error('Missing `[wokwi]` section in wokwi.toml');
2222
} catch (err: any) {
23-
throw new Error(
24-
`Error in wokwi.toml: ${(err?.message as string).replace(/:?\n.+/g, "")}`
25-
);
23+
throw new Error(`Error in wokwi.toml: ${(err?.message as string).replace(/:?\n.+/g, '')}`);
2624
}
2725
}

src/help.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import chalkTemplate from "chalk-template";
1+
import chalkTemplate from 'chalk-template';
22

33
export function cliHelp() {
44
console.log(chalkTemplate`

src/loadChips.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
import { existsSync } from "fs";
2-
import { join, resolve } from "path";
3-
import type { WokwiTOMLChip } from "./WokwiConfig.js";
1+
import { existsSync } from 'fs';
2+
import { join, resolve } from 'path';
3+
import type { WokwiTOMLChip } from './WokwiConfig.js';
44

55
function removeExtension(path: string) {
6-
return path.replace(/\.[^.]+$/, "");
6+
return path.replace(/\.[^.]+$/, '');
77
}
88

99
export function loadChips(chips: WokwiTOMLChip[], rootDir: string) {
@@ -15,7 +15,7 @@ export function loadChips(chips: WokwiTOMLChip[], rootDir: string) {
1515
process.exit(1);
1616
}
1717

18-
const jsonPath = join(rootDir, removeExtension(chip.binary) + ".json");
18+
const jsonPath = join(rootDir, removeExtension(chip.binary) + '.json');
1919
if (!existsSync(jsonPath)) {
2020
console.error(`Error: chip JSON file not found: ${resolve(jsonPath)}`);
2121
process.exit(1);

0 commit comments

Comments
 (0)