@deadair/plugin-sdk 0.77.4 → 0.77.6
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.
- package/dist/index.js +31 -0
- package/dist/index.js.map +1 -1
- package/dist/plugin.config.read.d.ts +18 -0
- package/dist/plugin.config.read.d.ts.map +1 -1
- package/dist/plugin.http.d.ts +44 -1
- package/dist/plugin.http.d.ts.map +1 -1
- package/dist/testing/fake.plugin.host.d.ts +20 -0
- package/dist/testing/fake.plugin.host.d.ts.map +1 -1
- package/dist/testing/index.js +24 -1
- package/dist/testing/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -31,6 +31,24 @@ export declare function configString(value: unknown): string | undefined;
|
|
|
31
31
|
* and change nothing else.
|
|
32
32
|
*/
|
|
33
33
|
export declare function configBaseUrl(value: unknown): string;
|
|
34
|
+
/**
|
|
35
|
+
* A multi-line config field as its non-empty, trimmed lines.
|
|
36
|
+
*
|
|
37
|
+
* Commas separate as well as newlines, because a list of chat or channel ids is
|
|
38
|
+
* what people paste, and they paste it comma-separated as often as one per line.
|
|
39
|
+
* Anything that is not a string is an empty list.
|
|
40
|
+
*/
|
|
41
|
+
export declare function configLines(value: unknown): string[];
|
|
42
|
+
/**
|
|
43
|
+
* A boolean config field, or `fallback` when it is not set.
|
|
44
|
+
*
|
|
45
|
+
* Plugin config is jsonb, so a checkbox arrives as a real boolean and this is
|
|
46
|
+
* mostly a narrowing. The string arm covers a row hand-edited in psql, where
|
|
47
|
+
* `"false"` would otherwise be truthy: the same trap `settingIsOn` exists for on
|
|
48
|
+
* the station's own settings, where it cost six switches. Anything else,
|
|
49
|
+
* including absent, takes the fallback.
|
|
50
|
+
*/
|
|
51
|
+
export declare function configFlag(value: unknown, fallback: boolean): boolean;
|
|
34
52
|
/**
|
|
35
53
|
* The credential one ROW of a `list` field holds, or `undefined` when the operator has not set it.
|
|
36
54
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.config.read.d.ts","sourceRoot":"","sources":["../src/plugin.config.read.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD;;;;;;;;;;;;GAYG;AAEH;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAK/D;AAED;;;;;;;;;GASG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAEpD;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,aAAa,CAAC,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAKnJ"}
|
|
1
|
+
{"version":3,"file":"plugin.config.read.d.ts","sourceRoot":"","sources":["../src/plugin.config.read.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD;;;;;;;;;;;;GAYG;AAEH;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAK/D;AAED;;;;;;;;;GASG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAEpD;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,EAAE,CAMpD;AAED;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,GAAG,OAAO,CAIrE;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,aAAa,CAAC,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAKnJ"}
|
package/dist/plugin.http.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { HostFetchMethod } from './plugin.host.js';
|
|
2
|
-
import type
|
|
2
|
+
import { PluginError, type PluginErrorCode } from './plugin.error.js';
|
|
3
3
|
/**
|
|
4
4
|
* An upstream's sentence, bounded.
|
|
5
5
|
*
|
|
@@ -77,4 +77,47 @@ export declare function hostFetchMethod(method: string | undefined): HostFetchMe
|
|
|
77
77
|
* per name. Lower-casing again is free and makes the guarantee local.
|
|
78
78
|
*/
|
|
79
79
|
export declare function headersToRecord(headers: Headers): Record<string, string>;
|
|
80
|
+
/** How an upstream failure is classified, beyond its status. Every field is optional. */
|
|
81
|
+
export interface UpstreamFailure {
|
|
82
|
+
/** The host's reading of it. Defaults to {@link pluginCodeForStatus} of the status. */
|
|
83
|
+
code?: PluginErrorCode;
|
|
84
|
+
/** The service's own code for it, when it sent one. See `PluginError.upstreamCode`. */
|
|
85
|
+
upstreamCode?: string | number;
|
|
86
|
+
/** The upstream's `Retry-After`, already parsed (see {@link retryAfterMs}). Marks the failure retryable. */
|
|
87
|
+
retryAfterMs?: number;
|
|
88
|
+
cause?: unknown;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* The base of every plugin's "the upstream said no" error.
|
|
92
|
+
*
|
|
93
|
+
* Eleven plugins each declared the same class: a `PluginError` carrying the numeric `status`,
|
|
94
|
+
* classified from it, with the retry advice attached when there was some. The subclass is kept
|
|
95
|
+
* rather than replaced, because it is how a plugin tells its own services apart (`musicbrainz` asks
|
|
96
|
+
* `instanceof ListenBrainzRequestError` before it asks anything else) and where a service-specific
|
|
97
|
+
* reading of the failure lives (Spotify's `quotaExhausted`, Deezer's `isNoData`). What moves here
|
|
98
|
+
* is the part they all wrote the same way:
|
|
99
|
+
*
|
|
100
|
+
* ```ts
|
|
101
|
+
* export class PlexRequestError extends UpstreamRequestError {
|
|
102
|
+
* constructor(message: string, status: number) {
|
|
103
|
+
* super(status, message);
|
|
104
|
+
* this.name = 'PlexRequestError';
|
|
105
|
+
* }
|
|
106
|
+
* }
|
|
107
|
+
* ```
|
|
108
|
+
*
|
|
109
|
+
* `status` stays a field of its own beside `upstreamStatus` because it is never absent on most of
|
|
110
|
+
* these, so a plugin branches on it without narrowing. `Status` widens to `number | undefined` for
|
|
111
|
+
* the one service (Subsonic) whose failures can arrive inside a well-formed envelope with no status
|
|
112
|
+
* worth naming.
|
|
113
|
+
*
|
|
114
|
+
* A 200 is never recorded as `upstreamStatus`, although it stays on `status`. A failure that came
|
|
115
|
+
* back inside a 200 is the service's own error (Last.fm's error number, Deezer's code), which is
|
|
116
|
+
* what `upstreamCode` is for, and an `upstreamStatus` of 200 on the settings card reads as "the
|
|
117
|
+
* upstream answered fine".
|
|
118
|
+
*/
|
|
119
|
+
export declare class UpstreamRequestError<Status extends number | undefined = number> extends PluginError {
|
|
120
|
+
readonly status: Status;
|
|
121
|
+
constructor(status: Status, message: string, failure?: UpstreamFailure);
|
|
122
|
+
}
|
|
80
123
|
//# sourceMappingURL=plugin.http.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.http.d.ts","sourceRoot":"","sources":["../src/plugin.http.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,
|
|
1
|
+
{"version":3,"file":"plugin.http.d.ts","sourceRoot":"","sources":["../src/plugin.http.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,EAAE,WAAW,EAAE,KAAK,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAuBtE;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAE/D;AAED;;;;;;;;;;;;GAYG;A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AE,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,eAAoB;CAW7E"}
|
|
@@ -141,6 +141,26 @@ export interface FakeResponseInit {
|
|
|
141
141
|
}
|
|
142
142
|
/** Builds a default 200 `Response`, overridable field by field. */
|
|
143
143
|
export declare function fakeHostFetchResponse(init?: FakeResponseInit): Response;
|
|
144
|
+
/** What a {@link FakeRoute} answers: a status (200 when left out) and a body, sent as JSON unless it is already text. */
|
|
145
|
+
export interface FakeReply {
|
|
146
|
+
status?: number;
|
|
147
|
+
body: unknown;
|
|
148
|
+
}
|
|
149
|
+
/** One path a {@link routedFetch} knows, answering `undefined` for a URL that is not its own. */
|
|
150
|
+
export type FakeRoute = (url: URL, init?: HostFetchInit) => FakeReply | undefined;
|
|
151
|
+
/**
|
|
152
|
+
* A `setFetchImpl` that answers by route, for a plugin test that talks to several paths.
|
|
153
|
+
*
|
|
154
|
+
* The first route that answers wins. Every unrouted call is a 500, so a test that forgot a route
|
|
155
|
+
* fails loudly rather than reading an empty answer. Three provider plugins wrote this same
|
|
156
|
+
* dispatcher into their own tests before it lived here.
|
|
157
|
+
*
|
|
158
|
+
* ```ts
|
|
159
|
+
* const users: FakeRoute = url => (url.pathname === '/Users' ? { body: [{ Name: 'station', Id: 'u1' }] } : undefined);
|
|
160
|
+
* host.setFetchImpl(routedFetch([users, ...routes]));
|
|
161
|
+
* ```
|
|
162
|
+
*/
|
|
163
|
+
export declare function routedFetch(routes: readonly FakeRoute[]): (url: string, init?: HostFetchInit) => Promise<Response>;
|
|
144
164
|
/** A socket that is open until either end closes it. Exported for a test that wants one on its own. */
|
|
145
165
|
export declare function createFakePluginSocket(url: string): FakePluginSocket;
|
|
146
166
|
/** A TLS connection that is open until either end closes it. Exported for a test that wants one on its own. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fake.plugin.host.d.ts","sourceRoot":"","sources":["../../src/testing/fake.plugin.host.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACR,iBAAiB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yHAAyH;AACzH,MAAM,WAAW,SAAS;IACtB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,OAAO,CAAC;CACjB;AAED,iGAAiG;AACjG,MAAM,MAAM,SAAS,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,aAAa,KAAK,SAAS,GAAG,SAAS,CAAC;AAElF;;;;;;;;;;;GAWG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,SAAS,SAAS,EAAE,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,aAAa,KAAK,OAAO,CAAC,QAAQ,CAAC,CAkBlH;AAED,uGAAuG;AACvG,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,MAAM,GAAG,gBAAgB,CAoCpE;AAED,+GAA+G;AAC/G,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,mBAAmB,CAiCtG;AAED,wBAAgB,oBAAoB,IAAI,cAAc,CAwIrD"}
|
package/dist/testing/index.js
CHANGED
|
@@ -26,6 +26,28 @@ function fakeHostFetchResponse(init = {}) {
|
|
|
26
26
|
return response;
|
|
27
27
|
}
|
|
28
28
|
__name(fakeHostFetchResponse, "fakeHostFetchResponse");
|
|
29
|
+
function routedFetch(routes) {
|
|
30
|
+
return async (raw, init) => {
|
|
31
|
+
const url = new URL(raw);
|
|
32
|
+
let reply = {
|
|
33
|
+
status: 500,
|
|
34
|
+
body: "unrouted"
|
|
35
|
+
};
|
|
36
|
+
for (const route of routes) {
|
|
37
|
+
const found = route(url, init);
|
|
38
|
+
if (found !== void 0) {
|
|
39
|
+
reply = found;
|
|
40
|
+
break;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return fakeHostFetchResponse({
|
|
44
|
+
status: reply.status,
|
|
45
|
+
body: typeof reply.body === "string" ? reply.body : JSON.stringify(reply.body),
|
|
46
|
+
url: raw
|
|
47
|
+
});
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
__name(routedFetch, "routedFetch");
|
|
29
51
|
function createFakePluginSocket(url) {
|
|
30
52
|
const messageListeners = [];
|
|
31
53
|
const closeListeners = [];
|
|
@@ -254,6 +276,7 @@ export {
|
|
|
254
276
|
createFakePluginHost,
|
|
255
277
|
createFakePluginSocket,
|
|
256
278
|
createFakePluginTlsSocket,
|
|
257
|
-
fakeHostFetchResponse
|
|
279
|
+
fakeHostFetchResponse,
|
|
280
|
+
routedFetch
|
|
258
281
|
};
|
|
259
282
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/testing/fake.plugin.host.ts"],"sourcesContent":["import { vi } from 'vitest';\n\nimport type {\n DiscoveredService,\n DiscoveryQuery,\n HostFetchInit,\n HostFetchMethod,\n PluginHost,\n PluginSocket,\n PluginTlsOptions,\n PluginTlsSocket,\n ProviderStream,\n ProviderTrack,\n} from '../index.js';\n\n/**\n * Shipped from the SDK rather than copied into each plugin, which three of them\n * were doing — two of those carrying a comment saying the copy was deliberate\n * because plugins do not depend on each other.\n *\n * That reasoning held for the copies and does not hold for this: every plugin\n * already depends on the SDK, and `PluginHost` is the SDK's own contract, so its\n * test double belongs beside the interface it doubles. A plugin importing this\n * gains no dependency on any other plugin. It also means a host method added to\n * the contract turns up in one fake rather than being added to three and\n * forgotten in the other three.\n *\n * Reached as `@deadair/plugin-sdk/testing`, which is kept out of the runtime\n * entry so nothing ships a dependency on vitest.\n */\n\n/** One `host.fetch` call, recorded with only the fields tests care about. */\nexport interface RecordedFetchCall {\n url: string;\n method: HostFetchMethod | undefined;\n headers: Record<string, string> | undefined;\n body: string | undefined;\n}\n\n/**\n * One `host.socket` the plugin opened, driven from the test: frames the plugin sent are in `sent`,\n * and `receive` / `closeFromServer` play the far end.\n */\nexport interface FakePluginSocket extends PluginSocket {\n readonly url: string;\n /** Every text frame the plugin sent, in order. */\n readonly sent: string[];\n /** Whether either end has closed it. */\n readonly closed: boolean;\n /** The frames the plugin sent, each parsed as JSON. */\n sentJson(): unknown[];\n /** Deliver one text frame to the plugin's listeners. */\n receive(text: string): void;\n /** Deliver `JSON.stringify(value)`. */\n receiveJson(value: unknown): void;\n /** Close it from the far end, telling the plugin's close listeners. */\n closeFromServer(code?: number, reason?: string): void;\n}\n\n/**\n * One `host.tls` connection the plugin opened, driven from the test: bytes the plugin wrote are in\n * `sent`, and `receive` / `closeFromServer` play the device.\n */\nexport interface FakePluginTlsSocket extends PluginTlsSocket {\n readonly url: string;\n /** The options the plugin opened it with. */\n readonly options: PluginTlsOptions | undefined;\n /** Every write the plugin made, in order, one entry per `send`. */\n readonly sent: Uint8Array[];\n /** Whether either end has closed it. */\n readonly closed: boolean;\n /** Deliver one chunk to the plugin's data listeners. */\n receive(bytes: Uint8Array): void;\n /** Close it from the far end, telling the plugin's close listeners. */\n closeFromServer(reason?: string): void;\n}\n\n/**\n * A `PluginHost` for tests. `fetch` replays a queue of scripted\n * `Response`s (FIFO, one per call) — or a custom handler installed\n * with `setFetchImpl`, for call-count-driven scenarios like a 401-then-200\n * retry — and records every call it received in `calls`. `storage`, `config`,\n * `secrets` and the `oauth` vault are in-memory and can be seeded or read\n * directly, bypassing the `PluginHost` methods, so a test can assert on state\n * without going through the code under test twice.\n */\nexport interface FakePluginHost extends PluginHost {\n /** Every `host.fetch` call so far, in call order. */\n readonly calls: RecordedFetchCall[];\n /** Set what `host.remainingMs()` reports, for testing budget shedding. */\n seedRemainingMs(ms: number): void;\n /** Push one scripted response onto the back of the reply queue. */\n queueResponse(response: FakeResponseInit): void;\n /** Replace the fetch handler outright; overrides the queue while set. */\n setFetchImpl(impl: (url: string, init?: HostFetchInit) => Promise<Response>): void;\n /** Seed the value `host.config.get()` resolves to. */\n seedConfig(config: Record<string, unknown>): void;\n /** Seed a value `host.secrets.get(key)` resolves to. */\n seedSecret(key: string, value: string): void;\n /** Seed a storage entry directly, bypassing `host.storage.set`. */\n seedStorage(key: string, value: unknown): void;\n /** Read a storage entry directly, bypassing `host.storage.get`. */\n getStorageEntry(key: string): unknown;\n /** All storage keys currently set, unfiltered. */\n storageKeys(): string[];\n /** Seed the oauth vault directly, bypassing `host.oauth.saveTokens`. */\n seedTokens(tokens: Record<string, string>): void;\n /** Read the oauth vault directly, bypassing `host.oauth.getTokens`. */\n getVaultTokens(): Record<string, string> | undefined;\n /** Set what `host.trackFetcher.serve()` answers with; `undefined` means \"this station has no fetcher\". */\n seedFetchedTrack(stream: ProviderStream | undefined): void;\n /**\n * Set what `host.trackFetcher.playlistTracks()` answers with. `undefined` means \"this station\n * has no fetcher\"; pass an `Error` to make it throw, which is the fetcher having tried and\n * failed and is a different case for a plugin to handle.\n */\n seedFetchedPlaylist(tracks: ProviderTrack[] | Error | undefined): void;\n /** Every socket `host.socket` opened, in order, closed ones included. */\n readonly sockets: FakePluginSocket[];\n /** Make every later `host.socket` reject with `error`; `undefined` lets them open again. */\n refuseSockets(error: Error | undefined): void;\n /** Every connection `host.tls` opened, in order, closed ones included. */\n readonly tlsSockets: FakePluginTlsSocket[];\n /** Make every later `host.tls` reject with `error`; `undefined` lets them open again. */\n refuseTls(error: Error | undefined): void;\n /**\n * Called with each connection as `host.tls` opens it, before the plugin sees it, so a test can\n * script the device's answers to whatever the plugin writes.\n */\n onTlsOpen(listener: ((socket: FakePluginTlsSocket) => void) | undefined): void;\n /**\n * What `host.discover` answers from now on: a fixed list, or one worked out per query. Nothing\n * is found until a test says otherwise, which is what a station on a bridge network sees.\n */\n seedDiscovery(found: DiscoveredService[] | ((query: DiscoveryQuery) => DiscoveredService[])): void;\n}\n\n/**\n * What `host.remainingMs()` reports unless a test says otherwise: what a live\n * call reads on its first line. The host's default per-call deadline is 8s, and\n * the clock has already been running for a few milliseconds by the time plugin\n * code asks, so a live call never sees the whole 8s. A plugin that refuses to\n * start unless a full request timeout is left therefore never starts at all,\n * and a default above the real deadline hid exactly that: every test passed\n * while every live call returned nothing.\n */\nconst DEFAULT_REMAINING_MS = 8_000 - 5;\n\n/**\n * What a test says a scripted reply should be.\n *\n * Not `ResponseInit`, because `url` is not on it: `host.fetch` reports the last\n * hop of the redirect chain there, and a `Response` built by hand has an empty\n * one unless it is defined in.\n */\nexport interface FakeResponseInit {\n status?: number;\n statusText?: string;\n headers?: Record<string, string>;\n /**\n * Text for a JSON or error reply, bytes for a binary one.\n *\n * `Uint8Array<ArrayBuffer>` rather than a bare `Uint8Array`: the DOM lib's\n * `BodyInit` accepts a view over a real `ArrayBuffer`, and the unparameterized\n * form widens to `ArrayBufferLike`, which includes `SharedArrayBuffer` and is\n * not something `Response` will take. `new Uint8Array([...])` already has the\n * narrow type, so no test has to say so.\n */\n body?: string | Uint8Array<ArrayBuffer>;\n url?: string;\n}\n\n/** Statuses whose `Response` must carry a null body, or the constructor throws. */\nconst NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);\n\n/** Builds a default 200 `Response`, overridable field by field. */\nexport function fakeHostFetchResponse(init: FakeResponseInit = {}): Response {\n const status = init.status ?? 200;\n\n const response = new Response(NULL_BODY_STATUSES.has(status) ? null : (init.body ?? ''), {\n status,\n statusText: init.statusText ?? 'OK',\n headers: init.headers ?? { 'content-type': 'application/json' },\n });\n\n // Read-only on a constructed response, and part of what the host promises.\n Object.defineProperty(response, 'url', { value: init.url ?? 'https://example.test/' });\n\n return response;\n}\n\n/** A socket that is open until either end closes it. Exported for a test that wants one on its own. */\nexport function createFakePluginSocket(url: string): FakePluginSocket {\n const messageListeners: ((text: string) => void)[] = [];\n const closeListeners: ((code?: number, reason?: string) => void)[] = [];\n const sent: string[] = [];\n let closed = false;\n\n const shut = (code: number | undefined, reason: string | undefined): void => {\n if (closed) return;\n closed = true;\n for (const listener of closeListeners) listener(code, reason);\n };\n\n return {\n url,\n sent,\n get closed() {\n return closed;\n },\n send: vi.fn((text: string) => {\n if (!closed) sent.push(text);\n }),\n close: vi.fn((code?: number, reason?: string) => shut(code ?? 1000, reason)),\n onMessage: listener => void messageListeners.push(listener),\n onClose: listener => void closeListeners.push(listener),\n sentJson: () => sent.map(text => JSON.parse(text) as unknown),\n receive(text) {\n if (closed) throw new Error(`fake plugin socket: ${url} is closed`);\n for (const listener of messageListeners) listener(text);\n },\n receiveJson(value) {\n this.receive(JSON.stringify(value));\n },\n closeFromServer(code = 1000, reason = '') {\n shut(code, reason);\n },\n };\n}\n\n/** A TLS connection that is open until either end closes it. Exported for a test that wants one on its own. */\nexport function createFakePluginTlsSocket(url: string, options?: PluginTlsOptions): FakePluginTlsSocket {\n const dataListeners: ((bytes: Uint8Array) => void)[] = [];\n const closeListeners: ((reason?: string) => void)[] = [];\n const sent: Uint8Array[] = [];\n let closed = false;\n\n const shut = (reason: string | undefined): void => {\n if (closed) return;\n closed = true;\n for (const listener of closeListeners) listener(reason);\n };\n\n return {\n url,\n options,\n sent,\n get closed() {\n return closed;\n },\n send: vi.fn((bytes: Uint8Array) => {\n if (!closed) sent.push(bytes);\n }),\n close: vi.fn(() => shut(undefined)),\n onData: listener => void dataListeners.push(listener),\n onClose: listener => void closeListeners.push(listener),\n receive(bytes) {\n if (closed) throw new Error(`fake plugin tls socket: ${url} is closed`);\n for (const listener of dataListeners) listener(bytes);\n },\n closeFromServer(reason) {\n shut(reason);\n },\n };\n}\n\nexport function createFakePluginHost(): FakePluginHost {\n const calls: RecordedFetchCall[] = [];\n const queue: Response[] = [];\n let customImpl: ((url: string, init?: HostFetchInit) => Promise<Response>) | undefined;\n\n const storageData = new Map<string, unknown>();\n let configData: Record<string, unknown> = {};\n const secretsData = new Map<string, string>();\n let tokens: Record<string, string> | undefined;\n let remainingMs = DEFAULT_REMAINING_MS;\n let fetchedTrack: ProviderStream | undefined = { url: 'http://127.0.0.1:3679/track/song-1?t=signed', expiresAt: 1_893_456_000_000 };\n // Nothing by default: a plugin should ask its own API first, and a test that means to exercise\n // the fetcher says so.\n let fetchedPlaylist: ProviderTrack[] | Error | undefined;\n const sockets: FakePluginSocket[] = [];\n let socketRefusal: Error | undefined;\n const tlsSockets: FakePluginTlsSocket[] = [];\n let tlsRefusal: Error | undefined;\n let tlsOpened: ((socket: FakePluginTlsSocket) => void) | undefined;\n let discovered: (query: DiscoveryQuery) => DiscoveredService[] = () => [];\n\n const fetchImpl = vi.fn(async (url: string, init?: HostFetchInit): Promise<Response> => {\n calls.push({ url, method: init?.method, headers: init?.headers, body: init?.body });\n if (customImpl) return customImpl(url, init);\n const next = queue.shift();\n if (!next) throw new Error(`fake plugin host: no response queued for ${init?.method ?? 'GET'} ${url}`);\n return next;\n });\n\n const host: FakePluginHost = {\n logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },\n fetch: fetchImpl,\n socket: vi.fn(async (url: string) => {\n if (socketRefusal !== undefined) throw socketRefusal;\n const socket = createFakePluginSocket(url);\n sockets.push(socket);\n return socket;\n }),\n tls: vi.fn(async (url: string, options?: PluginTlsOptions) => {\n if (tlsRefusal !== undefined) throw tlsRefusal;\n const socket = createFakePluginTlsSocket(url, options);\n tlsSockets.push(socket);\n tlsOpened?.(socket);\n return socket;\n }),\n discover: vi.fn(async (query: DiscoveryQuery) => discovered(query)),\n // Never aborts: these tests are about what a plugin does with a reply,\n // not about being cancelled half way through one.\n signal: new AbortController().signal,\n remainingMs: vi.fn(() => remainingMs),\n storage: {\n get: vi.fn(async (key: string) => storageData.get(key)),\n set: vi.fn(async (key: string, value: unknown) => {\n storageData.set(key, value);\n }),\n delete: vi.fn(async (key: string) => {\n storageData.delete(key);\n }),\n list: vi.fn(async (prefix?: string) => [...storageData.keys()].filter(key => !prefix || key.startsWith(prefix))),\n },\n secrets: { get: vi.fn(async (key: string) => secretsData.get(key)) },\n config: { get: vi.fn(async () => configData) },\n oauth: {\n getRedirectUri: vi.fn(async () => 'https://example.test/callback'),\n saveTokens: vi.fn(async (next: Record<string, string>) => {\n tokens = next;\n }),\n getTokens: vi.fn(async () => tokens),\n },\n events: { emit: vi.fn() },\n trackFetcher: {\n serve: vi.fn(async () => fetchedTrack),\n // Answers the same canned stream as `serve`: a plugin under test cares that it asked the\n // host for audio and passed the answer through, not which helper the station happens to run\n // behind it. `fetchedTrack` is what a test sets to say \"the station has a fetcher\" or, as\n // undefined, \"it has not got one\".\n servePlayer: vi.fn(async () => fetchedTrack),\n playlistTracks: vi.fn(async () => {\n if (fetchedPlaylist instanceof Error) throw fetchedPlaylist;\n return fetchedPlaylist;\n }),\n },\n calls,\n sockets,\n refuseSockets(error) {\n socketRefusal = error;\n },\n tlsSockets,\n refuseTls(error) {\n tlsRefusal = error;\n },\n onTlsOpen(listener) {\n tlsOpened = listener;\n },\n seedDiscovery(found) {\n discovered = typeof found === 'function' ? found : () => found;\n },\n seedRemainingMs(ms) {\n remainingMs = ms;\n },\n queueResponse(response: FakeResponseInit) {\n queue.push(fakeHostFetchResponse(response));\n },\n setFetchImpl(impl) {\n customImpl = impl;\n },\n seedConfig(config) {\n configData = config;\n },\n seedSecret(key, value) {\n secretsData.set(key, value);\n },\n seedStorage(key, value) {\n storageData.set(key, value);\n },\n getStorageEntry(key) {\n return storageData.get(key);\n },\n storageKeys() {\n return [...storageData.keys()];\n },\n seedTokens(next) {\n tokens = next;\n },\n getVaultTokens() {\n return tokens;\n },\n seedFetchedTrack(stream) {\n fetchedTrack = stream;\n },\n seedFetchedPlaylist(tracks) {\n fetchedPlaylist = tracks;\n },\n };\n\n return host;\n}\n"],"mappings":";;;;;AAAA,SAASA,UAAU;AAkJnB,IAAMC,uBAAuB,MAAQ;AA2BrC,IAAMC,qBAAqB,oBAAIC,IAAI;EAAC;EAAK;EAAK;EAAK;CAAI;AAGhD,SAASC,sBAAsBC,OAAyB,CAAC,GAAC;AAC7D,QAAMC,SAASD,KAAKC,UAAU;AAE9B,QAAMC,WAAW,IAAIC,SAASN,mBAAmBO,IAAIH,MAAAA,IAAU,OAAQD,KAAKK,QAAQ,IAAK;IACrFJ;IACAK,YAAYN,KAAKM,cAAc;IAC/BC,SAASP,KAAKO,WAAW;MAAE,gBAAgB;IAAmB;EA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;AACbhE,mBAAagE;IACjB;IACAC,WAAWrB,QAAM;AACbzC,mBAAayC;IACjB;IACAsB,WAAW/B,KAAKxE,OAAK;AACjByC,kBAAYgC,IAAID,KAAKxE,KAAAA;IACzB;IACAwG,YAAYhC,KAAKxE,OAAK;AAClBsC,kBAAYmC,IAAID,KAAKxE,KAAAA;IACzB;IACAyG,gBAAgBjC,KAAG;AACf,aAAOlC,YAAYiC,IAAIC,GAAAA;IAC3B;IACAkC,cAAAA;AACI,aAAO;WAAIpE,YAAYuC,KAAI;;IAC/B;IACA8B,WAAWpD,MAAI;AACXb,eAASa;IACb;IACAqD,iBAAAA;AACI,aAAOlE;IACX;IACAmE,iBAAiBC,QAAM;AACnBlE,qBAAekE;IACnB;IACAC,oBAAoBC,QAAM;AACtBlE,wBAAkBkE;IACtB;EACJ;AAEA,SAAOvD;AACX;AAxIgBvB;","names":["vi","DEFAULT_REMAINING_MS","NULL_BODY_STATUSES","Set","fakeHostFetchResponse","init","status","response","Response","has","body","statusText","headers","Object","defineProperty","value","url","createFakePluginSocket","messageListeners","closeListeners","sent","closed","shut","code","reason","listener","send","vi","fn","text","push","close","onMessage","onClose","sentJson","map","JSON","parse","receive","Error","receiveJson","stringify","closeFromServer","createFakePluginTlsSocket","options","dataListeners","bytes","undefined","onData","createFakePluginHost","calls","queue","customImpl","storageData","Map","configData","secretsData","tokens","remainingMs","fetchedTrack","expiresAt","fetchedPlaylist","sockets","socketRefusal","tlsSockets","tlsRefusal","tlsOpened","discovered","fetchImpl","method","next","shift","host","logger","debug","info","warn","error","fetch","socket","tls","discover","query","signal","AbortController","storage","get","key","set","delete","list","prefix","keys","filter","startsWith","secrets","config","oauth","getRedirectUri","saveTokens","getTokens","events","emit","trackFetcher","serve","servePlayer","playlistTracks","refuseSockets","refuseTls","onTlsOpen","seedDiscovery","found","seedRemainingMs","ms","queueResponse","setFetchImpl","impl","seedConfig","seedSecret","seedStorage","getStorageEntry","storageKeys","seedTokens","getVaultTokens","seedFetchedTrack","stream","seedFetchedPlaylist","tracks"]}
|
|
1
|
+
{"version":3,"sources":["../../src/testing/fake.plugin.host.ts"],"sourcesContent":["import { vi } from 'vitest';\n\nimport type {\n DiscoveredService,\n DiscoveryQuery,\n HostFetchInit,\n HostFetchMethod,\n PluginHost,\n PluginSocket,\n PluginTlsOptions,\n PluginTlsSocket,\n ProviderStream,\n ProviderTrack,\n} from '../index.js';\n\n/**\n * Shipped from the SDK rather than copied into each plugin, which three of them\n * were doing — two of those carrying a comment saying the copy was deliberate\n * because plugins do not depend on each other.\n *\n * That reasoning held for the copies and does not hold for this: every plugin\n * already depends on the SDK, and `PluginHost` is the SDK's own contract, so its\n * test double belongs beside the interface it doubles. A plugin importing this\n * gains no dependency on any other plugin. It also means a host method added to\n * the contract turns up in one fake rather than being added to three and\n * forgotten in the other three.\n *\n * Reached as `@deadair/plugin-sdk/testing`, which is kept out of the runtime\n * entry so nothing ships a dependency on vitest.\n */\n\n/** One `host.fetch` call, recorded with only the fields tests care about. */\nexport interface RecordedFetchCall {\n url: string;\n method: HostFetchMethod | undefined;\n headers: Record<string, string> | undefined;\n body: string | undefined;\n}\n\n/**\n * One `host.socket` the plugin opened, driven from the test: frames the plugin sent are in `sent`,\n * and `receive` / `closeFromServer` play the far end.\n */\nexport interface FakePluginSocket extends PluginSocket {\n readonly url: string;\n /** Every text frame the plugin sent, in order. */\n readonly sent: string[];\n /** Whether either end has closed it. */\n readonly closed: boolean;\n /** The frames the plugin sent, each parsed as JSON. */\n sentJson(): unknown[];\n /** Deliver one text frame to the plugin's listeners. */\n receive(text: string): void;\n /** Deliver `JSON.stringify(value)`. */\n receiveJson(value: unknown): void;\n /** Close it from the far end, telling the plugin's close listeners. */\n closeFromServer(code?: number, reason?: string): void;\n}\n\n/**\n * One `host.tls` connection the plugin opened, driven from the test: bytes the plugin wrote are in\n * `sent`, and `receive` / `closeFromServer` play the device.\n */\nexport interface FakePluginTlsSocket extends PluginTlsSocket {\n readonly url: string;\n /** The options the plugin opened it with. */\n readonly options: PluginTlsOptions | undefined;\n /** Every write the plugin made, in order, one entry per `send`. */\n readonly sent: Uint8Array[];\n /** Whether either end has closed it. */\n readonly closed: boolean;\n /** Deliver one chunk to the plugin's data listeners. */\n receive(bytes: Uint8Array): void;\n /** Close it from the far end, telling the plugin's close listeners. */\n closeFromServer(reason?: string): void;\n}\n\n/**\n * A `PluginHost` for tests. `fetch` replays a queue of scripted\n * `Response`s (FIFO, one per call) — or a custom handler installed\n * with `setFetchImpl`, for call-count-driven scenarios like a 401-then-200\n * retry — and records every call it received in `calls`. `storage`, `config`,\n * `secrets` and the `oauth` vault are in-memory and can be seeded or read\n * directly, bypassing the `PluginHost` methods, so a test can assert on state\n * without going through the code under test twice.\n */\nexport interface FakePluginHost extends PluginHost {\n /** Every `host.fetch` call so far, in call order. */\n readonly calls: RecordedFetchCall[];\n /** Set what `host.remainingMs()` reports, for testing budget shedding. */\n seedRemainingMs(ms: number): void;\n /** Push one scripted response onto the back of the reply queue. */\n queueResponse(response: FakeResponseInit): void;\n /** Replace the fetch handler outright; overrides the queue while set. */\n setFetchImpl(impl: (url: string, init?: HostFetchInit) => Promise<Response>): void;\n /** Seed the value `host.config.get()` resolves to. */\n seedConfig(config: Record<string, unknown>): void;\n /** Seed a value `host.secrets.get(key)` resolves to. */\n seedSecret(key: string, value: string): void;\n /** Seed a storage entry directly, bypassing `host.storage.set`. */\n seedStorage(key: string, value: unknown): void;\n /** Read a storage entry directly, bypassing `host.storage.get`. */\n getStorageEntry(key: string): unknown;\n /** All storage keys currently set, unfiltered. */\n storageKeys(): string[];\n /** Seed the oauth vault directly, bypassing `host.oauth.saveTokens`. */\n seedTokens(tokens: Record<string, string>): void;\n /** Read the oauth vault directly, bypassing `host.oauth.getTokens`. */\n getVaultTokens(): Record<string, string> | undefined;\n /** Set what `host.trackFetcher.serve()` answers with; `undefined` means \"this station has no fetcher\". */\n seedFetchedTrack(stream: ProviderStream | undefined): void;\n /**\n * Set what `host.trackFetcher.playlistTracks()` answers with. `undefined` means \"this station\n * has no fetcher\"; pass an `Error` to make it throw, which is the fetcher having tried and\n * failed and is a different case for a plugin to handle.\n */\n seedFetchedPlaylist(tracks: ProviderTrack[] | Error | undefined): void;\n /** Every socket `host.socket` opened, in order, closed ones included. */\n readonly sockets: FakePluginSocket[];\n /** Make every later `host.socket` reject with `error`; `undefined` lets them open again. */\n refuseSockets(error: Error | undefined): void;\n /** Every connection `host.tls` opened, in order, closed ones included. */\n readonly tlsSockets: FakePluginTlsSocket[];\n /** Make every later `host.tls` reject with `error`; `undefined` lets them open again. */\n refuseTls(error: Error | undefined): void;\n /**\n * Called with each connection as `host.tls` opens it, before the plugin sees it, so a test can\n * script the device's answers to whatever the plugin writes.\n */\n onTlsOpen(listener: ((socket: FakePluginTlsSocket) => void) | undefined): void;\n /**\n * What `host.discover` answers from now on: a fixed list, or one worked out per query. Nothing\n * is found until a test says otherwise, which is what a station on a bridge network sees.\n */\n seedDiscovery(found: DiscoveredService[] | ((query: DiscoveryQuery) => DiscoveredService[])): void;\n}\n\n/**\n * What `host.remainingMs()` reports unless a test says otherwise: what a live\n * call reads on its first line. The host's default per-call deadline is 8s, and\n * the clock has already been running for a few milliseconds by the time plugin\n * code asks, so a live call never sees the whole 8s. A plugin that refuses to\n * start unless a full request timeout is left therefore never starts at all,\n * and a default above the real deadline hid exactly that: every test passed\n * while every live call returned nothing.\n */\nconst DEFAULT_REMAINING_MS = 8_000 - 5;\n\n/**\n * What a test says a scripted reply should be.\n *\n * Not `ResponseInit`, because `url` is not on it: `host.fetch` reports the last\n * hop of the redirect chain there, and a `Response` built by hand has an empty\n * one unless it is defined in.\n */\nexport interface FakeResponseInit {\n status?: number;\n statusText?: string;\n headers?: Record<string, string>;\n /**\n * Text for a JSON or error reply, bytes for a binary one.\n *\n * `Uint8Array<ArrayBuffer>` rather than a bare `Uint8Array`: the DOM lib's\n * `BodyInit` accepts a view over a real `ArrayBuffer`, and the unparameterized\n * form widens to `ArrayBufferLike`, which includes `SharedArrayBuffer` and is\n * not something `Response` will take. `new Uint8Array([...])` already has the\n * narrow type, so no test has to say so.\n */\n body?: string | Uint8Array<ArrayBuffer>;\n url?: string;\n}\n\n/** Statuses whose `Response` must carry a null body, or the constructor throws. */\nconst NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);\n\n/** Builds a default 200 `Response`, overridable field by field. */\nexport function fakeHostFetchResponse(init: FakeResponseInit = {}): Response {\n const status = init.status ?? 200;\n\n const response = new Response(NULL_BODY_STATUSES.has(status) ? null : (init.body ?? ''), {\n status,\n statusText: init.statusText ?? 'OK',\n headers: init.headers ?? { 'content-type': 'application/json' },\n });\n\n // Read-only on a constructed response, and part of what the host promises.\n Object.defineProperty(response, 'url', { value: init.url ?? 'https://example.test/' });\n\n return response;\n}\n\n/** What a {@link FakeRoute} answers: a status (200 when left out) and a body, sent as JSON unless it is already text. */\nexport interface FakeReply {\n status?: number;\n body: unknown;\n}\n\n/** One path a {@link routedFetch} knows, answering `undefined` for a URL that is not its own. */\nexport type FakeRoute = (url: URL, init?: HostFetchInit) => FakeReply | undefined;\n\n/**\n * A `setFetchImpl` that answers by route, for a plugin test that talks to several paths.\n *\n * The first route that answers wins. Every unrouted call is a 500, so a test that forgot a route\n * fails loudly rather than reading an empty answer. Three provider plugins wrote this same\n * dispatcher into their own tests before it lived here.\n *\n * ```ts\n * const users: FakeRoute = url => (url.pathname === '/Users' ? { body: [{ Name: 'station', Id: 'u1' }] } : undefined);\n * host.setFetchImpl(routedFetch([users, ...routes]));\n * ```\n */\nexport function routedFetch(routes: readonly FakeRoute[]): (url: string, init?: HostFetchInit) => Promise<Response> {\n return async (raw, init) => {\n const url = new URL(raw);\n let reply: FakeReply = { status: 500, body: 'unrouted' };\n for (const route of routes) {\n const found = route(url, init);\n if (found !== undefined) {\n reply = found;\n break;\n }\n }\n\n return fakeHostFetchResponse({\n status: reply.status,\n body: typeof reply.body === 'string' ? reply.body : JSON.stringify(reply.body),\n url: raw,\n });\n };\n}\n\n/** A socket that is open until either end closes it. Exported for a test that wants one on its own. */\nexport function createFakePluginSocket(url: string): FakePluginSocket {\n const messageListeners: ((text: string) => void)[] = [];\n const closeListeners: ((code?: number, reason?: string) => void)[] = [];\n const sent: string[] = [];\n let closed = false;\n\n const shut = (code: number | undefined, reason: string | undefined): void => {\n if (closed) return;\n closed = true;\n for (const listener of closeListeners) listener(code, reason);\n };\n\n return {\n url,\n sent,\n get closed() {\n return closed;\n },\n send: vi.fn((text: string) => {\n if (!closed) sent.push(text);\n }),\n close: vi.fn((code?: number, reason?: string) => shut(code ?? 1000, reason)),\n onMessage: listener => void messageListeners.push(listener),\n onClose: listener => void closeListeners.push(listener),\n sentJson: () => sent.map(text => JSON.parse(text) as unknown),\n receive(text) {\n if (closed) throw new Error(`fake plugin socket: ${url} is closed`);\n for (const listener of messageListeners) listener(text);\n },\n receiveJson(value) {\n this.receive(JSON.stringify(value));\n },\n closeFromServer(code = 1000, reason = '') {\n shut(code, reason);\n },\n };\n}\n\n/** A TLS connection that is open until either end closes it. Exported for a test that wants one on its own. */\nexport function createFakePluginTlsSocket(url: string, options?: PluginTlsOptions): FakePluginTlsSocket {\n const dataListeners: ((bytes: Uint8Array) => void)[] = [];\n const closeListeners: ((reason?: string) => void)[] = [];\n const sent: Uint8Array[] = [];\n let closed = false;\n\n const shut = (reason: string | undefined): void => {\n if (closed) return;\n closed = true;\n for (const listener of closeListeners) listener(reason);\n };\n\n return {\n url,\n options,\n sent,\n get closed() {\n return closed;\n },\n send: vi.fn((bytes: Uint8Array) => {\n if (!closed) sent.push(bytes);\n }),\n close: vi.fn(() => shut(undefined)),\n onData: listener => void dataListeners.push(listener),\n onClose: listener => void closeListeners.push(listener),\n receive(bytes) {\n if (closed) throw new Error(`fake plugin tls socket: ${url} is closed`);\n for (const listener of dataListeners) listener(bytes);\n },\n closeFromServer(reason) {\n shut(reason);\n },\n };\n}\n\nexport function createFakePluginHost(): FakePluginHost {\n const calls: RecordedFetchCall[] = [];\n const queue: Response[] = [];\n let customImpl: ((url: string, init?: HostFetchInit) => Promise<Response>) | undefined;\n\n const storageData = new Map<string, unknown>();\n let configData: Record<string, unknown> = {};\n const secretsData = new Map<string, string>();\n let tokens: Record<string, string> | undefined;\n let remainingMs = DEFAULT_REMAINING_MS;\n let fetchedTrack: ProviderStream | undefined = { url: 'http://127.0.0.1:3679/track/song-1?t=signed', expiresAt: 1_893_456_000_000 };\n // Nothing by default: a plugin should ask its own API first, and a test that means to exercise\n // the fetcher says so.\n let fetchedPlaylist: ProviderTrack[] | Error | undefined;\n const sockets: FakePluginSocket[] = [];\n let socketRefusal: Error | undefined;\n const tlsSockets: FakePluginTlsSocket[] = [];\n let tlsRefusal: Error | undefined;\n let tlsOpened: ((socket: FakePluginTlsSocket) => void) | undefined;\n let discovered: (query: DiscoveryQuery) => DiscoveredService[] = () => [];\n\n const fetchImpl = vi.fn(async (url: string, init?: HostFetchInit): Promise<Response> => {\n calls.push({ url, method: init?.method, headers: init?.headers, body: init?.body });\n if (customImpl) return customImpl(url, init);\n const next = queue.shift();\n if (!next) throw new Error(`fake plugin host: no response queued for ${init?.method ?? 'GET'} ${url}`);\n return next;\n });\n\n const host: FakePluginHost = {\n logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },\n fetch: fetchImpl,\n socket: vi.fn(async (url: string) => {\n if (socketRefusal !== undefined) throw socketRefusal;\n const socket = createFakePluginSocket(url);\n sockets.push(socket);\n return socket;\n }),\n tls: vi.fn(async (url: string, options?: PluginTlsOptions) => {\n if (tlsRefusal !== undefined) throw tlsRefusal;\n const socket = createFakePluginTlsSocket(url, options);\n tlsSockets.push(socket);\n tlsOpened?.(socket);\n return socket;\n }),\n discover: vi.fn(async (query: DiscoveryQuery) => discovered(query)),\n // Never aborts: these tests are about what a plugin does with a reply,\n // not about being cancelled half way through one.\n signal: new AbortController().signal,\n remainingMs: vi.fn(() => remainingMs),\n storage: {\n get: vi.fn(async (key: string) => storageData.get(key)),\n set: vi.fn(async (key: string, value: unknown) => {\n storageData.set(key, value);\n }),\n delete: vi.fn(async (key: string) => {\n storageData.delete(key);\n }),\n list: vi.fn(async (prefix?: string) => [...storageData.keys()].filter(key => !prefix || key.startsWith(prefix))),\n },\n secrets: { get: vi.fn(async (key: string) => secretsData.get(key)) },\n config: { get: vi.fn(async () => configData) },\n oauth: {\n getRedirectUri: vi.fn(async () => 'https://example.test/callback'),\n saveTokens: vi.fn(async (next: Record<string, string>) => {\n tokens = next;\n }),\n getTokens: vi.fn(async () => tokens),\n },\n events: { emit: vi.fn() },\n trackFetcher: {\n serve: vi.fn(async () => fetchedTrack),\n // Answers the same canned stream as `serve`: a plugin under test cares that it asked the\n // host for audio and passed the answer through, not which helper the station happens to run\n // behind it. `fetchedTrack` is what a test sets to say \"the station has a fetcher\" or, as\n // undefined, \"it has not got one\".\n servePlayer: vi.fn(async () => fetchedTrack),\n playlistTracks: vi.fn(async () => {\n if (fetchedPlaylist instanceof Error) throw fetchedPlaylist;\n return fetchedPlaylist;\n }),\n },\n calls,\n sockets,\n refuseSockets(error) {\n socketRefusal = error;\n },\n tlsSockets,\n refuseTls(error) {\n tlsRefusal = error;\n },\n onTlsOpen(listener) {\n tlsOpened = listener;\n },\n seedDiscovery(found) {\n discovered = typeof found === 'function' ? found : () => found;\n },\n seedRemainingMs(ms) {\n remainingMs = ms;\n },\n queueResponse(response: FakeResponseInit) {\n queue.push(fakeHostFetchResponse(response));\n },\n setFetchImpl(impl) {\n customImpl = impl;\n },\n seedConfig(config) {\n configData = config;\n },\n seedSecret(key, value) {\n secretsData.set(key, value);\n },\n seedStorage(key, value) {\n storageData.set(key, value);\n },\n getStorageEntry(key) {\n return storageData.get(key);\n },\n storageKeys() {\n return [...storageData.keys()];\n },\n seedTokens(next) {\n tokens = next;\n },\n getVaultTokens() {\n return tokens;\n },\n seedFetchedTrack(stream) {\n fetchedTrack = stream;\n },\n seedFetchedPlaylist(tracks) {\n fetchedPlaylist = tracks;\n },\n };\n\n return host;\n}\n"],"mapp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iBAAAA;AACI,aAAOjE;IACX;IACAkE,iBAAiBC,QAAM;AACnBjE,qBAAeiE;IACnB;IACAC,oBAAoBC,QAAM;AACtBjE,wBAAkBiE;IACtB;EACJ;AAEA,SAAOtD;AACX;AAxIgBvB;","names":["vi","DEFAULT_REMAINING_MS","NULL_BODY_STATUSES","Set","fakeHostFetchResponse","init","status","response","Response","has","body","statusText","headers","Object","defineProperty","value","url","routedFetch","routes","raw","URL","reply","route","found","undefined","JSON","stringify","createFakePluginSocket","messageListeners","closeListeners","sent","closed","shut","code","reason","listener","send","vi","fn","text","push","close","onMessage","onClose","sentJson","map","parse","receive","Error","receiveJson","closeFromServer","createFakePluginTlsSocket","options","dataListeners","bytes","onData","createFakePluginHost","calls","queue","customImpl","storageData","Map","configData","secretsData","tokens","remainingMs","fetchedTrack","expiresAt","fetchedPlaylist","sockets","socketRefusal","tlsSockets","tlsRefusal","tlsOpened","discovered","fetchImpl","method","next","shift","host","logger","debug","info","warn","error","fetch","socket","tls","discover","query","signal","AbortController","storage","get","key","set","delete","list","prefix","keys","filter","startsWith","secrets","config","oauth","getRedirectUri","saveTokens","getTokens","events","emit","trackFetcher","serve","servePlayer","playlistTracks","refuseSockets","refuseTls","onTlsOpen","seedDiscovery","seedRemainingMs","ms","queueResponse","setFetchImpl","impl","seedConfig","seedSecret","seedStorage","getStorageEntry","storageKeys","seedTokens","getVaultTokens","seedFetchedTrack","stream","seedFetchedPlaylist","tracks"]}
|
package/package.json
CHANGED