opencode-codebuddy-quota 0.0.0-stage → 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.
@@ -0,0 +1,77 @@
1
+ import { DatabaseSync } from "node:sqlite"
2
+ import { homedir } from "node:os"
3
+ import { join } from "node:path"
4
+ import type { ModelsDevCatalog } from "./pricing"
5
+
6
+ /**
7
+ * Reads the models.dev catalog out of the database OpenCode keeps for itself.
8
+ *
9
+ * The catalog is stored as a `kv` row whose `value` is JSON wrapping a `body`
10
+ * string that is itself JSON — two parses, not one. Everything here is
11
+ * best-effort: a missing database, a schema change, or a locked file must
12
+ * degrade to "no prices" rather than break the plugin.
13
+ */
14
+
15
+ const KV_KEY = "models-dev:v3:catalog"
16
+ const DB_FILE = "opencode.db"
17
+ /** Long enough to ride out another process's write lock, short enough not to stall a transform. */
18
+ const BUSY_TIMEOUT_MS = 2_000
19
+
20
+ /**
21
+ * OpenCode's data directory. Mirrors its own precedence so a relocated install
22
+ * is picked up without configuration.
23
+ */
24
+ export function storageDir(
25
+ env: Record<string, string | undefined> = process.env,
26
+ home: string = homedir(),
27
+ ): string {
28
+ const explicit = env.OPENCODE_STORAGE_DIR
29
+ if (explicit) return explicit
30
+ const xdg = env.XDG_DATA_HOME
31
+ if (xdg) return join(xdg, "opencode")
32
+ return join(home, ".local", "share", "opencode")
33
+ }
34
+
35
+ /** `{ updatedAt, digest, body: "<json>" }` → the catalog. Null if either layer is unparseable. */
36
+ export function parseCatalogValue(value: string): ModelsDevCatalog | null {
37
+ try {
38
+ const outer = JSON.parse(value) as { body?: unknown }
39
+ if (typeof outer?.body !== "string") return null
40
+ const catalog = JSON.parse(outer.body) as unknown
41
+ if (typeof catalog !== "object" || catalog === null) return null
42
+ return catalog as ModelsDevCatalog
43
+ } catch {
44
+ return null
45
+ }
46
+ }
47
+
48
+ export interface ReadCatalogDeps {
49
+ dbPath?: string
50
+ /** Seam for tests: given the database path and kv key, return the raw `kv.value` or null. */
51
+ readValue?: (dbPath: string, key: string) => string | null
52
+ }
53
+
54
+ function readValueFromDatabase(dbPath: string, key: string): string | null {
55
+ // Read-only: the plugin must never write to OpenCode's database.
56
+ const db = new DatabaseSync(dbPath, { readOnly: true })
57
+ try {
58
+ db.exec(`pragma busy_timeout = ${BUSY_TIMEOUT_MS}`)
59
+ const row = db.prepare("select value from kv where key = ?").get(key) as { value?: unknown } | undefined
60
+ return typeof row?.value === "string" ? row.value : null
61
+ } finally {
62
+ db.close()
63
+ }
64
+ }
65
+
66
+ /** The whole models.dev catalog, or null when it cannot be read. Never throws. */
67
+ export function readModelsDevCatalog(deps: ReadCatalogDeps = {}): ModelsDevCatalog | null {
68
+ const dbPath = deps.dbPath ?? join(storageDir(), DB_FILE)
69
+ const read = deps.readValue ?? readValueFromDatabase
70
+ try {
71
+ const value = read(dbPath, KV_KEY)
72
+ if (value === null) return null
73
+ return parseCatalogValue(value)
74
+ } catch {
75
+ return null
76
+ }
77
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The `@ai-sdk/openai-compatible` spec inside the user's `codebuddy` provider,
3
+ * and validation for the versions that feed it.
4
+ *
5
+ * The provider block itself is the user's: it carries their endpoint, their key
6
+ * reference and anything else they wrote. The plugin only owns the `package`
7
+ * spec, whose version it keeps current.
8
+ */
9
+
10
+ /** New v2 provider ids. The legacy `codebuddy` id is intentionally absent. */
11
+ export const PROVIDER_IDS = ["codebuddy-cn", "codebuddy-intl"] as const
12
+ export type ProviderId = (typeof PROVIDER_IDS)[number]
13
+
14
+ export const PACKAGE_PREFIX = "aisdk:"
15
+ export const PACKAGE_NAME = "@ai-sdk/openai-compatible"
16
+
17
+ /**
18
+ * The version this build was tested against, used when npm cannot be reached.
19
+ * `config.ts` seeds `package_version` with it, and `config.test.ts` keeps that,
20
+ * `config.default.json` and this constant equal.
21
+ */
22
+ export const DEFAULT_PACKAGE_VERSION = "2.0.90"
23
+
24
+ /** A published version and nothing else: `2.0.90`, `2.1.0-rc.1`, `2.1.0+build`. */
25
+ const VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/
26
+
27
+ export function isVersion(value: unknown): value is string {
28
+ return typeof value === "string" && VERSION_PATTERN.test(value)
29
+ }
30
+
31
+ /**
32
+ * `aisdk:@ai-sdk/openai-compatible@2.0.90`. OpenCode strips the `aisdk:` prefix
33
+ * and resolves the rest as an npm specifier, caching it under `<name>@<version>`
34
+ * — which is why the version has to be spelled out and kept current.
35
+ *
36
+ * Throws on a non-version: this is the last point before the value becomes a
37
+ * spec, and a stray file or empty string must never get this far.
38
+ */
39
+ export function packageSpec(version: string): string {
40
+ if (!isVersion(version)) throw new Error(`not a version: ${JSON.stringify(version)}`)
41
+ return `${PACKAGE_PREFIX}${PACKAGE_NAME}@${version}`
42
+ }
@@ -0,0 +1,51 @@
1
+ import { PACKAGE_NAME, PACKAGE_PREFIX, isVersion, packageSpec } from "./package-spec"
2
+ import { timeoutSignal } from "./signal"
3
+
4
+ /**
5
+ * Looks up the newest `@ai-sdk/openai-compatible` build published under the
6
+ * `ai-v6` dist-tag.
7
+ *
8
+ * OpenCode resolves a bare `@ai-sdk/*` spec through that tag, but it caches the
9
+ * result under `<name>@<version>` and never re-resolves. Writing an explicit
10
+ * version into the config is therefore the only way an upgrade takes effect,
11
+ * which is why this exists rather than letting OpenCode follow the tag.
12
+ */
13
+
14
+ /** The dist-tag OpenCode's own `aisdk:` resolution points at. */
15
+ export const DIST_TAG = "ai-v6"
16
+ export const REGISTRY_URL = `https://registry.npmjs.org/${PACKAGE_NAME}`
17
+
18
+ const DEFAULT_TIMEOUT_MS = 10_000
19
+
20
+ export interface LatestVersionDeps {
21
+ fetchImpl?: typeof fetch
22
+ timeoutMs?: number
23
+ }
24
+
25
+ /** The version the tag points at, or null when the registry cannot be read. Never throws. */
26
+ export async function latestTaggedVersion(deps: LatestVersionDeps = {}): Promise<string | null> {
27
+ const fetchImpl = deps.fetchImpl ?? fetch
28
+ try {
29
+ const response = await fetchImpl(REGISTRY_URL, {
30
+ // The abbreviated doc is enough: it carries dist-tags and is far smaller.
31
+ headers: { accept: "application/vnd.npm.install-v1+json" },
32
+ signal: timeoutSignal(deps.timeoutMs ?? DEFAULT_TIMEOUT_MS),
33
+ })
34
+ if (!response.ok) return null
35
+ const body = (await response.json()) as { "dist-tags"?: Record<string, unknown> }
36
+ const version = body?.["dist-tags"]?.[DIST_TAG]
37
+ return isVersion(version) ? version : null
38
+ } catch {
39
+ return null
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Rewrites the version inside an `aisdk:` provider package spec, or returns
45
+ * null when the spec names some other package. A bare spec gains the version.
46
+ */
47
+ export function withVersion(spec: string, version: string): string | null {
48
+ const prefix = `${PACKAGE_PREFIX}${PACKAGE_NAME}`
49
+ if (spec !== prefix && !spec.startsWith(`${prefix}@`)) return null
50
+ return packageSpec(version)
51
+ }
@@ -0,0 +1,169 @@
1
+ import type { ModelMapping } from "./config"
2
+
3
+ /**
4
+ * Pricing and reasoning levels for a CodeBuddy model, taken from the models.dev
5
+ * catalog that OpenCode keeps locally.
6
+ *
7
+ * Every lookup goes through the user's `models` map: a model is only offered
8
+ * because someone wrote down where it lives, so there is nothing to guess. The
9
+ * same model carries different prices and levels depending on who resells it,
10
+ * which is exactly why the mapping names the provider rather than inferring it.
11
+ */
12
+
13
+ /** models.dev v3 sometimes declares cache.write as per-duration tiers, e.g. {"5m":3,"1h":6}. */
14
+ export type CacheWritePrice = number | Record<string, number>
15
+
16
+ export interface ModelsDevCost {
17
+ text?: {
18
+ input?: { price?: number; cache?: { read?: number; write?: CacheWritePrice } }
19
+ output?: { price?: number }
20
+ }
21
+ }
22
+
23
+ export interface ModelsDevEntry {
24
+ name?: string
25
+ cost?: ModelsDevCost
26
+ capabilities?: {
27
+ reasoning?: {
28
+ supported?: boolean
29
+ toggle?: boolean
30
+ /** Selectable reasoning levels, least to most. */
31
+ effort?: readonly string[]
32
+ /** The level the vendor picks when the caller names none. */
33
+ default?: { type?: string; value?: string } | string
34
+ }
35
+ }
36
+ }
37
+
38
+ /** `{ [providerID]: { models: { [modelID]: entry } } }`, as stored under `models-dev:v3:catalog`. */
39
+ export type ModelsDevCatalog = Record<string, { models?: Record<string, ModelsDevEntry> }>
40
+
41
+ export interface ModelCost {
42
+ input: number
43
+ output: number
44
+ cache: { read: number; write: number }
45
+ }
46
+
47
+ /** What a lookup needs: the models.dev coordinates plus the credit multiplier. */
48
+ export interface PricedModel {
49
+ id: string
50
+ /** Credit multiplier. `0` means the model is free; `null` means the server did not say. */
51
+ credits: number | null
52
+ }
53
+
54
+ const ZERO_COST: ModelCost = { input: 0, output: 0, cache: { read: 0, write: 0 } }
55
+
56
+ /** The models.dev entry a CodeBuddy model maps to, or undefined when unmapped or absent. */
57
+ export function mappingEntry(
58
+ catalog: ModelsDevCatalog | null,
59
+ mapping: ModelMapping | undefined,
60
+ ): ModelsDevEntry | undefined {
61
+ if (!catalog || !mapping) return undefined
62
+ return catalog[mapping.provider]?.models?.[mapping.model]
63
+ }
64
+
65
+ /**
66
+ * Exact id first, then a case-insensitive pass — the server writes
67
+ * `minimax-m3.1-flash` while models.dev writes `MiniMax-M3.1-Flash`.
68
+ *
69
+ * Nothing fuzzier than that: the catalog is full of `-free` siblings
70
+ * (`step-5-preview-free`, `hy3-free`, …) that price at zero, so a prefix or
71
+ * substring match would quietly report those instead of the paid model.
72
+ */
73
+ export function findEntry(
74
+ catalog: ModelsDevCatalog,
75
+ provider: string,
76
+ modelID: string,
77
+ ): ModelsDevEntry | undefined {
78
+ const models = catalog[provider]?.models
79
+ if (!models) return undefined
80
+
81
+ const exact = models[modelID]
82
+ if (exact) return exact
83
+
84
+ const lowered = modelID.toLowerCase()
85
+ for (const [id, entry] of Object.entries(models)) {
86
+ if (id.toLowerCase() === lowered) return entry
87
+ }
88
+ return undefined
89
+ }
90
+
91
+ /** Only a finite number is a usable price; tier objects and strings fall back to zero. */
92
+ function finitePrice(value: unknown): number {
93
+ return typeof value === "number" && Number.isFinite(value) ? value : 0
94
+ }
95
+
96
+ function toCost(entry: ModelsDevEntry): ModelCost | null {
97
+ const text = entry.cost?.text
98
+ const input = text?.input?.price
99
+ const output = text?.output?.price
100
+ if (typeof input !== "number" || typeof output !== "number") return null
101
+ return {
102
+ input,
103
+ output,
104
+ // Most catalog entries omit cache.write; some v3 entries declare it as a
105
+ // per-duration tier object. Neither is a usable scalar, so fall back to zero.
106
+ cache: {
107
+ read: finitePrice(text?.input?.cache?.read),
108
+ write: finitePrice(text?.input?.cache?.write),
109
+ },
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Resolve a model's price, returning `[]` when no price can be trusted — an
115
+ * unpriced model is better than a wrong one.
116
+ */
117
+ export function resolveCost(
118
+ model: PricedModel,
119
+ mapping: ModelMapping | undefined,
120
+ catalog: ModelsDevCatalog | null,
121
+ log: (message: string) => void,
122
+ ): ModelCost[] {
123
+ // Checked before any lookup: a free model needs no price, and looking one up
124
+ // would contradict the credit factor the server reported.
125
+ if (model.credits === 0) return [ZERO_COST]
126
+
127
+ if (!catalog) {
128
+ log(`models.dev catalog unavailable; ${model.id} stays unpriced`)
129
+ return []
130
+ }
131
+ if (!mapping) {
132
+ log(`${model.id} has no models.dev mapping; leaving it unpriced`)
133
+ return []
134
+ }
135
+
136
+ const entry = findEntry(catalog, mapping.provider, mapping.model)
137
+ if (!entry) {
138
+ log(`${mapping.provider} has no entry for ${mapping.model} (${model.id}); leaving it unpriced`)
139
+ return []
140
+ }
141
+ const cost = toCost(entry)
142
+ if (!cost) {
143
+ log(`${mapping.provider}/${mapping.model} has no text pricing; ${model.id} stays unpriced`)
144
+ return []
145
+ }
146
+ return [cost]
147
+ }
148
+
149
+ /**
150
+ * The vendor's own reasoning levels for a model, or null when models.dev has
151
+ * none for it. CodeBuddy's gateway rewrites some of these (it swaps `max` for
152
+ * `xhigh` on `deepseek-v4-pro`, for instance), but the vendor table is the
153
+ * source of record here.
154
+ */
155
+ export function vendorEfforts(
156
+ mapping: ModelMapping | undefined,
157
+ catalog: ModelsDevCatalog | null,
158
+ ): { efforts: string[]; defaultEffort: string | null } | null {
159
+ const reasoning = mappingEntry(catalog, mapping)?.capabilities?.reasoning
160
+ const efforts = reasoning?.effort
161
+ if (!efforts || efforts.length === 0) return null
162
+
163
+ const declared = typeof reasoning.default === "string" ? reasoning.default : reasoning.default?.value ?? null
164
+ return {
165
+ efforts: [...efforts],
166
+ // Only honour a vendor default that is actually one of its levels.
167
+ defaultEffort: declared && efforts.includes(declared) ? declared : null,
168
+ }
169
+ }
@@ -0,0 +1,236 @@
1
+ import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
2
+ import type { Site } from "../shared"
3
+ import { apiHeaders, channelHeaders } from "./headers"
4
+ import { SITE_ENDPOINTS } from "./login"
5
+ import type { TokenStore } from "./token-store"
6
+
7
+ export function routeSite(url: string): Site | null {
8
+ if (url.startsWith("/cn/v2/")) return "cn"
9
+ if (url.startsWith("/intl/v2/")) return "intl"
10
+ return null
11
+ }
12
+
13
+ export function upstreamUrl(site: Site, pathAfterV2: string): string {
14
+ return `${SITE_ENDPOINTS[site].endpoint}/v2/${pathAfterV2}`
15
+ }
16
+
17
+ /** The bits of an HTTP request the handler needs. */
18
+ export interface ProxyRequest {
19
+ url: string
20
+ method?: string
21
+ headers?: Record<string, string | string[] | undefined>
22
+ }
23
+
24
+ /** The bits of an HTTP response the handler writes to. */
25
+ export interface ProxyResponse {
26
+ status(code: number): void
27
+ setHeader(name: string, value: string): void
28
+ write(chunk: string | Uint8Array): void
29
+ end(chunk?: string | Uint8Array): void
30
+ }
31
+
32
+ export interface HandleRequestDeps {
33
+ store: TokenStore
34
+ fetchImpl?: typeof fetch
35
+ /** Reads the inbound body; injectable so the handler is testable without a socket. */
36
+ readBody?: (req: ProxyRequest) => Promise<string>
37
+ /** Aborts when the client disconnects, so we stop the upstream SSE stream. */
38
+ signal?: AbortSignal
39
+ /** Optional logger; errors are logged here, never echoed to the client body. */
40
+ log?: (message: string) => void
41
+ }
42
+
43
+ /** Official identity the intl gateway requires as the first system message. */
44
+ const SYSTEM_PROMPT = "You are CodeBuddy Code."
45
+
46
+ /** Extract plain text from a message content (string or multimodal text parts). */
47
+ function identityText(content: unknown): string | null {
48
+ if (typeof content === "string") return content
49
+ if (Array.isArray(content)) {
50
+ return content
51
+ .filter((part) => part && typeof part === "object" && (part as { type?: unknown }).type === "text")
52
+ .map((part) => String((part as { text?: unknown }).text ?? ""))
53
+ .join("\n")
54
+ }
55
+ return null
56
+ }
57
+
58
+ /**
59
+ * Force `stream:true`, and for intl prepend the official system prompt the
60
+ * gateway's channel verification checks for. A caller-supplied leading system
61
+ * message is kept as-is; only the identity prompt is prepended when missing.
62
+ */
63
+ function prepareBody(body: string, site: Site): string {
64
+ try {
65
+ const parsed = JSON.parse(body) as Record<string, unknown>
66
+ parsed.stream = true
67
+ if (site === "intl" && Array.isArray(parsed.messages) && parsed.messages.length > 0) {
68
+ const messages = parsed.messages as Array<{ role?: unknown; content?: unknown }>
69
+ // The gate requires the identity specifically as a *system* message; a
70
+ // developer-role copy does not satisfy it (verified against the gateway).
71
+ // Normalise content (string or multimodal text parts) and compare exactly:
72
+ // a loose substring would mistake an unrelated message mentioning the
73
+ // name for the identity, while a bare `===` would miss trailing whitespace
74
+ // and inject a duplicate. The identity may sit at any position — only
75
+ // duplicates are avoided (verified against the gateway).
76
+ const hasIdentity = messages.some(
77
+ (m) => m?.role === "system" && identityText(m?.content)?.trim() === SYSTEM_PROMPT,
78
+ )
79
+ if (!hasIdentity) parsed.messages = [{ role: "system", content: SYSTEM_PROMPT }, ...messages]
80
+ }
81
+ return JSON.stringify(parsed)
82
+ } catch {
83
+ return body
84
+ }
85
+ }
86
+
87
+ const copyHeaders = (from: Headers, to: ProxyResponse): void => {
88
+ for (const [key, value] of from.entries()) {
89
+ // Hop-by-hop / framing / content-encoding headers are unsafe to forward:
90
+ // undici already decompressed the body, so a forwarded gzip header would
91
+ // make strict clients try to gunzip plain text.
92
+ if (
93
+ key === "content-length" ||
94
+ key === "transfer-encoding" ||
95
+ key === "connection" ||
96
+ key === "content-encoding" ||
97
+ key === "keep-alive" ||
98
+ key === "upgrade" ||
99
+ key === "trailer"
100
+ ) continue
101
+ to.setHeader(key, value)
102
+ }
103
+ }
104
+
105
+ export async function handleRequest(
106
+ req: ProxyRequest,
107
+ res: ProxyResponse,
108
+ deps: HandleRequestDeps,
109
+ ): Promise<void> {
110
+ const site = routeSite(req.url ?? "")
111
+ if (!site) {
112
+ res.status(404)
113
+ res.end("not found")
114
+ return
115
+ }
116
+ const auth = await deps.store.ensureFresh(site)
117
+ const pathAfterV2 = req.url!.split("/v2/")[1] ?? ""
118
+ const url = upstreamUrl(site, pathAfterV2)
119
+ const readBody = deps.readBody ?? (() => Promise.resolve(""))
120
+ const raw = await readBody(req)
121
+ const body = prepareBody(raw, site)
122
+ const doFetch = deps.fetchImpl ?? fetch
123
+
124
+ let upstream: Response
125
+ try {
126
+ upstream = await doFetch(url, {
127
+ method: "POST",
128
+ headers: {
129
+ ...apiHeaders(auth, { accept: "text/event-stream" }),
130
+ // Only intl is channel-gated; keep CN's existing header set untouched.
131
+ ...(site === "intl" ? channelHeaders() : {}),
132
+ "Content-Type": "application/json",
133
+ },
134
+ body,
135
+ signal: deps.signal,
136
+ })
137
+ } catch (err) {
138
+ deps.log?.(`proxy upstream error: ${String((err as Error)?.message ?? err)}`)
139
+ res.status(502)
140
+ res.end() // never echo internal error detail (host/path) to the caller
141
+ return
142
+ }
143
+
144
+ copyHeaders(upstream.headers, res)
145
+ res.status(upstream.status)
146
+
147
+ const reader = upstream.body?.getReader()
148
+ if (!reader) {
149
+ const text = await upstream.text()
150
+ res.end(text)
151
+ return
152
+ }
153
+ for (;;) {
154
+ const { done, value } = await reader.read()
155
+ if (done) break
156
+ res.write(value)
157
+ }
158
+ res.end()
159
+ }
160
+
161
+ export interface ProxyServer {
162
+ start(port: number): Promise<void>
163
+ close(): Promise<void>
164
+ }
165
+
166
+ export function createProxy(deps: {
167
+ store: TokenStore
168
+ fetchImpl?: typeof fetch
169
+ log?: (message: string) => void
170
+ }): ProxyServer {
171
+ const server = createServer((incoming: IncomingMessage, outgoing: ServerResponse) => {
172
+ const headers: Record<string, string> = {}
173
+ for (const [k, v] of Object.entries(incoming.headers)) {
174
+ if (typeof v === "string") headers[k] = v
175
+ else if (Array.isArray(v)) headers[k] = v.join(", ")
176
+ }
177
+ const controller = new AbortController()
178
+ // A client that disconnects (Esc / tab close) must stop the upstream stream,
179
+ // otherwise the full SSE answer is generated and billed to the user's quota.
180
+ outgoing.on("close", () => controller.abort())
181
+ incoming.on("aborted", () => controller.abort())
182
+ const chunks: Buffer[] = []
183
+ let size = 0
184
+ const MAX_BODY = 8 * 1024 * 1024
185
+ let tooLarge = false
186
+ incoming.on("data", (c: Buffer) => {
187
+ size += c.length
188
+ if (size > MAX_BODY) {
189
+ tooLarge = true
190
+ controller.abort()
191
+ return
192
+ }
193
+ chunks.push(c)
194
+ })
195
+ incoming.on("end", () => {
196
+ if (tooLarge || controller.signal.aborted) {
197
+ if (!outgoing.headersSent) outgoing.writeHead(413)
198
+ outgoing.end()
199
+ return
200
+ }
201
+ const text = Buffer.concat(chunks).toString("utf8")
202
+ const response: ProxyResponse = {
203
+ status: (code) => outgoing.writeHead(code),
204
+ setHeader: (name, value) => outgoing.setHeader(name, value),
205
+ write: (chunk) => { outgoing.write(chunk) },
206
+ end: (chunk) => { outgoing.end(chunk) },
207
+ }
208
+ void handleRequest(
209
+ { url: incoming.url ?? "", method: incoming.method, headers },
210
+ response,
211
+ {
212
+ store: deps.store,
213
+ fetchImpl: deps.fetchImpl,
214
+ readBody: async () => text,
215
+ signal: controller.signal,
216
+ log: deps.log,
217
+ },
218
+ ).catch(() => {
219
+ if (controller.signal.aborted) return
220
+ if (!outgoing.headersSent) outgoing.writeHead(500)
221
+ outgoing.end()
222
+ })
223
+ })
224
+ })
225
+ return {
226
+ start: (port) =>
227
+ new Promise<void>((resolve, reject) => {
228
+ server.once("error", reject)
229
+ server.listen(port, "127.0.0.1", () => resolve())
230
+ }),
231
+ close: () =>
232
+ new Promise<void>((resolve, reject) => {
233
+ server.close((err) => (err ? reject(err) : resolve()))
234
+ }),
235
+ }
236
+ }