@computesdk/cloudbrowser 0.0.0-stage → 0.1.1
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 +21 -0
- package/README.md +29 -2
- package/dist/index.cjs +198 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +13 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +173 -0
- package/dist/index.js.map +1 -0
- package/package.json +60 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 computesdk
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,30 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @computesdk/cloudbrowser
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Create a dedicated managed Chrome browser and connect to it over CDP.
|
|
4
|
+
|
|
5
|
+
## Use the adapter
|
|
6
|
+
|
|
7
|
+
Install `@computesdk/cloudbrowser` and set `CLOUDBROWSER_API_KEY` to an API token with `rest:read`, `rest:manage`, and `rest:links`. See the [Cloudbrowser API guide](https://cloudbrowser.tv/docs/api-tokens) for token setup.
|
|
8
|
+
|
|
9
|
+
```typescript
|
|
10
|
+
import { cloudbrowser } from '@computesdk/cloudbrowser';
|
|
11
|
+
|
|
12
|
+
const provider = cloudbrowser({});
|
|
13
|
+
const session = await provider.session.create();
|
|
14
|
+
|
|
15
|
+
try {
|
|
16
|
+
// Pass session.connectUrl to your CDP client.
|
|
17
|
+
} finally {
|
|
18
|
+
await session.destroy();
|
|
19
|
+
}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The adapter creates browsers with a reserved `ComputeSDK` name and only manages those browsers. Keep that generated name for lookup and cleanup. Looking up or deleting an existing browser with a different name throws an ownership error. `getById()` returns `null` when Cloudbrowser returns HTTP 404, and `destroy()` handles that case as already deleted.
|
|
23
|
+
|
|
24
|
+
`list()` includes managed browsers throughout their lifecycle and skips browsers being deleted. ComputeSDK's `running` status also covers paused browsers and browsers transitioning between running states. Read `session.getInstance().status` for the exact Cloudbrowser state. A CDP connection requires the native state to be `running`. Resume a paused browser from Cloudbrowser before reconnecting.
|
|
25
|
+
|
|
26
|
+
Treat the CDP URL as a credential. Call `destroy()` when you are done. It deletes the dedicated browser and its saved profile.
|
|
27
|
+
|
|
28
|
+
Browsers use automatic idle pause by default. Set `keepAlive: true` when creating a session to turn off idle pause. Workspace usage and billing limits still apply.
|
|
29
|
+
|
|
30
|
+
See [example-cloudbrowser.ts](./example-cloudbrowser.ts) for the full Playwright example.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
cloudbrowser: () => cloudbrowser
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(index_exports);
|
|
26
|
+
var import_provider = require("@computesdk/provider");
|
|
27
|
+
var api = "https://cloudbrowser.tv/api/v1";
|
|
28
|
+
var sessionPrefix = "ComputeSDK ";
|
|
29
|
+
var sessionName = /^ComputeSDK [0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
|
|
30
|
+
var grantName = "ComputeSDK CDP";
|
|
31
|
+
var warnedOptions = /* @__PURE__ */ new Set();
|
|
32
|
+
var ApiError = class extends Error {
|
|
33
|
+
constructor(status, path, method) {
|
|
34
|
+
super(`Cloudbrowser ${method} ${path.split("?")[0]} returned HTTP ${status}`);
|
|
35
|
+
this.status = status;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
function createClient(config) {
|
|
39
|
+
const key = config.apiKey || typeof process !== "undefined" && process.env?.CLOUDBROWSER_API_KEY;
|
|
40
|
+
if (!key) {
|
|
41
|
+
throw new Error(
|
|
42
|
+
"Missing Cloudbrowser API key. Provide 'apiKey' in config or set CLOUDBROWSER_API_KEY. See https://cloudbrowser.tv/docs/api-tokens for token setup."
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
return async function request(path, method = "GET", body, idempotencyKey) {
|
|
46
|
+
const headers = new Headers({ Accept: "application/json", Authorization: `Bearer ${key}` });
|
|
47
|
+
if (body) headers.set("Content-Type", "application/json");
|
|
48
|
+
if (idempotencyKey) headers.set("Idempotency-Key", idempotencyKey);
|
|
49
|
+
const response = await fetch(api + path, {
|
|
50
|
+
method,
|
|
51
|
+
headers,
|
|
52
|
+
body: body && JSON.stringify(body),
|
|
53
|
+
redirect: "error",
|
|
54
|
+
signal: AbortSignal.timeout(15e3)
|
|
55
|
+
});
|
|
56
|
+
if (!response.ok) throw new ApiError(response.status, path, method);
|
|
57
|
+
return response.json();
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
async function waitForOperation(request, operation) {
|
|
61
|
+
const deadline = Date.now() + 9e4;
|
|
62
|
+
while (operation.status === "pending" || operation.status === "running") {
|
|
63
|
+
if (Date.now() >= deadline) throw new Error(`Cloudbrowser operation ${operation.id} timed out`);
|
|
64
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
65
|
+
operation = await request(`/operations/${encodeURIComponent(operation.id)}`);
|
|
66
|
+
}
|
|
67
|
+
if (operation.status !== "succeeded") throw new Error(`Cloudbrowser operation ${operation.id} failed`);
|
|
68
|
+
}
|
|
69
|
+
function browserPath(id) {
|
|
70
|
+
return `/browsers/${encodeURIComponent(id)}`;
|
|
71
|
+
}
|
|
72
|
+
async function readSession(request, id) {
|
|
73
|
+
try {
|
|
74
|
+
const browser = await request(browserPath(id));
|
|
75
|
+
if (!sessionName.test(browser.name)) {
|
|
76
|
+
throw new Error(`Cloudbrowser browser ${id} is not managed by ComputeSDK`);
|
|
77
|
+
}
|
|
78
|
+
return browser;
|
|
79
|
+
} catch (error) {
|
|
80
|
+
if (error instanceof ApiError && error.status === 404) return null;
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
async function deleteSession(request, id) {
|
|
85
|
+
try {
|
|
86
|
+
const operation = await request(browserPath(id), "DELETE", void 0, globalThis.crypto.randomUUID());
|
|
87
|
+
await waitForOperation(request, operation);
|
|
88
|
+
} catch (error) {
|
|
89
|
+
if (error instanceof ApiError && error.status === 404) return;
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
async function readConnectUrl(request, id) {
|
|
94
|
+
const path = `${browserPath(id)}/grants`;
|
|
95
|
+
const { items } = await request(`${path}?audience=cdp&status=active`);
|
|
96
|
+
const grant = items.find((item) => item.name === grantName);
|
|
97
|
+
if (!grant) throw new Error(`ComputeSDK CDP link for browser ${id} is unavailable`);
|
|
98
|
+
const { url } = await request(`${path}/${encodeURIComponent(grant.id)}/secret`);
|
|
99
|
+
return secureConnectUrl(url);
|
|
100
|
+
}
|
|
101
|
+
function secureConnectUrl(url) {
|
|
102
|
+
if (typeof url !== "string" || !url.startsWith("wss://")) {
|
|
103
|
+
throw new Error("Cloudbrowser did not return a secure CDP URL");
|
|
104
|
+
}
|
|
105
|
+
return url;
|
|
106
|
+
}
|
|
107
|
+
function mapStatus(browser) {
|
|
108
|
+
switch (browser.status) {
|
|
109
|
+
case "starting":
|
|
110
|
+
return "created";
|
|
111
|
+
case "running":
|
|
112
|
+
case "pausing":
|
|
113
|
+
case "paused":
|
|
114
|
+
case "resuming":
|
|
115
|
+
case "restarting":
|
|
116
|
+
return "running";
|
|
117
|
+
case "failed":
|
|
118
|
+
return "failed";
|
|
119
|
+
case "deleting":
|
|
120
|
+
return "completed";
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function createOptions(options = {}) {
|
|
124
|
+
for (const [name, value] of Object.entries(options)) {
|
|
125
|
+
if (name === "keepAlive" || value === void 0 || value === false || warnedOptions.has(name)) continue;
|
|
126
|
+
warnedOptions.add(name);
|
|
127
|
+
console.warn(`[@computesdk/cloudbrowser] '${name}' is ignored because the browser API does not accept it at creation`);
|
|
128
|
+
}
|
|
129
|
+
return { name: sessionPrefix + globalThis.crypto.randomUUID(), autoPause: options.keepAlive !== true };
|
|
130
|
+
}
|
|
131
|
+
var cloudbrowser = (0, import_provider.defineBrowserProvider)({
|
|
132
|
+
name: "cloudbrowser",
|
|
133
|
+
methods: {
|
|
134
|
+
session: {
|
|
135
|
+
create: async (config, options) => {
|
|
136
|
+
const request = createClient(config);
|
|
137
|
+
const operation = await request("/browsers", "POST", createOptions(options), globalThis.crypto.randomUUID());
|
|
138
|
+
const id = operation.browserId;
|
|
139
|
+
try {
|
|
140
|
+
await waitForOperation(request, operation);
|
|
141
|
+
const session = await request(browserPath(id));
|
|
142
|
+
if (session.status !== "running") throw new Error(`Cloudbrowser browser ${id} is not running`);
|
|
143
|
+
const { cdpUrl } = await request(`${browserPath(id)}/grants`, "POST", {
|
|
144
|
+
audience: "cdp",
|
|
145
|
+
permission: "control",
|
|
146
|
+
name: grantName
|
|
147
|
+
});
|
|
148
|
+
return { session, sessionId: id, connectUrl: secureConnectUrl(cdpUrl), status: mapStatus(session) };
|
|
149
|
+
} catch (error) {
|
|
150
|
+
try {
|
|
151
|
+
await deleteSession(request, id);
|
|
152
|
+
} catch (cleanupError) {
|
|
153
|
+
throw new AggregateError([error, cleanupError], `Could not provision or clean up Cloudbrowser browser ${id}`);
|
|
154
|
+
}
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
},
|
|
158
|
+
getById: async (config, id) => {
|
|
159
|
+
const request = createClient(config);
|
|
160
|
+
const session = await readSession(request, id);
|
|
161
|
+
if (!session) return null;
|
|
162
|
+
const connectUrl = await readConnectUrl(request, id);
|
|
163
|
+
return { session, sessionId: id, connectUrl, status: mapStatus(session) };
|
|
164
|
+
},
|
|
165
|
+
list: async (config) => {
|
|
166
|
+
const request = createClient(config);
|
|
167
|
+
const sessions = [];
|
|
168
|
+
let cursor;
|
|
169
|
+
do {
|
|
170
|
+
const params = new URLSearchParams({ limit: "100" });
|
|
171
|
+
if (cursor) params.set("cursor", cursor);
|
|
172
|
+
const page = await request(`/browsers?${params}`);
|
|
173
|
+
for (const session of page.items) {
|
|
174
|
+
if (session.status !== "deleting" && sessionName.test(session.name)) {
|
|
175
|
+
sessions.push({ session, sessionId: session.id, status: mapStatus(session) });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
cursor = page.nextCursor;
|
|
179
|
+
} while (cursor);
|
|
180
|
+
return sessions;
|
|
181
|
+
},
|
|
182
|
+
destroy: async (config, id) => {
|
|
183
|
+
const request = createClient(config);
|
|
184
|
+
if (await readSession(request, id)) await deleteSession(request, id);
|
|
185
|
+
},
|
|
186
|
+
getConnectUrl: async (config, id) => {
|
|
187
|
+
const request = createClient(config);
|
|
188
|
+
if (!await readSession(request, id)) throw new Error(`ComputeSDK browser ${id} was not found`);
|
|
189
|
+
return readConnectUrl(request, id);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
195
|
+
0 && (module.exports = {
|
|
196
|
+
cloudbrowser
|
|
197
|
+
});
|
|
198
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { defineBrowserProvider } from '@computesdk/provider';\nimport type { BrowserSession, CreateBrowserSessionOptions } from '@computesdk/provider';\n\nexport interface CloudbrowserConfig {\n apiKey?: string;\n}\n\ninterface CloudbrowserSession {\n id: string;\n name: string;\n status: 'starting' | 'running' | 'pausing' | 'paused' | 'resuming' | 'restarting' | 'failed' | 'deleting';\n}\n\ninterface Operation {\n id: string;\n browserId: string;\n status: 'pending' | 'running' | 'succeeded' | 'failed';\n}\n\ninterface Page<T> {\n items: T[];\n nextCursor?: string | null;\n}\n\nconst api = 'https://cloudbrowser.tv/api/v1';\nconst sessionPrefix = 'ComputeSDK ';\nconst sessionName = /^ComputeSDK [0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;\nconst grantName = 'ComputeSDK CDP';\nconst warnedOptions = new Set<string>();\n\nclass ApiError extends Error {\n constructor(readonly status: number, path: string, method: string) {\n super(`Cloudbrowser ${method} ${path.split('?')[0]} returned HTTP ${status}`);\n }\n}\n\nfunction createClient(config: CloudbrowserConfig) {\n const key = config.apiKey ||\n (typeof process !== 'undefined' && process.env?.CLOUDBROWSER_API_KEY);\n if (!key) {\n throw new Error(\n \"Missing Cloudbrowser API key. Provide 'apiKey' in config or set CLOUDBROWSER_API_KEY. \" +\n 'See https://cloudbrowser.tv/docs/api-tokens for token setup.',\n );\n }\n\n return async function request<T>(path: string, method = 'GET', body?: object, idempotencyKey?: string): Promise<T> {\n const headers = new Headers({ Accept: 'application/json', Authorization: `Bearer ${key}` });\n if (body) headers.set('Content-Type', 'application/json');\n if (idempotencyKey) headers.set('Idempotency-Key', idempotencyKey);\n\n const response = await fetch(api + path, {\n method,\n headers,\n body: body && JSON.stringify(body),\n redirect: 'error',\n signal: AbortSignal.timeout(15_000),\n });\n if (!response.ok) throw new ApiError(response.status, path, method);\n return response.json() as Promise<T>;\n };\n}\n\ntype Request = ReturnType<typeof createClient>;\n\nasync function waitForOperation(request: Request, operation: Operation) {\n const deadline = Date.now() + 90_000;\n while (operation.status === 'pending' || operation.status === 'running') {\n if (Date.now() >= deadline) throw new Error(`Cloudbrowser operation ${operation.id} timed out`);\n await new Promise<void>((resolve) => setTimeout(resolve, 500));\n operation = await request<Operation>(`/operations/${encodeURIComponent(operation.id)}`);\n }\n if (operation.status !== 'succeeded') throw new Error(`Cloudbrowser operation ${operation.id} failed`);\n}\n\nfunction browserPath(id: string) {\n return `/browsers/${encodeURIComponent(id)}`;\n}\n\nasync function readSession(request: Request, id: string) {\n try {\n const browser = await request<CloudbrowserSession>(browserPath(id));\n if (!sessionName.test(browser.name)) {\n throw new Error(`Cloudbrowser browser ${id} is not managed by ComputeSDK`);\n }\n return browser;\n } catch (error) {\n if (error instanceof ApiError && error.status === 404) return null;\n throw error;\n }\n}\n\nasync function deleteSession(request: Request, id: string) {\n try {\n const operation = await request<Operation>(browserPath(id), 'DELETE', undefined, globalThis.crypto.randomUUID());\n await waitForOperation(request, operation);\n } catch (error) {\n if (error instanceof ApiError && error.status === 404) return;\n throw error;\n }\n}\n\nasync function readConnectUrl(request: Request, id: string) {\n const path = `${browserPath(id)}/grants`;\n const { items } = await request<Page<{ id: string; name: string }>>(`${path}?audience=cdp&status=active`);\n const grant = items.find((item) => item.name === grantName);\n if (!grant) throw new Error(`ComputeSDK CDP link for browser ${id} is unavailable`);\n const { url } = await request<{ url: string }>(`${path}/${encodeURIComponent(grant.id)}/secret`);\n return secureConnectUrl(url);\n}\n\nfunction secureConnectUrl(url: string) {\n if (typeof url !== 'string' || !url.startsWith('wss://')) {\n throw new Error('Cloudbrowser did not return a secure CDP URL');\n }\n return url;\n}\n\nfunction mapStatus(browser: CloudbrowserSession): BrowserSession['status'] {\n switch (browser.status) {\n case 'starting': return 'created';\n case 'running':\n case 'pausing':\n case 'paused':\n case 'resuming':\n case 'restarting':\n return 'running';\n case 'failed': return 'failed';\n case 'deleting': return 'completed';\n }\n}\n\nfunction createOptions(options: CreateBrowserSessionOptions = {}) {\n for (const [name, value] of Object.entries(options)) {\n if (name === 'keepAlive' || value === undefined || value === false || warnedOptions.has(name)) continue;\n warnedOptions.add(name);\n console.warn(`[@computesdk/cloudbrowser] '${name}' is ignored because the browser API does not accept it at creation`);\n }\n return { name: sessionPrefix + globalThis.crypto.randomUUID(), autoPause: options.keepAlive !== true };\n}\n\nexport const cloudbrowser = defineBrowserProvider<CloudbrowserSession, CloudbrowserConfig>({\n name: 'cloudbrowser',\n methods: {\n session: {\n create: async (config, options) => {\n const request = createClient(config);\n const operation = await request<Operation>('/browsers', 'POST', createOptions(options), globalThis.crypto.randomUUID());\n const id = operation.browserId;\n try {\n await waitForOperation(request, operation);\n const session = await request<CloudbrowserSession>(browserPath(id));\n if (session.status !== 'running') throw new Error(`Cloudbrowser browser ${id} is not running`);\n const { cdpUrl } = await request<{ cdpUrl: string }>(`${browserPath(id)}/grants`, 'POST', {\n audience: 'cdp',\n permission: 'control',\n name: grantName,\n });\n return { session, sessionId: id, connectUrl: secureConnectUrl(cdpUrl), status: mapStatus(session) };\n } catch (error) {\n try {\n await deleteSession(request, id);\n } catch (cleanupError) {\n throw new AggregateError([error, cleanupError], `Could not provision or clean up Cloudbrowser browser ${id}`);\n }\n throw error;\n }\n },\n getById: async (config, id) => {\n const request = createClient(config);\n const session = await readSession(request, id);\n if (!session) return null;\n const connectUrl = await readConnectUrl(request, id);\n return { session, sessionId: id, connectUrl, status: mapStatus(session) };\n },\n list: async (config) => {\n const request = createClient(config);\n const sessions: Array<{ session: CloudbrowserSession; sessionId: string; status: BrowserSession['status'] }> = [];\n let cursor: string | null | undefined;\n do {\n const params = new URLSearchParams({ limit: '100' });\n if (cursor) params.set('cursor', cursor);\n const page = await request<Page<CloudbrowserSession>>(`/browsers?${params}`);\n for (const session of page.items) {\n if (session.status !== 'deleting' && sessionName.test(session.name)) {\n sessions.push({ session, sessionId: session.id, status: mapStatus(session) });\n }\n }\n cursor = page.nextCursor;\n } while (cursor);\n return sessions;\n },\n destroy: async (config, id) => {\n const request = createClient(config);\n if (await readSession(request, id)) await deleteSession(request, id);\n },\n getConnectUrl: async (config, id) => {\n const request = createClient(config);\n if (!await readSession(request, id)) throw new Error(`ComputeSDK browser ${id} was not found`);\n return readConnectUrl(request, id);\n },\n },\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAsC;AAwBtC,IAAM,MAAM;AACZ,IAAM,gBAAgB;AACtB,IAAM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,MACrE;AAAA,MACA,eAAe,OAAO,QAAQ,OAAO;AACnC,cAAM,UAAU,aAAa,MAAM;AACnC,YAAI,CAAC,MAAM,YAAY,SAAS,EAAE,EAAG,OAAM,IAAI,MAAM,sBAAsB,EAAE,gBAAgB;AAC7F,eAAO,eAAe,SAAS,EAAE;AAAA,MACnC;AAAA,IACF;AAAA,EACF;AACF,CAAC;","names":[]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import * as computesdk from 'computesdk';
|
|
2
|
+
|
|
3
|
+
interface CloudbrowserConfig {
|
|
4
|
+
apiKey?: string;
|
|
5
|
+
}
|
|
6
|
+
interface CloudbrowserSession {
|
|
7
|
+
id: string;
|
|
8
|
+
name: string;
|
|
9
|
+
status: 'starting' | 'running' | 'pausing' | 'paused' | 'resuming' | 'restarting' | 'failed' | 'deleting';
|
|
10
|
+
}
|
|
11
|
+
declare const cloudbrowser: (config: CloudbrowserConfig) => computesdk.BrowserProvider<CloudbrowserSession>;
|
|
12
|
+
|
|
13
|
+
export { type CloudbrowserConfig, cloudbrowser };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import * as computesdk from 'computesdk';
|
|
2
|
+
|
|
3
|
+
interface CloudbrowserConfig {
|
|
4
|
+
apiKey?: string;
|
|
5
|
+
}
|
|
6
|
+
interface CloudbrowserSession {
|
|
7
|
+
id: string;
|
|
8
|
+
name: string;
|
|
9
|
+
status: 'starting' | 'running' | 'pausing' | 'paused' | 'resuming' | 'restarting' | 'failed' | 'deleting';
|
|
10
|
+
}
|
|
11
|
+
declare const cloudbrowser: (config: CloudbrowserConfig) => computesdk.BrowserProvider<CloudbrowserSession>;
|
|
12
|
+
|
|
13
|
+
export { type CloudbrowserConfig, cloudbrowser };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { defineBrowserProvider } from "@computesdk/provider";
|
|
3
|
+
var api = "https://cloudbrowser.tv/api/v1";
|
|
4
|
+
var sessionPrefix = "ComputeSDK ";
|
|
5
|
+
var sessionName = /^ComputeSDK [0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
|
|
6
|
+
var grantName = "ComputeSDK CDP";
|
|
7
|
+
var warnedOptions = /* @__PURE__ */ new Set();
|
|
8
|
+
var ApiError = class extends Error {
|
|
9
|
+
constructor(status, path, method) {
|
|
10
|
+
super(`Cloudbrowser ${method} ${path.split("?")[0]} returned HTTP ${status}`);
|
|
11
|
+
this.status = status;
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
function createClient(config) {
|
|
15
|
+
const key = config.apiKey || typeof process !== "undefined" && process.env?.CLOUDBROWSER_API_KEY;
|
|
16
|
+
if (!key) {
|
|
17
|
+
throw new Error(
|
|
18
|
+
"Missing Cloudbrowser API key. Provide 'apiKey' in config or set CLOUDBROWSER_API_KEY. See https://cloudbrowser.tv/docs/api-tokens for token setup."
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
return async function request(path, method = "GET", body, idempotencyKey) {
|
|
22
|
+
const headers = new Headers({ Accept: "application/json", Authorization: `Bearer ${key}` });
|
|
23
|
+
if (body) headers.set("Content-Type", "application/json");
|
|
24
|
+
if (idempotencyKey) headers.set("Idempotency-Key", idempotencyKey);
|
|
25
|
+
const response = await fetch(api + path, {
|
|
26
|
+
method,
|
|
27
|
+
headers,
|
|
28
|
+
body: body && JSON.stringify(body),
|
|
29
|
+
redirect: "error",
|
|
30
|
+
signal: AbortSignal.timeout(15e3)
|
|
31
|
+
});
|
|
32
|
+
if (!response.ok) throw new ApiError(response.status, path, method);
|
|
33
|
+
return response.json();
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
async function waitForOperation(request, operation) {
|
|
37
|
+
const deadline = Date.now() + 9e4;
|
|
38
|
+
while (operation.status === "pending" || operation.status === "running") {
|
|
39
|
+
if (Date.now() >= deadline) throw new Error(`Cloudbrowser operation ${operation.id} timed out`);
|
|
40
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
41
|
+
operation = await request(`/operations/${encodeURIComponent(operation.id)}`);
|
|
42
|
+
}
|
|
43
|
+
if (operation.status !== "succeeded") throw new Error(`Cloudbrowser operation ${operation.id} failed`);
|
|
44
|
+
}
|
|
45
|
+
function browserPath(id) {
|
|
46
|
+
return `/browsers/${encodeURIComponent(id)}`;
|
|
47
|
+
}
|
|
48
|
+
async function readSession(request, id) {
|
|
49
|
+
try {
|
|
50
|
+
const browser = await request(browserPath(id));
|
|
51
|
+
if (!sessionName.test(browser.name)) {
|
|
52
|
+
throw new Error(`Cloudbrowser browser ${id} is not managed by ComputeSDK`);
|
|
53
|
+
}
|
|
54
|
+
return browser;
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (error instanceof ApiError && error.status === 404) return null;
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
async function deleteSession(request, id) {
|
|
61
|
+
try {
|
|
62
|
+
const operation = await request(browserPath(id), "DELETE", void 0, globalThis.crypto.randomUUID());
|
|
63
|
+
await waitForOperation(request, operation);
|
|
64
|
+
} catch (error) {
|
|
65
|
+
if (error instanceof ApiError && error.status === 404) return;
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
async function readConnectUrl(request, id) {
|
|
70
|
+
const path = `${browserPath(id)}/grants`;
|
|
71
|
+
const { items } = await request(`${path}?audience=cdp&status=active`);
|
|
72
|
+
const grant = items.find((item) => item.name === grantName);
|
|
73
|
+
if (!grant) throw new Error(`ComputeSDK CDP link for browser ${id} is unavailable`);
|
|
74
|
+
const { url } = await request(`${path}/${encodeURIComponent(grant.id)}/secret`);
|
|
75
|
+
return secureConnectUrl(url);
|
|
76
|
+
}
|
|
77
|
+
function secureConnectUrl(url) {
|
|
78
|
+
if (typeof url !== "string" || !url.startsWith("wss://")) {
|
|
79
|
+
throw new Error("Cloudbrowser did not return a secure CDP URL");
|
|
80
|
+
}
|
|
81
|
+
return url;
|
|
82
|
+
}
|
|
83
|
+
function mapStatus(browser) {
|
|
84
|
+
switch (browser.status) {
|
|
85
|
+
case "starting":
|
|
86
|
+
return "created";
|
|
87
|
+
case "running":
|
|
88
|
+
case "pausing":
|
|
89
|
+
case "paused":
|
|
90
|
+
case "resuming":
|
|
91
|
+
case "restarting":
|
|
92
|
+
return "running";
|
|
93
|
+
case "failed":
|
|
94
|
+
return "failed";
|
|
95
|
+
case "deleting":
|
|
96
|
+
return "completed";
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
function createOptions(options = {}) {
|
|
100
|
+
for (const [name, value] of Object.entries(options)) {
|
|
101
|
+
if (name === "keepAlive" || value === void 0 || value === false || warnedOptions.has(name)) continue;
|
|
102
|
+
warnedOptions.add(name);
|
|
103
|
+
console.warn(`[@computesdk/cloudbrowser] '${name}' is ignored because the browser API does not accept it at creation`);
|
|
104
|
+
}
|
|
105
|
+
return { name: sessionPrefix + globalThis.crypto.randomUUID(), autoPause: options.keepAlive !== true };
|
|
106
|
+
}
|
|
107
|
+
var cloudbrowser = defineBrowserProvider({
|
|
108
|
+
name: "cloudbrowser",
|
|
109
|
+
methods: {
|
|
110
|
+
session: {
|
|
111
|
+
create: async (config, options) => {
|
|
112
|
+
const request = createClient(config);
|
|
113
|
+
const operation = await request("/browsers", "POST", createOptions(options), globalThis.crypto.randomUUID());
|
|
114
|
+
const id = operation.browserId;
|
|
115
|
+
try {
|
|
116
|
+
await waitForOperation(request, operation);
|
|
117
|
+
const session = await request(browserPath(id));
|
|
118
|
+
if (session.status !== "running") throw new Error(`Cloudbrowser browser ${id} is not running`);
|
|
119
|
+
const { cdpUrl } = await request(`${browserPath(id)}/grants`, "POST", {
|
|
120
|
+
audience: "cdp",
|
|
121
|
+
permission: "control",
|
|
122
|
+
name: grantName
|
|
123
|
+
});
|
|
124
|
+
return { session, sessionId: id, connectUrl: secureConnectUrl(cdpUrl), status: mapStatus(session) };
|
|
125
|
+
} catch (error) {
|
|
126
|
+
try {
|
|
127
|
+
await deleteSession(request, id);
|
|
128
|
+
} catch (cleanupError) {
|
|
129
|
+
throw new AggregateError([error, cleanupError], `Could not provision or clean up Cloudbrowser browser ${id}`);
|
|
130
|
+
}
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
getById: async (config, id) => {
|
|
135
|
+
const request = createClient(config);
|
|
136
|
+
const session = await readSession(request, id);
|
|
137
|
+
if (!session) return null;
|
|
138
|
+
const connectUrl = await readConnectUrl(request, id);
|
|
139
|
+
return { session, sessionId: id, connectUrl, status: mapStatus(session) };
|
|
140
|
+
},
|
|
141
|
+
list: async (config) => {
|
|
142
|
+
const request = createClient(config);
|
|
143
|
+
const sessions = [];
|
|
144
|
+
let cursor;
|
|
145
|
+
do {
|
|
146
|
+
const params = new URLSearchParams({ limit: "100" });
|
|
147
|
+
if (cursor) params.set("cursor", cursor);
|
|
148
|
+
const page = await request(`/browsers?${params}`);
|
|
149
|
+
for (const session of page.items) {
|
|
150
|
+
if (session.status !== "deleting" && sessionName.test(session.name)) {
|
|
151
|
+
sessions.push({ session, sessionId: session.id, status: mapStatus(session) });
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
cursor = page.nextCursor;
|
|
155
|
+
} while (cursor);
|
|
156
|
+
return sessions;
|
|
157
|
+
},
|
|
158
|
+
destroy: async (config, id) => {
|
|
159
|
+
const request = createClient(config);
|
|
160
|
+
if (await readSession(request, id)) await deleteSession(request, id);
|
|
161
|
+
},
|
|
162
|
+
getConnectUrl: async (config, id) => {
|
|
163
|
+
const request = createClient(config);
|
|
164
|
+
if (!await readSession(request, id)) throw new Error(`ComputeSDK browser ${id} was not found`);
|
|
165
|
+
return readConnectUrl(request, id);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
export {
|
|
171
|
+
cloudbrowser
|
|
172
|
+
};
|
|
173
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { defineBrowserProvider } from '@computesdk/provider';\nimport type { BrowserSession, CreateBrowserSessionOptions } from '@computesdk/provider';\n\nexport interface CloudbrowserConfig {\n apiKey?: string;\n}\n\ninterface CloudbrowserSession {\n id: string;\n name: string;\n status: 'starting' | 'running' | 'pausing' | 'paused' | 'resuming' | 'restarting' | 'failed' | 'deleting';\n}\n\ninterface Operation {\n id: string;\n browserId: string;\n status: 'pending' | 'running' | 'succeeded' | 'failed';\n}\n\ninterface Page<T> {\n items: T[];\n nextCursor?: string | null;\n}\n\nconst api = 'https://cloudbrowser.tv/api/v1';\nconst sessionPrefix = 'ComputeSDK ';\nconst sessionName = /^ComputeSDK [0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;\nconst grantName = 'ComputeSDK CDP';\nconst warnedOptions = new Set<string>();\n\nclass ApiError extends Error {\n constructor(readonly status: number, path: string, method: string) {\n super(`Cloudbrowser ${method} ${path.split('?')[0]} returned HTTP ${status}`);\n }\n}\n\nfunction createClient(config: CloudbrowserConfig) {\n const key = config.apiKey ||\n (typeof process !== 'undefined' && process.env?.CLOUDBROWSER_API_KEY);\n if (!key) {\n throw new Error(\n \"Missing Cloudbrowser API key. Provide 'apiKey' in config or set CLOUDBROWSER_API_KEY. \" +\n 'See https://cloudbrowser.tv/docs/api-tokens for token setup.',\n );\n }\n\n return async function request<T>(path: string, method = 'GET', body?: object, idempotencyKey?: string): Promise<T> {\n const headers = new Headers({ Accept: 'application/json', Authorization: `Bearer ${key}` });\n if (body) headers.set('Content-Type', 'application/json');\n if (idempotencyKey) headers.set('Idempotency-Key', idempotencyKey);\n\n const response = await fetch(api + path, {\n method,\n headers,\n body: body && JSON.stringify(body),\n redirect: 'error',\n signal: AbortSignal.timeout(15_000),\n });\n if (!response.ok) throw new ApiError(response.status, path, method);\n return response.json() as Promise<T>;\n };\n}\n\ntype Request = ReturnType<typeof createClient>;\n\nasync function waitForOperation(request: Request, operation: Operation) {\n const deadline = Date.now() + 90_000;\n while (operation.status === 'pending' || operation.status === 'running') {\n if (Date.now() >= deadline) throw new Error(`Cloudbrowser operation ${operation.id} timed out`);\n await new Promise<void>((resolve) => setTimeout(resolve, 500));\n operation = await request<Operation>(`/operations/${encodeURIComponent(operation.id)}`);\n }\n if (operation.status !== 'succeeded') throw new Error(`Cloudbrowser operation ${operation.id} failed`);\n}\n\nfunction browserPath(id: string) {\n return `/browsers/${encodeURIComponent(id)}`;\n}\n\nasync function readSession(request: Request, id: string) {\n try {\n const browser = await request<CloudbrowserSession>(browserPath(id));\n if (!sessionName.test(browser.name)) {\n throw new Error(`Cloudbrowser browser ${id} is not managed by ComputeSDK`);\n }\n return browser;\n } catch (error) {\n if (error instanceof ApiError && error.status === 404) return null;\n throw error;\n }\n}\n\nasync function deleteSession(request: Request, id: string) {\n try {\n const operation = await request<Operation>(browserPath(id), 'DELETE', undefined, globalThis.crypto.randomUUID());\n await waitForOperation(request, operation);\n } catch (error) {\n if (error instanceof ApiError && error.status === 404) return;\n throw error;\n }\n}\n\nasync function readConnectUrl(request: Request, id: string) {\n const path = `${browserPath(id)}/grants`;\n const { items } = await request<Page<{ id: string; name: string }>>(`${path}?audience=cdp&status=active`);\n const grant = items.find((item) => item.name === grantName);\n if (!grant) throw new Error(`ComputeSDK CDP link for browser ${id} is unavailable`);\n const { url } = await request<{ url: string }>(`${path}/${encodeURIComponent(grant.id)}/secret`);\n return secureConnectUrl(url);\n}\n\nfunction secureConnectUrl(url: string) {\n if (typeof url !== 'string' || !url.startsWith('wss://')) {\n throw new Error('Cloudbrowser did not return a secure CDP URL');\n }\n return url;\n}\n\nfunction mapStatus(browser: CloudbrowserSession): BrowserSession['status'] {\n switch (browser.status) {\n case 'starting': return 'created';\n case 'running':\n case 'pausing':\n case 'paused':\n case 'resuming':\n case 'restarting':\n return 'running';\n case 'failed': return 'failed';\n case 'deleting': return 'completed';\n }\n}\n\nfunction createOptions(options: CreateBrowserSessionOptions = {}) {\n for (const [name, value] of Object.entries(options)) {\n if (name === 'keepAlive' || value === undefined || value === false || warnedOptions.has(name)) continue;\n warnedOptions.add(name);\n console.warn(`[@computesdk/cloudbrowser] '${name}' is ignored because the browser API does not accept it at creation`);\n }\n return { name: sessionPrefix + globalThis.crypto.randomUUID(), autoPause: options.keepAlive !== true };\n}\n\nexport const cloudbrowser = defineBrowserProvider<CloudbrowserSession, CloudbrowserConfig>({\n name: 'cloudbrowser',\n methods: {\n session: {\n create: async (config, options) => {\n const request = createClient(config);\n const operation = await request<Operation>('/browsers', 'POST', createOptions(options), globalThis.crypto.randomUUID());\n const id = operation.browserId;\n try {\n await waitForOperation(request, operation);\n const session = await request<CloudbrowserSession>(browserPath(id));\n if (session.status !== 'running') throw new Error(`Cloudbrowser browser ${id} is not running`);\n const { cdpUrl } = await request<{ cdpUrl: string }>(`${browserPath(id)}/grants`, 'POST', {\n audience: 'cdp',\n permission: 'control',\n name: grantName,\n });\n return { session, sessionId: id, connectUrl: secureConnectUrl(cdpUrl), status: mapStatus(session) };\n } catch (error) {\n try {\n await deleteSession(request, id);\n } catch (cleanupError) {\n throw new AggregateError([error, cleanupError], `Could not provision or clean up Cloudbrowser browser ${id}`);\n }\n throw error;\n }\n },\n getById: async (config, id) => {\n const request = createClient(config);\n const session = await readSession(request, id);\n if (!session) return null;\n const connectUrl = await readConnectUrl(request, id);\n return { session, sessionId: id, connectUrl, status: mapStatus(session) };\n },\n list: async (config) => {\n const request = createClient(config);\n const sessions: Array<{ session: CloudbrowserSession; sessionId: string; status: BrowserSession['status'] }> = [];\n let cursor: string | null | undefined;\n do {\n const params = new URLSearchParams({ limit: '100' });\n if (cursor) params.set('cursor', cursor);\n const page = await request<Page<CloudbrowserSession>>(`/browsers?${params}`);\n for (const session of page.items) {\n if (session.status !== 'deleting' && sessionName.test(session.name)) {\n sessions.push({ session, sessionId: session.id, status: mapStatus(session) });\n }\n }\n cursor = page.nextCursor;\n } while (cursor);\n return sessions;\n },\n destroy: async (config, id) => {\n const request = createClient(config);\n if (await readSession(request, id)) await deleteSession(request, id);\n },\n getConnectUrl: async (config, id) => {\n const request = createClient(config);\n if (!await readSession(request, id)) throw new Error(`ComputeSDK browser ${id} was not found`);\n return readConnectUrl(request, id);\n },\n },\n },\n});\n"],"mappings":";AAAA,SAAS,6BAA6B;AAwBtC,IAAM,MAAM;AACZ,IAAM,gBAAgB;AACtB,IAAM,cAAc;AACpB,IAAM,YAAY;AAClB,IAAM,gBAAgB,oBAAI,IAAY;AAEtC,IAAM,WAAN,cAAuB,MAAM;AAAA,EAC3B,YAAqB,QAAgB,MAAc,QAAgB;AACjE,UAAM,gBAAgB,MAAM,IAAI,KAAK,MAAM,GAAG,EAAE,CAAC,CAAC,kBAAkB,MAAM,EAAE;AADzD;AAAA,EAErB;AACF;AAEA,SAAS,aAAa,QAA4B;AAChD,QAAM,MAAM,OAAO,UAChB,OAAO,YAAY,eAAe,QAAQ,KAAK;AAClD,MAAI,CAAC,KAAK;AACR,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AAEA,SAAO,eAAe,QAAW,MAAc,SAAS,OAAO,MAAe,gBAAqC;AACjH,UAAM,UAAU,IAAI,QAAQ,EAAE,QAAQ,oBAAoB,eAAe,UAAU,GAAG,GAAG,CAAC;AAC1F,QAAI,KAAM,SAAQ,IAAI,gBAAgB,kBAAkB;AACxD,QAAI,eAAgB,SAAQ,IAAI,mBAAmB,cAAc;AAEjE,UAAM,WAAW,MAAM,MAAM,MAAM,MAAM;AAAA,MACvC;AAAA,MACA;AAAA,MACA,MAAM,QAAQ,KAAK,UAAU,IAAI;AAAA,MACjC,UAAU;AAAA,MACV,QAAQ,YAAY,QAAQ,IAAM;AAAA,IACpC,CAAC;AACD,QAAI,CAAC,SAAS,GAAI,OAAM,IAAI,SAAS,SAAS,QAAQ,MAAM,MAAM;AAClE,WAAO,SAAS,KAAK;A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I,GAAG;AACnE,uBAAS,KAAK,EAAE,SAAS,WAAW,QAAQ,IAAI,QAAQ,UAAU,OAAO,EAAE,CAAC;AAAA,YAC9E;AAAA,UACF;AACA,mBAAS,KAAK;AAAA,QAChB,SAAS;AACT,eAAO;AAAA,MACT;AAAA,MACA,SAAS,OAAO,QAAQ,OAAO;AAC7B,cAAM,UAAU,aAAa,MAAM;AACnC,YAAI,MAAM,YAAY,SAAS,EAAE,EAAG,OAAM,cAAc,SAAS,EAAE;AAAA,MACrE;AAAA,MACA,eAAe,OAAO,QAAQ,OAAO;AACnC,cAAM,UAAU,aAAa,MAAM;AACnC,YAAI,CAAC,MAAM,YAAY,SAAS,EAAE,EAAG,OAAM,IAAI,MAAM,sBAAsB,EAAE,gBAAgB;AAC7F,eAAO,eAAe,SAAS,EAAE;AAAA,MACnC;AAAA,IACF;AAAA,EACF;AACF,CAAC;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@computesdk/cloudbrowser",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Cloudbrowser adapter for ComputeSDK. Create managed Chrome sessions and connect over CDP.",
|
|
5
|
+
"author": "Cloudbrowser",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "./dist/index.cjs",
|
|
9
|
+
"module": "./dist/index.js",
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"import": "./dist/index.js",
|
|
15
|
+
"require": "./dist/index.cjs"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist"
|
|
20
|
+
],
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"playwright-core": "^1.40.0",
|
|
23
|
+
"@computesdk/provider": "2.1.35",
|
|
24
|
+
"computesdk": "4.1.29"
|
|
25
|
+
},
|
|
26
|
+
"keywords": [
|
|
27
|
+
"computesdk",
|
|
28
|
+
"cloudbrowser",
|
|
29
|
+
"browser",
|
|
30
|
+
"headless",
|
|
31
|
+
"playwright",
|
|
32
|
+
"provider"
|
|
33
|
+
],
|
|
34
|
+
"repository": {
|
|
35
|
+
"type": "git",
|
|
36
|
+
"url": "https://github.com/computesdk/computesdk.git",
|
|
37
|
+
"directory": "packages/cloudbrowser"
|
|
38
|
+
},
|
|
39
|
+
"homepage": "https://github.com/computesdk/computesdk/tree/main/packages/cloudbrowser#readme",
|
|
40
|
+
"bugs": {
|
|
41
|
+
"url": "https://github.com/computesdk/computesdk/issues"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@types/node": "^20.0.0",
|
|
45
|
+
"@vitest/coverage-v8": "^1.0.0",
|
|
46
|
+
"eslint": "^8.37.0",
|
|
47
|
+
"rimraf": "^5.0.0",
|
|
48
|
+
"tsup": "^8.0.0",
|
|
49
|
+
"typescript": "^5.0.0",
|
|
50
|
+
"vitest": "^1.0.0",
|
|
51
|
+
"@computesdk/test-utils": "2.0.7"
|
|
52
|
+
},
|
|
53
|
+
"scripts": {
|
|
54
|
+
"build": "tsup",
|
|
55
|
+
"clean": "rimraf dist",
|
|
56
|
+
"dev": "tsup --watch",
|
|
57
|
+
"test": "vitest run",
|
|
58
|
+
"test:watch": "vitest watch",
|
|
59
|
+
"test:coverage": "vitest run --coverage",
|
|
60
|
+
"typecheck": "tsc --noEmit",
|
|
61
|
+
"lint": "eslint"
|
|
62
|
+
}
|
|
6
63
|
}
|