@eserstack/noskills-client 0.0.0-bootstrap.0 → 5.0.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.
- package/LICENSE +13 -0
- package/README.md +286 -0
- package/dist/attach.d.ts +85 -0
- package/dist/attach.js +234 -0
- package/dist/cert.d.ts +48 -0
- package/dist/cert.js +197 -0
- package/dist/client.d.ts +85 -0
- package/dist/client.js +205 -0
- package/dist/deadline.d.ts +13 -0
- package/dist/deadline.js +62 -0
- package/dist/errors.d.ts +43 -0
- package/dist/errors.js +61 -0
- package/dist/mod.d.ts +16 -0
- package/dist/mod.js +5 -0
- package/dist/types.d.ts +317 -0
- package/dist/types.js +2 -0
- package/package.json +51 -1
package/dist/cert.js
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
import * as deadline from "./deadline.js";
|
|
3
|
+
import * as errors from "./errors.js";
|
|
4
|
+
const DB_NAME = "noskills-cert";
|
|
5
|
+
const DB_STORE = "fingerprints";
|
|
6
|
+
const CERT_FINGERPRINT_TIMEOUT_MS = 10_000;
|
|
7
|
+
const SHA256_BYTES = 32;
|
|
8
|
+
const FINGERPRINT_FORMAT = "64 hex digits, optionally separated by colons or spaces";
|
|
9
|
+
// =============================================================================
|
|
10
|
+
// Fingerprint values
|
|
11
|
+
// =============================================================================
|
|
12
|
+
/**
|
|
13
|
+
* The cache key for a daemon: the origin of its base URL, so two daemons on
|
|
14
|
+
* one machine, or one host on two ports, keep their own pins.
|
|
15
|
+
*/
|
|
16
|
+
function cacheKey(baseUrl) {
|
|
17
|
+
let url;
|
|
18
|
+
try {
|
|
19
|
+
url = new URL(baseUrl);
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
throw new TypeError(`baseUrl "${baseUrl}" is not an absolute URL; expected one like https://localhost:4433`, { cause: error });
|
|
23
|
+
}
|
|
24
|
+
return url.origin;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Reads a SHA-256 fingerprint written as hex, in the compact form or the
|
|
28
|
+
* colon-separated display form. Returns null for anything that is not 32
|
|
29
|
+
* bytes of hex.
|
|
30
|
+
*/
|
|
31
|
+
function parseFingerprint(hex) {
|
|
32
|
+
const clean = hex.replace(/[:\s]/g, "");
|
|
33
|
+
if (!/^[0-9a-fA-F]{64}$/.test(clean)) {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
return Uint8Array.from({ length: SHA256_BYTES }, (_, index) => Number.parseInt(clean.slice(index * 2, index * 2 + 2), 16));
|
|
37
|
+
}
|
|
38
|
+
function toHex(bytes) {
|
|
39
|
+
return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
40
|
+
}
|
|
41
|
+
// =============================================================================
|
|
42
|
+
// IndexedDB helpers
|
|
43
|
+
// =============================================================================
|
|
44
|
+
function openCertDB() {
|
|
45
|
+
// Typed as always present, but undefined outside browsers.
|
|
46
|
+
const factory = globalThis.indexedDB;
|
|
47
|
+
if (factory === undefined) {
|
|
48
|
+
return Promise.reject(new Error(`open IndexedDB database "${DB_NAME}": IndexedDB is not available in this runtime; pin the certificate with certHashes in NoskillsClientConfig instead`));
|
|
49
|
+
}
|
|
50
|
+
return new Promise((resolve, reject) => {
|
|
51
|
+
const req = factory.open(DB_NAME, 1);
|
|
52
|
+
req.onupgradeneeded = () => req.result.createObjectStore(DB_STORE);
|
|
53
|
+
req.onsuccess = () => resolve(req.result);
|
|
54
|
+
req.onerror = () => reject(req.error);
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Persist the hex fingerprint of the daemon at `baseUrl` to IndexedDB, in
|
|
59
|
+
* place of the one stored for the same origin.
|
|
60
|
+
*
|
|
61
|
+
* @throws {RangeError} When `fingerprint` is not a SHA-256 fingerprint.
|
|
62
|
+
*/
|
|
63
|
+
export async function storeCertFingerprint(baseUrl, fingerprint) {
|
|
64
|
+
const key = cacheKey(baseUrl);
|
|
65
|
+
const bytes = parseFingerprint(fingerprint);
|
|
66
|
+
if (bytes === null) {
|
|
67
|
+
throw new RangeError(`store certificate fingerprint for ${key}: the value is not a SHA-256 fingerprint; expected ${FINGERPRINT_FORMAT}`);
|
|
68
|
+
}
|
|
69
|
+
const db = await openCertDB();
|
|
70
|
+
try {
|
|
71
|
+
await new Promise((resolve, reject) => {
|
|
72
|
+
const tx = db.transaction(DB_STORE, "readwrite");
|
|
73
|
+
const req = tx.objectStore(DB_STORE).put(toHex(bytes), key);
|
|
74
|
+
req.onsuccess = () => resolve();
|
|
75
|
+
req.onerror = () => reject(req.error);
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
db.close();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Load the hex fingerprint stored for the daemon at `baseUrl` from IndexedDB.
|
|
84
|
+
* Returns null if that origin has none.
|
|
85
|
+
*/
|
|
86
|
+
export async function loadCertFingerprint(baseUrl) {
|
|
87
|
+
const key = cacheKey(baseUrl);
|
|
88
|
+
const db = await openCertDB();
|
|
89
|
+
try {
|
|
90
|
+
const result = await new Promise((resolve, reject) => {
|
|
91
|
+
const tx = db.transaction(DB_STORE, "readonly");
|
|
92
|
+
const req = tx.objectStore(DB_STORE).get(key);
|
|
93
|
+
req.onsuccess = () => resolve(req.result);
|
|
94
|
+
req.onerror = () => reject(req.error);
|
|
95
|
+
});
|
|
96
|
+
return typeof result === "string" ? result : null;
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
db.close();
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
// =============================================================================
|
|
103
|
+
// Fetch from daemon
|
|
104
|
+
// =============================================================================
|
|
105
|
+
/**
|
|
106
|
+
* Fetch the current daemon TLS fingerprint from GET /api/cert-fingerprint,
|
|
107
|
+
* store it in IndexedDB and return it as an ArrayBuffer for WebTransport.
|
|
108
|
+
*
|
|
109
|
+
* Returns null when the daemon has no fingerprint endpoint (a 404): its
|
|
110
|
+
* certificate is one the operating system trusts, such as mkcert's, and there
|
|
111
|
+
* is nothing to pin. The request waits 10 000 ms unless `options.timeoutMs`
|
|
112
|
+
* says otherwise.
|
|
113
|
+
*
|
|
114
|
+
* @throws {CertFingerprintError} When the request fails, the endpoint answers
|
|
115
|
+
* with another error status, or the answer is not a SHA-256 fingerprint.
|
|
116
|
+
* @throws {NoskillsTimeoutError} When the daemon does not answer in time.
|
|
117
|
+
*/
|
|
118
|
+
export async function fetchAndPinCertFingerprint(baseUrl, options = {}) {
|
|
119
|
+
cacheKey(baseUrl); // rejects a malformed baseUrl before any request
|
|
120
|
+
const url = `${baseUrl.replace(/\/$/, "")}/api/cert-fingerprint`;
|
|
121
|
+
const answer = await deadline.withDeadline("GET /api/cert-fingerprint", options.timeoutMs ?? CERT_FINGERPRINT_TIMEOUT_MS, options.signal, (signal) => fetchFingerprintAnswer(url, signal));
|
|
122
|
+
if (answer === null) {
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
const fields = answer.body instanceof Object
|
|
126
|
+
? answer.body
|
|
127
|
+
: {};
|
|
128
|
+
if (fields.algorithm !== undefined && fields.algorithm !== "sha-256") {
|
|
129
|
+
throw new errors.CertFingerprintError(url, null, `the fingerprint uses algorithm ${JSON.stringify(fields.algorithm)}; only sha-256 can be pinned`);
|
|
130
|
+
}
|
|
131
|
+
const bytes = typeof fields.fingerprint === "string"
|
|
132
|
+
? parseFingerprint(fields.fingerprint)
|
|
133
|
+
: null;
|
|
134
|
+
if (bytes === null) {
|
|
135
|
+
throw new errors.CertFingerprintError(url, null, `the answer has no SHA-256 fingerprint; expected a "fingerprint" field of ${FINGERPRINT_FORMAT}`);
|
|
136
|
+
}
|
|
137
|
+
// The cache only saves a fetch on the next attach, so a failed write (no
|
|
138
|
+
// IndexedDB outside browsers) does not fail this call.
|
|
139
|
+
await storeCertFingerprint(baseUrl, toHex(bytes)).catch(() => { });
|
|
140
|
+
return bytes.buffer;
|
|
141
|
+
}
|
|
142
|
+
/** The fingerprint endpoint's parsed JSON body, or null for a 404. */
|
|
143
|
+
async function fetchFingerprintAnswer(url, signal) {
|
|
144
|
+
let response;
|
|
145
|
+
try {
|
|
146
|
+
response = await fetch(url, { signal });
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
if (signal.aborted) {
|
|
150
|
+
throw error; // a timeout or the caller's abort, reported by withDeadline
|
|
151
|
+
}
|
|
152
|
+
throw new errors.CertFingerprintError(url, null, "the request failed; check that the daemon is running at this address", { cause: error });
|
|
153
|
+
}
|
|
154
|
+
if (response.status === 404) {
|
|
155
|
+
await response.body?.cancel();
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
if (!response.ok) {
|
|
159
|
+
await response.body?.cancel();
|
|
160
|
+
throw new errors.CertFingerprintError(url, response.status, `the endpoint answered HTTP ${response.status}; check the daemon's log`);
|
|
161
|
+
}
|
|
162
|
+
try {
|
|
163
|
+
return { body: await response.json() };
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
if (signal.aborted) {
|
|
167
|
+
throw error;
|
|
168
|
+
}
|
|
169
|
+
throw new errors.CertFingerprintError(url, null, "the answer is not JSON; check that baseUrl points at a noskills daemon", { cause: error });
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Return the fingerprint cached for the daemon at `baseUrl`, or fetch it with
|
|
174
|
+
* fetchAndPinCertFingerprint when there is none or IndexedDB is unavailable.
|
|
175
|
+
* Use this on reconnect to avoid a round-trip when the cert is still valid;
|
|
176
|
+
* attachSession refetches by itself when a cached pin stops matching.
|
|
177
|
+
*/
|
|
178
|
+
export async function getCertFingerprint(baseUrl, options = {}) {
|
|
179
|
+
// A malformed baseUrl throws here, so the catch below sees IndexedDB
|
|
180
|
+
// failures only.
|
|
181
|
+
cacheKey(baseUrl);
|
|
182
|
+
let cached;
|
|
183
|
+
try {
|
|
184
|
+
cached = await loadCertFingerprint(baseUrl);
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
// IndexedDB is unavailable (non-browser runtime or private browsing), so
|
|
188
|
+
// fetch the fingerprint live.
|
|
189
|
+
cached = null;
|
|
190
|
+
}
|
|
191
|
+
// An entry that does not parse counts as none; the fetch replaces it.
|
|
192
|
+
const bytes = cached === null ? null : parseFingerprint(cached);
|
|
193
|
+
if (bytes !== null) {
|
|
194
|
+
return bytes.buffer;
|
|
195
|
+
}
|
|
196
|
+
return await fetchAndPinCertFingerprint(baseUrl, options);
|
|
197
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* REST client for the noskills-server daemon.
|
|
3
|
+
*
|
|
4
|
+
* Uses the browser's native fetch (HTTP/3 ALPN is negotiated automatically by
|
|
5
|
+
* the UA when the daemon advertises h3). The daemon listens on HTTP/3 only, so
|
|
6
|
+
* outside a browser supply a fetchFn that speaks HTTP/3.
|
|
7
|
+
*
|
|
8
|
+
* Every call has a time limit (10 000 ms unless `timeoutMs` says otherwise;
|
|
9
|
+
* 300 000 ms for registering a git URL) and takes an optional AbortSignal.
|
|
10
|
+
*
|
|
11
|
+
* @module
|
|
12
|
+
*/
|
|
13
|
+
import type { CallOptions, CreateSessionRequest, CreateSessionResponse, LoginResponse, NoskillsClientConfig, Project, RegisterProjectRequest, Session } from "./types.ts";
|
|
14
|
+
type FetchFn = typeof globalThis.fetch;
|
|
15
|
+
/**
|
|
16
|
+
* REST client for one daemon. Every method takes an optional
|
|
17
|
+
* {@link CallOptions} as its last argument, to cancel the call or change its
|
|
18
|
+
* time limit.
|
|
19
|
+
*/
|
|
20
|
+
export declare class NoskillsClient {
|
|
21
|
+
#private;
|
|
22
|
+
/** Uses `fetchFn` in place of the global fetch when given. */
|
|
23
|
+
constructor(config: NoskillsClientConfig, fetchFn?: FetchFn);
|
|
24
|
+
/** Sets the daemon's PIN on first run (`POST /auth/setup`). */
|
|
25
|
+
setup(pin: string, options?: CallOptions): Promise<void>;
|
|
26
|
+
/** Logs in with the PIN and keeps the token for later calls. */
|
|
27
|
+
login(pin: string, options?: CallOptions): Promise<LoginResponse>;
|
|
28
|
+
/** Ends the token's session on the daemon, then forgets the token. */
|
|
29
|
+
logout(options?: CallOptions): Promise<void>;
|
|
30
|
+
/** Inject a token obtained externally (e.g. from localStorage). */
|
|
31
|
+
setToken(token: string): void;
|
|
32
|
+
/** The token later calls send, if any. */
|
|
33
|
+
get token(): string | undefined;
|
|
34
|
+
/** Reads the daemon's version and uptime (`GET /api/health`). */
|
|
35
|
+
health(options?: CallOptions): Promise<{
|
|
36
|
+
version: string;
|
|
37
|
+
uptime: number;
|
|
38
|
+
}>;
|
|
39
|
+
/** Lists the registered projects (`GET /api/projects`). */
|
|
40
|
+
listProjects(options?: CallOptions): Promise<Project[]>;
|
|
41
|
+
/**
|
|
42
|
+
* Registers a local path, or clones a git URL into the daemon's data
|
|
43
|
+
* directory. A git URL waits 300 000 ms by default, because the daemon
|
|
44
|
+
* answers only after the clone; the daemon uses `path` when both are set.
|
|
45
|
+
*/
|
|
46
|
+
registerProject(req: RegisterProjectRequest, options?: CallOptions): Promise<Project>;
|
|
47
|
+
/** Removes a project from the daemon's registry. */
|
|
48
|
+
deleteProject(slug: string, options?: CallOptions): Promise<void>;
|
|
49
|
+
/** Lists a project's sessions. */
|
|
50
|
+
listSessions(slug: string, options?: CallOptions): Promise<Session[]>;
|
|
51
|
+
/** Starts a session in a project, or resumes one with `resumeFrom`. */
|
|
52
|
+
createSession(slug: string, req?: CreateSessionRequest, options?: CallOptions): Promise<CreateSessionResponse>;
|
|
53
|
+
/** Forks a session, at a message when `atMessageId` is given. */
|
|
54
|
+
forkSession(slug: string, sessionId: string, atMessageId?: string, label?: string, options?: CallOptions): Promise<CreateSessionResponse>;
|
|
55
|
+
/** Reads a session's parent and children. */
|
|
56
|
+
getSessionLineage(slug: string, sessionId: string, options?: CallOptions): Promise<{
|
|
57
|
+
sessionId: string;
|
|
58
|
+
parent?: string;
|
|
59
|
+
children: string[];
|
|
60
|
+
}>;
|
|
61
|
+
/** Reads the daemon's VAPID public key for Web Push; needs no token. */
|
|
62
|
+
getVapidPublicKey(options?: CallOptions): Promise<string>;
|
|
63
|
+
/** Subscribes a browser to Web Push, for the sessions in `sessionFilter`. */
|
|
64
|
+
subscribePush(subscription: PushSubscriptionJSON, sessionFilter?: string[], options?: CallOptions): Promise<{
|
|
65
|
+
subscriptionId: string;
|
|
66
|
+
}>;
|
|
67
|
+
/** Removes a Web Push subscription. */
|
|
68
|
+
unsubscribePush(subscriptionId: string, options?: CallOptions): Promise<void>;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Factory. Parallel to createHttpClient / createWebTransportClient pattern.
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* ```ts
|
|
75
|
+
* import * as noskillsClient from "@eserstack/noskills-client";
|
|
76
|
+
*
|
|
77
|
+
* const client = noskillsClient.createNoskillsClient({
|
|
78
|
+
* baseUrl: "https://localhost:4433",
|
|
79
|
+
* });
|
|
80
|
+
* await client.login("your_pin");
|
|
81
|
+
* const { sessionId } = await client.createSession("your_project_slug");
|
|
82
|
+
* ```
|
|
83
|
+
*/
|
|
84
|
+
export declare function createNoskillsClient(config: NoskillsClientConfig, fetchFn?: typeof globalThis.fetch): NoskillsClient;
|
|
85
|
+
export {};
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
import * as deadline from "./deadline.js";
|
|
3
|
+
import * as errors from "./errors.js";
|
|
4
|
+
const REQUEST_TIMEOUT_MS = 10_000;
|
|
5
|
+
/** The daemon clones the repository before it answers a git registration. */
|
|
6
|
+
const GIT_CLONE_TIMEOUT_MS = 300_000;
|
|
7
|
+
function buildHeaders(token) {
|
|
8
|
+
const headers = {
|
|
9
|
+
"content-type": "application/json",
|
|
10
|
+
"protocol-version": "1",
|
|
11
|
+
};
|
|
12
|
+
if (token !== undefined && token !== "") {
|
|
13
|
+
headers["authorization"] = `Bearer ${token}`;
|
|
14
|
+
}
|
|
15
|
+
return headers;
|
|
16
|
+
}
|
|
17
|
+
const readJson = async (response) => (await response.json());
|
|
18
|
+
const discardBody = async (response) => {
|
|
19
|
+
await response.body?.cancel();
|
|
20
|
+
};
|
|
21
|
+
// =============================================================================
|
|
22
|
+
// NoskillsClient
|
|
23
|
+
// =============================================================================
|
|
24
|
+
/**
|
|
25
|
+
* REST client for one daemon. Every method takes an optional
|
|
26
|
+
* {@link CallOptions} as its last argument, to cancel the call or change its
|
|
27
|
+
* time limit.
|
|
28
|
+
*/
|
|
29
|
+
export class NoskillsClient {
|
|
30
|
+
#base;
|
|
31
|
+
#fetch;
|
|
32
|
+
#timeoutMs;
|
|
33
|
+
#token;
|
|
34
|
+
/** Uses `fetchFn` in place of the global fetch when given. */
|
|
35
|
+
constructor(config, fetchFn) {
|
|
36
|
+
this.#base = config.baseUrl.replace(/\/$/, "");
|
|
37
|
+
this.#token = config.token;
|
|
38
|
+
this.#timeoutMs = config.timeoutMs ?? REQUEST_TIMEOUT_MS;
|
|
39
|
+
this.#fetch = fetchFn ?? globalThis.fetch.bind(globalThis);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Sends one call and reads its response, within the call's time limit and
|
|
43
|
+
* the caller's signal. An error status throws `NoskillsResponseError`.
|
|
44
|
+
*/
|
|
45
|
+
#send(call, options, read, defaultTimeoutMs) {
|
|
46
|
+
return deadline.withDeadline(`${call.method} ${call.path}`, options?.timeoutMs ?? defaultTimeoutMs, options?.signal, async (signal) => {
|
|
47
|
+
const response = await this.#fetch(`${this.#base}${call.path}`, {
|
|
48
|
+
method: call.method,
|
|
49
|
+
headers: buildHeaders(call.token),
|
|
50
|
+
body: call.body === undefined ? undefined : JSON.stringify(call.body),
|
|
51
|
+
signal,
|
|
52
|
+
});
|
|
53
|
+
if (!response.ok) {
|
|
54
|
+
const detail = await response.text().catch(() => response.statusText);
|
|
55
|
+
throw new errors.NoskillsResponseError(call.method, call.path, response.status, detail);
|
|
56
|
+
}
|
|
57
|
+
return await read(response);
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
#json(call, options) {
|
|
61
|
+
return this.#send(call, options, readJson, this.#timeoutMs);
|
|
62
|
+
}
|
|
63
|
+
// ---------------------------------------------------------------------------
|
|
64
|
+
// Auth
|
|
65
|
+
// ---------------------------------------------------------------------------
|
|
66
|
+
/** Sets the daemon's PIN on first run (`POST /auth/setup`). */
|
|
67
|
+
async setup(pin, options) {
|
|
68
|
+
await this.#json({ method: "POST", path: "/auth/setup", body: { pin } }, options);
|
|
69
|
+
}
|
|
70
|
+
/** Logs in with the PIN and keeps the token for later calls. */
|
|
71
|
+
async login(pin, options) {
|
|
72
|
+
const req = { pin };
|
|
73
|
+
const resp = await this.#json({ method: "POST", path: "/auth/login", body: req }, options);
|
|
74
|
+
this.#token = resp.token;
|
|
75
|
+
return resp;
|
|
76
|
+
}
|
|
77
|
+
/** Ends the token's session on the daemon, then forgets the token. */
|
|
78
|
+
async logout(options) {
|
|
79
|
+
await this.#json({ method: "POST", path: "/auth/logout", body: {}, token: this.#token }, options);
|
|
80
|
+
this.#token = undefined;
|
|
81
|
+
}
|
|
82
|
+
/** Inject a token obtained externally (e.g. from localStorage). */
|
|
83
|
+
setToken(token) {
|
|
84
|
+
this.#token = token;
|
|
85
|
+
}
|
|
86
|
+
/** The token later calls send, if any. */
|
|
87
|
+
get token() {
|
|
88
|
+
return this.#token;
|
|
89
|
+
}
|
|
90
|
+
// ---------------------------------------------------------------------------
|
|
91
|
+
// Health
|
|
92
|
+
// ---------------------------------------------------------------------------
|
|
93
|
+
/** Reads the daemon's version and uptime (`GET /api/health`). */
|
|
94
|
+
health(options) {
|
|
95
|
+
return this.#json({ method: "GET", path: "/api/health", token: this.#token }, options);
|
|
96
|
+
}
|
|
97
|
+
// ---------------------------------------------------------------------------
|
|
98
|
+
// Projects
|
|
99
|
+
// ---------------------------------------------------------------------------
|
|
100
|
+
/** Lists the registered projects (`GET /api/projects`). */
|
|
101
|
+
listProjects(options) {
|
|
102
|
+
return this.#json({ method: "GET", path: "/api/projects", token: this.#token }, options);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Registers a local path, or clones a git URL into the daemon's data
|
|
106
|
+
* directory. A git URL waits 300 000 ms by default, because the daemon
|
|
107
|
+
* answers only after the clone; the daemon uses `path` when both are set.
|
|
108
|
+
*/
|
|
109
|
+
registerProject(req, options) {
|
|
110
|
+
const clones = (req.path === undefined || req.path === "") &&
|
|
111
|
+
req.git !== undefined &&
|
|
112
|
+
req.git !== "";
|
|
113
|
+
return this.#send({ method: "POST", path: "/api/projects", body: req, token: this.#token }, options, readJson, clones ? GIT_CLONE_TIMEOUT_MS : this.#timeoutMs);
|
|
114
|
+
}
|
|
115
|
+
/** Removes a project from the daemon's registry. */
|
|
116
|
+
deleteProject(slug, options) {
|
|
117
|
+
return this.#send({
|
|
118
|
+
method: "DELETE",
|
|
119
|
+
path: `/api/projects/${encodeURIComponent(slug)}`,
|
|
120
|
+
token: this.#token,
|
|
121
|
+
}, options, discardBody, this.#timeoutMs);
|
|
122
|
+
}
|
|
123
|
+
// ---------------------------------------------------------------------------
|
|
124
|
+
// Sessions
|
|
125
|
+
// ---------------------------------------------------------------------------
|
|
126
|
+
/** Lists a project's sessions. */
|
|
127
|
+
listSessions(slug, options) {
|
|
128
|
+
return this.#json({
|
|
129
|
+
method: "GET",
|
|
130
|
+
path: `/api/projects/${encodeURIComponent(slug)}/sessions`,
|
|
131
|
+
token: this.#token,
|
|
132
|
+
}, options);
|
|
133
|
+
}
|
|
134
|
+
/** Starts a session in a project, or resumes one with `resumeFrom`. */
|
|
135
|
+
createSession(slug, req, options) {
|
|
136
|
+
return this.#json({
|
|
137
|
+
method: "POST",
|
|
138
|
+
path: `/api/projects/${encodeURIComponent(slug)}/sessions`,
|
|
139
|
+
body: req ?? {},
|
|
140
|
+
token: this.#token,
|
|
141
|
+
}, options);
|
|
142
|
+
}
|
|
143
|
+
// ---------------------------------------------------------------------------
|
|
144
|
+
// Session forking
|
|
145
|
+
// ---------------------------------------------------------------------------
|
|
146
|
+
/** Forks a session, at a message when `atMessageId` is given. */
|
|
147
|
+
forkSession(slug, sessionId, atMessageId, label, options) {
|
|
148
|
+
return this.#json({
|
|
149
|
+
method: "POST",
|
|
150
|
+
path: `/api/projects/${encodeURIComponent(slug)}/sessions/${encodeURIComponent(sessionId)}/fork`,
|
|
151
|
+
body: { at_message_id: atMessageId, label },
|
|
152
|
+
token: this.#token,
|
|
153
|
+
}, options);
|
|
154
|
+
}
|
|
155
|
+
/** Reads a session's parent and children. */
|
|
156
|
+
getSessionLineage(slug, sessionId, options) {
|
|
157
|
+
return this.#json({
|
|
158
|
+
method: "GET",
|
|
159
|
+
path: `/api/projects/${encodeURIComponent(slug)}/sessions/${encodeURIComponent(sessionId)}/lineage`,
|
|
160
|
+
token: this.#token,
|
|
161
|
+
}, options);
|
|
162
|
+
}
|
|
163
|
+
// ---------------------------------------------------------------------------
|
|
164
|
+
// Web Push subscriptions
|
|
165
|
+
// ---------------------------------------------------------------------------
|
|
166
|
+
/** Reads the daemon's VAPID public key for Web Push; needs no token. */
|
|
167
|
+
async getVapidPublicKey(options) {
|
|
168
|
+
const resp = await this.#json({ method: "GET", path: "/api/push/vapid-public-key" }, options);
|
|
169
|
+
return resp.publicKey;
|
|
170
|
+
}
|
|
171
|
+
/** Subscribes a browser to Web Push, for the sessions in `sessionFilter`. */
|
|
172
|
+
subscribePush(subscription, sessionFilter, options) {
|
|
173
|
+
return this.#json({
|
|
174
|
+
method: "POST",
|
|
175
|
+
path: "/api/push/subscribe",
|
|
176
|
+
body: { ...subscription, sessionFilter },
|
|
177
|
+
token: this.#token,
|
|
178
|
+
}, options);
|
|
179
|
+
}
|
|
180
|
+
/** Removes a Web Push subscription. */
|
|
181
|
+
unsubscribePush(subscriptionId, options) {
|
|
182
|
+
return this.#send({
|
|
183
|
+
method: "DELETE",
|
|
184
|
+
path: `/api/push/subscribe/${encodeURIComponent(subscriptionId)}`,
|
|
185
|
+
token: this.#token,
|
|
186
|
+
}, options, discardBody, this.#timeoutMs);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Factory. Parallel to createHttpClient / createWebTransportClient pattern.
|
|
191
|
+
*
|
|
192
|
+
* @example
|
|
193
|
+
* ```ts
|
|
194
|
+
* import * as noskillsClient from "@eserstack/noskills-client";
|
|
195
|
+
*
|
|
196
|
+
* const client = noskillsClient.createNoskillsClient({
|
|
197
|
+
* baseUrl: "https://localhost:4433",
|
|
198
|
+
* });
|
|
199
|
+
* await client.login("your_pin");
|
|
200
|
+
* const { sessionId } = await client.createSession("your_project_slug");
|
|
201
|
+
* ```
|
|
202
|
+
*/
|
|
203
|
+
export function createNoskillsClient(config, fetchFn) {
|
|
204
|
+
return new NoskillsClient(config, fetchFn);
|
|
205
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Settles like `pending`, or rejects with the signal's reason as soon as the
|
|
3
|
+
* signal aborts, so work that ignores the signal still cannot outlive it. A
|
|
4
|
+
* value that arrives after the abort goes to `discardLate`, which releases it.
|
|
5
|
+
*/
|
|
6
|
+
export declare function raceSignal<T>(pending: Promise<T>, signal: AbortSignal, discardLate: (value: T) => void): Promise<T>;
|
|
7
|
+
/**
|
|
8
|
+
* Runs `work` with one signal that aborts when `callerSignal` does or when
|
|
9
|
+
* `timeoutMs` passes. A failure caused by the time limit becomes a
|
|
10
|
+
* `NoskillsTimeoutError` naming `operation`; the caller's abort and every
|
|
11
|
+
* other failure propagate unchanged.
|
|
12
|
+
*/
|
|
13
|
+
export declare function withDeadline<T>(operation: string, timeoutMs: number, callerSignal: AbortSignal | undefined, work: (signal: AbortSignal) => Promise<T>, discardLate?: (value: T) => void): Promise<T>;
|
package/dist/deadline.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* Time limits and cancellation shared by the REST client, the certificate
|
|
4
|
+
* fetch and attach. Internal: not exported from the package.
|
|
5
|
+
*
|
|
6
|
+
* @module
|
|
7
|
+
*/
|
|
8
|
+
import * as errors from "./errors.js";
|
|
9
|
+
/**
|
|
10
|
+
* Settles like `pending`, or rejects with the signal's reason as soon as the
|
|
11
|
+
* signal aborts, so work that ignores the signal still cannot outlive it. A
|
|
12
|
+
* value that arrives after the abort goes to `discardLate`, which releases it.
|
|
13
|
+
*/
|
|
14
|
+
export function raceSignal(pending, signal, discardLate) {
|
|
15
|
+
return new Promise((resolve, reject) => {
|
|
16
|
+
const onAbort = () => reject(signal.reason);
|
|
17
|
+
if (signal.aborted) {
|
|
18
|
+
onAbort();
|
|
19
|
+
}
|
|
20
|
+
else {
|
|
21
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
22
|
+
}
|
|
23
|
+
pending.then((value) => {
|
|
24
|
+
signal.removeEventListener("abort", onAbort);
|
|
25
|
+
if (signal.aborted) {
|
|
26
|
+
discardLate(value);
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
resolve(value);
|
|
30
|
+
}, (error) => {
|
|
31
|
+
signal.removeEventListener("abort", onAbort);
|
|
32
|
+
// After an abort the promise is already rejected, and this is a no-op.
|
|
33
|
+
reject(error);
|
|
34
|
+
});
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Runs `work` with one signal that aborts when `callerSignal` does or when
|
|
39
|
+
* `timeoutMs` passes. A failure caused by the time limit becomes a
|
|
40
|
+
* `NoskillsTimeoutError` naming `operation`; the caller's abort and every
|
|
41
|
+
* other failure propagate unchanged.
|
|
42
|
+
*/
|
|
43
|
+
export async function withDeadline(operation, timeoutMs, callerSignal, work, discardLate = () => { }) {
|
|
44
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
45
|
+
throw new RangeError(`${operation}: timeoutMs ${timeoutMs} is not a positive number of milliseconds`);
|
|
46
|
+
}
|
|
47
|
+
const deadline = AbortSignal.timeout(timeoutMs);
|
|
48
|
+
const signal = callerSignal === undefined
|
|
49
|
+
? deadline
|
|
50
|
+
: AbortSignal.any([callerSignal, deadline]);
|
|
51
|
+
try {
|
|
52
|
+
return await raceSignal(work(signal), signal, discardLate);
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
if (deadline.aborted && callerSignal?.aborted !== true) {
|
|
56
|
+
throw new errors.NoskillsTimeoutError(operation, timeoutMs, {
|
|
57
|
+
cause: error,
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Errors thrown by noskills-client.
|
|
3
|
+
*
|
|
4
|
+
* A cancelled call does not use these: when your `signal` aborts, the call
|
|
5
|
+
* rejects with the signal's reason, as `fetch` does.
|
|
6
|
+
*
|
|
7
|
+
* @module
|
|
8
|
+
*/
|
|
9
|
+
/** A call to the daemon did not finish within its time limit. */
|
|
10
|
+
export declare class NoskillsTimeoutError extends Error {
|
|
11
|
+
/** The call that timed out, such as `GET /api/health` or `attach app/s-1`. */
|
|
12
|
+
readonly operation: string;
|
|
13
|
+
/** The limit that passed, in milliseconds. */
|
|
14
|
+
readonly timeoutMs: number;
|
|
15
|
+
/** Names the call that timed out and the limit, in milliseconds, it had. */
|
|
16
|
+
constructor(operation: string, timeoutMs: number, options?: ErrorOptions);
|
|
17
|
+
}
|
|
18
|
+
/** The daemon answered a REST call with an error status. */
|
|
19
|
+
export declare class NoskillsResponseError extends Error {
|
|
20
|
+
/** The HTTP method of the call. */
|
|
21
|
+
readonly method: string;
|
|
22
|
+
/** The request path, without the base URL. */
|
|
23
|
+
readonly path: string;
|
|
24
|
+
/** The HTTP status the daemon answered with. */
|
|
25
|
+
readonly status: number;
|
|
26
|
+
/** The response body, or the status text when the body could not be read. */
|
|
27
|
+
readonly detail: string;
|
|
28
|
+
/** Describes the call and the daemon's answer. */
|
|
29
|
+
constructor(method: string, path: string, status: number, detail: string);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The daemon's certificate fingerprint could not be fetched: the request
|
|
33
|
+
* failed, the endpoint answered with an error status, or the answer was not a
|
|
34
|
+
* SHA-256 fingerprint.
|
|
35
|
+
*/
|
|
36
|
+
export declare class CertFingerprintError extends Error {
|
|
37
|
+
/** The fingerprint endpoint that was asked. */
|
|
38
|
+
readonly url: string;
|
|
39
|
+
/** The HTTP status, or `null` when no response arrived or it was a 2xx. */
|
|
40
|
+
readonly status: number | null;
|
|
41
|
+
/** Names the endpoint, the status if one arrived, and what was wrong. */
|
|
42
|
+
constructor(url: string, status: number | null, reason: string, options?: ErrorOptions);
|
|
43
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* Errors thrown by noskills-client.
|
|
4
|
+
*
|
|
5
|
+
* A cancelled call does not use these: when your `signal` aborts, the call
|
|
6
|
+
* rejects with the signal's reason, as `fetch` does.
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
/** A call to the daemon did not finish within its time limit. */
|
|
11
|
+
export class NoskillsTimeoutError extends Error {
|
|
12
|
+
/** The call that timed out, such as `GET /api/health` or `attach app/s-1`. */
|
|
13
|
+
operation;
|
|
14
|
+
/** The limit that passed, in milliseconds. */
|
|
15
|
+
timeoutMs;
|
|
16
|
+
/** Names the call that timed out and the limit, in milliseconds, it had. */
|
|
17
|
+
constructor(operation, timeoutMs, options) {
|
|
18
|
+
super(`${operation}: the daemon did not answer within ${timeoutMs} ms; check that it is running and reachable, or raise timeoutMs`, options);
|
|
19
|
+
this.name = "NoskillsTimeoutError";
|
|
20
|
+
this.operation = operation;
|
|
21
|
+
this.timeoutMs = timeoutMs;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** The daemon answered a REST call with an error status. */
|
|
25
|
+
export class NoskillsResponseError extends Error {
|
|
26
|
+
/** The HTTP method of the call. */
|
|
27
|
+
method;
|
|
28
|
+
/** The request path, without the base URL. */
|
|
29
|
+
path;
|
|
30
|
+
/** The HTTP status the daemon answered with. */
|
|
31
|
+
status;
|
|
32
|
+
/** The response body, or the status text when the body could not be read. */
|
|
33
|
+
detail;
|
|
34
|
+
/** Describes the call and the daemon's answer. */
|
|
35
|
+
constructor(method, path, status, detail) {
|
|
36
|
+
super(`${method} ${path} → ${status}: ${detail}`);
|
|
37
|
+
this.name = "NoskillsResponseError";
|
|
38
|
+
this.method = method;
|
|
39
|
+
this.path = path;
|
|
40
|
+
this.status = status;
|
|
41
|
+
this.detail = detail;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The daemon's certificate fingerprint could not be fetched: the request
|
|
46
|
+
* failed, the endpoint answered with an error status, or the answer was not a
|
|
47
|
+
* SHA-256 fingerprint.
|
|
48
|
+
*/
|
|
49
|
+
export class CertFingerprintError extends Error {
|
|
50
|
+
/** The fingerprint endpoint that was asked. */
|
|
51
|
+
url;
|
|
52
|
+
/** The HTTP status, or `null` when no response arrived or it was a 2xx. */
|
|
53
|
+
status;
|
|
54
|
+
/** Names the endpoint, the status if one arrived, and what was wrong. */
|
|
55
|
+
constructor(url, status, reason, options) {
|
|
56
|
+
super(`fetch certificate fingerprint from ${url}: ${reason}`, options);
|
|
57
|
+
this.name = "CertFingerprintError";
|
|
58
|
+
this.url = url;
|
|
59
|
+
this.status = status;
|
|
60
|
+
}
|
|
61
|
+
}
|