@mayurajs/browser-kernel 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,8 @@
1
+ Mayura
2
+ Copyright 2026 The Mayura Authors
3
+
4
+ This product includes software developed by the Mayura contributors.
5
+
6
+ Third-party dependencies retain their own copyright and license terms. Exact
7
+ resolved versions are recorded in pnpm-lock.yaml and reviewed by the release
8
+ artifact and dependency qualification procedures.
package/README.md CHANGED
@@ -1,3 +1,37 @@
1
- # Temporary Holding Version
1
+ # @mayurajs/browser-kernel
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Kernel](https://www.kernel.sh/docs) browsers for `mayura/browser`: hosted Chromium, created over Kernel's browsers
4
+ API and driven over CDP, from any runtime, with no dependency.
5
+
6
+ ```bash
7
+ npm install mayura @mayurajs/browser-kernel
8
+ ```
9
+
10
+ ```ts
11
+ import { createBrowsers } from 'mayura/browser';
12
+ import { kernelBrowsers } from '@mayurajs/browser-kernel';
13
+
14
+ const browsers = createBrowsers(kernelBrowsers({ apiKey }), {
15
+ maxBrowsers: 2, maxLifetimeMs: 30 * 60_000,
16
+ origins: ['https://example.com'],
17
+ });
18
+ const browser = await browsers.open();
19
+ await browser.goto('https://example.com/');
20
+ await browser.release();
21
+ ```
22
+
23
+ - Each browser is created when opened and deleted when released. Kernel keeps a browser running for as long as it is
24
+ connected, so its lifetime is kept by `createBrowsers`, which releases it then. Once nothing is connected (this
25
+ process stopped, say), Kernel deletes it after `standbyTimeoutSeconds`: 60 by default.
26
+ - **Stealth is off**, since in Kernel it also turns on a captcha solver; turn it on with `stealth`. No proxy is used.
27
+ Labels become the browser's tags.
28
+ - `liveViewUrl` is Kernel's live view, a link with a token in it: by default it only shows the browser
29
+ (`liveView: 'view'`); `'interact'` lets whoever has the link use it too; `false` gives none and runs the browser
30
+ headless.
31
+ - Treat the CDP URL as a secret, as Kernel does not say what it carries: Mayura never logs it.
32
+ - Origins are enforced inside the browser, by intercepting its requests over CDP. This has not yet been tried against
33
+ Kernel itself: should its connection not allow that, opening a browser fails rather than running unchecked.
34
+ - Options: `apiKey`, `liveView`, `stealth`, `region` (`us-east`, `eu-west`, `ap-southeast`), `standbyTimeoutSeconds`,
35
+ `maxLifetimeMs` (24 hours), `fetch`, `baseUrl`.
36
+
37
+ See the [browser guide](https://mayurajs.com/docs/guides/browsers/). Apache-2.0.
@@ -0,0 +1,33 @@
1
+ import { type BrowserProvider } from 'mayura/browser';
2
+ export interface KernelBrowserOptions {
3
+ /** A Kernel API key. Nothing is read from the environment. */
4
+ readonly apiKey: string;
5
+ /**
6
+ * Give each browser a live view (`liveViewUrl`), a link with a token in it: `'view'` (the default) only shows the
7
+ * browser; `'interact'` also lets whoever has the link use it; `false` gives none, and runs the browser headless.
8
+ */
9
+ readonly liveView?: 'view' | 'interact' | false;
10
+ /** Kernel's stealth mode, which also turns on its captcha solver; off by default. */
11
+ readonly stealth?: boolean;
12
+ /** Where browsers run: `us-east` (Kernel's default), `eu-west` or `ap-southeast`. */
13
+ readonly region?: 'us-east' | 'eu-west' | 'ap-southeast';
14
+ /**
15
+ * How long a browser waits once nothing is connected before Kernel deletes it, in seconds: 60 by default (10 to
16
+ * 259,200). It ends a browser whose release never came, such as when this process stops.
17
+ */
18
+ readonly standbyTimeoutSeconds?: number;
19
+ /** The longest lifetime; 24 hours by default. */
20
+ readonly maxLifetimeMs?: number;
21
+ /** For tests and proxies: the fetch to use. */
22
+ readonly fetch?: typeof fetch;
23
+ /** The API's address; `https://api.onkernel.com` by default. */
24
+ readonly baseUrl?: string;
25
+ }
26
+ /**
27
+ * Browsers from Kernel: hosted Chromium, driven over CDP from any runtime, with no dependency. Each browser is created
28
+ * when opened and deleted when released. Kernel keeps a browser running while it is connected, so its lifetime is kept
29
+ * by `createBrowsers`; a browser left without a connection is deleted after `standbyTimeoutSeconds`.
30
+ * Give the result to `createBrowsers` from `mayura/browser`.
31
+ */
32
+ export declare function kernelBrowsers(options: KernelBrowserOptions): BrowserProvider;
33
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAEgB,KAAK,eAAe,EAC1C,MAAM,gBAAgB,CAAC;AAExB,MAAM,WAAW,oBAAoB;IACnC,8DAA8D;IAC9D,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,UAAU,GAAG,KAAK,CAAC;IAChD,qFAAqF;IACrF,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;IAC3B,qFAAqF;IACrF,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,GAAG,SAAS,GAAG,cAAc,CAAC;IACzD;;;OAGG;IACH,QAAQ,CAAC,qBAAqB,CAAC,EAAE,MAAM,CAAC;IACxC,iDAAiD;IACjD,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,+CAA+C;IAC/C,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IAC9B,gEAAgE;IAChE,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;CAC3B;AAMD;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,oBAAoB,GAAG,eAAe,CAoD7E"}
package/dist/index.js ADDED
@@ -0,0 +1,84 @@
1
+ import { MayuraError } from 'mayura';
2
+ import { BrowserError, browserHttpFailure, browserResponseFailure, } from 'mayura/browser';
3
+ const regions = ['us-east', 'eu-west', 'ap-southeast'];
4
+ /** A CDP WebSocket over TLS, or plain only on this machine (a local proxy or a test). */
5
+ const secureSocket = /^(?:wss:\/\/|ws:\/\/(?:127\.0\.0\.1|localhost|\[::1\])[:/])/u;
6
+ /**
7
+ * Browsers from Kernel: hosted Chromium, driven over CDP from any runtime, with no dependency. Each browser is created
8
+ * when opened and deleted when released. Kernel keeps a browser running while it is connected, so its lifetime is kept
9
+ * by `createBrowsers`; a browser left without a connection is deleted after `standbyTimeoutSeconds`.
10
+ * Give the result to `createBrowsers` from `mayura/browser`.
11
+ */
12
+ export function kernelBrowsers(options) {
13
+ if (!options || typeof options.apiKey !== 'string' || !/^[!-~]{8,512}$/u.test(options.apiKey))
14
+ throw new MayuraError('INVALID_CONFIG', 'kernelBrowsers(): apiKey must be a Kernel API key.');
15
+ const liveView = options.liveView ?? 'view';
16
+ if (liveView !== 'view' && liveView !== 'interact' && liveView !== false)
17
+ throw new MayuraError('INVALID_CONFIG', "kernelBrowsers(): liveView is 'view', 'interact' or false.");
18
+ if (options.stealth !== undefined && typeof options.stealth !== 'boolean')
19
+ throw new MayuraError('INVALID_CONFIG', 'kernelBrowsers(): stealth must be a boolean.');
20
+ if (options.region !== undefined && !regions.includes(options.region))
21
+ throw new MayuraError('INVALID_CONFIG', `kernelBrowsers(): region is one of ${regions.join(', ')}.`);
22
+ const standby = options.standbyTimeoutSeconds ?? 60;
23
+ if (!Number.isSafeInteger(standby) || standby < 10 || standby > 259_200)
24
+ throw new MayuraError('INVALID_CONFIG', 'kernelBrowsers(): standbyTimeoutSeconds is 10 to 259,200.');
25
+ const maxLifetimeMs = options.maxLifetimeMs ?? 86_400_000;
26
+ if (!Number.isSafeInteger(maxLifetimeMs) || maxLifetimeMs < 1_000 || maxLifetimeMs > 259_200_000)
27
+ throw new MayuraError('INVALID_CONFIG', 'kernelBrowsers(): maxLifetimeMs is 1 s to 72 hours.');
28
+ if (options.fetch !== undefined && typeof options.fetch !== 'function')
29
+ throw new MayuraError('INVALID_CONFIG', 'kernelBrowsers(): fetch must be a function.');
30
+ const base = (() => {
31
+ try {
32
+ const url = new URL(options.baseUrl ?? 'https://api.onkernel.com');
33
+ if (url.protocol !== 'https:' && url.hostname !== '127.0.0.1' && url.hostname !== 'localhost')
34
+ throw new Error();
35
+ return url.origin;
36
+ }
37
+ catch {
38
+ throw new MayuraError('INVALID_CONFIG', 'kernelBrowsers(): baseUrl must be an https URL.');
39
+ }
40
+ })();
41
+ const fetcher = options.fetch ?? globalThis.fetch;
42
+ const headers = (json = false) => ({ authorization: `Bearer ${options.apiKey}`, ...(json ? { 'content-type': 'application/json' } : {}) });
43
+ const create = async (spec, { signal }) => {
44
+ const created = await fetcher(`${base}/browsers`, { method: 'POST', signal, headers: headers(true), body: JSON.stringify({
45
+ timeout_seconds: standby,
46
+ // Kernel's live view needs a browser with a screen.
47
+ headless: liveView === false,
48
+ stealth: options.stealth ?? false,
49
+ viewport: { width: spec.viewport.width, height: spec.viewport.height },
50
+ ...(options.region ? { region: options.region } : {}),
51
+ ...(Object.keys(spec.labels).length ? { tags: { ...spec.labels } } : {}),
52
+ }) });
53
+ if (!created.ok)
54
+ throw browserResponseFailure(created);
55
+ const browser = await created.json().catch(() => undefined);
56
+ if (typeof browser?.session_id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/u.test(browser.session_id) || typeof browser.cdp_ws_url !== 'string' || !secureSocket.test(browser.cdp_ws_url)) {
57
+ throw new BrowserError('invalid_response');
58
+ }
59
+ const id = browser.session_id;
60
+ let liveViewUrl;
61
+ // Without liveView, createBrowsers shows none (and a headless browser has none).
62
+ if (typeof browser.browser_live_view_url === 'string') {
63
+ try {
64
+ const view = new URL(browser.browser_live_view_url);
65
+ if (liveView === 'view')
66
+ view.searchParams.set('readOnly', 'true');
67
+ liveViewUrl = view.href;
68
+ }
69
+ catch { /* no live view */ }
70
+ }
71
+ return {
72
+ id, cdp: { url: browser.cdp_ws_url }, ...(liveViewUrl ? { liveViewUrl } : {}),
73
+ release: async ({ signal: callSignal }) => {
74
+ const reply = await fetcher(`${base}/browsers/${id}`, { method: 'DELETE', signal: callSignal, headers: headers() });
75
+ void reply.body?.cancel().catch(() => undefined);
76
+ // 404: deleted already, which createBrowsers counts as released.
77
+ if (!reply.ok)
78
+ throw browserHttpFailure(reply.status);
79
+ },
80
+ };
81
+ };
82
+ return Object.freeze({ id: 'kernel', features: Object.freeze({ liveView: liveView !== false }), maxLifetimeMs, create });
83
+ }
84
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,EACL,YAAY,EAAE,kBAAkB,EAAE,sBAAsB,GAEzD,MAAM,gBAAgB,CAAC;AA2BxB,MAAM,OAAO,GAAG,CAAC,SAAS,EAAE,SAAS,EAAE,cAAc,CAAU,CAAC;AAChE,yFAAyF;AACzF,MAAM,YAAY,GAAG,8DAA8D,CAAC;AAEpF;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,OAA6B;IAC1D,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,CAAC,MAAM,KAAK,QAAQ,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC;QAAE,MAAM,IAAI,WAAW,CAAC,gBAAgB,EAAE,oDAAoD,CAAC,CAAC;IAC7L,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,MAAM,CAAC;IAC5C,IAAI,QAAQ,KAAK,MAAM,IAAI,QAAQ,KAAK,UAAU,IAAI,QAAQ,KAAK,KAAK;QAAE,MAAM,IAAI,WAAW,CAAC,gBAAgB,EAAE,4DAA4D,CAAC,CAAC;IAChL,IAAI,OAAO,CAAC,OAAO,KAAK,SAAS,IAAI,OAAO,OAAO,CAAC,OAAO,KAAK,SAAS;QAAE,MAAM,IAAI,WAAW,CAAC,gBAAgB,EAAE,8CAA8C,CAAC,CAAC;IACnK,IAAI,OAAO,CAAC,MAAM,KAAK,SAAS,IAAI,CAAC,O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AE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC;gBACpH,KAAK,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;gBACjD,iEAAiE;gBACjE,IAAI,CAAC,KAAK,CAAC,EAAE;oBAAE,MAAM,kBAAkB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YACxD,CAAC;SACF,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,QAAQ,KAAK,KAAK,EAAE,CAAC,EAAE,aAAa,EAAE,MAAM,EAAE,CAAC,CAAC;AAC3H,CAAC","sourcesContent":["import { MayuraError } from 'mayura';\nimport {\n BrowserError, browserHttpFailure, browserResponseFailure,\n type BrowserBackend, type BrowserProvider, type ProviderBrowserSpec,\n} from 'mayura/browser';\n\nexport interface KernelBrowserOptions {\n /** A Kernel API key. Nothing is read from the environment. */\n readonly apiKey: string;\n /**\n * Give each browser a live view (`liveViewUrl`), a link with a token in it: `'view'` (the default) only shows the\n * browser; `'interact'` also lets whoever has the link use it; `false` gives none, and runs the browser headless.\n */\n readonly liveView?: 'view' | 'interact' | false;\n /** Kernel's stealth mode, which also turns on its captcha solver; off by default. */\n readonly stealth?: boolean;\n /** Where browsers run: `us-east` (Kernel's default), `eu-west` or `ap-southeast`. */\n readonly region?: 'us-east' | 'eu-west' | 'ap-southeast';\n /**\n * How long a browser waits once nothing is connected before Kernel deletes it, in seconds: 60 by default (10 to\n * 259,200). It ends a browser whose release never came, such as when this process stops.\n */\n readonly standbyTimeoutSeconds?: number;\n /** The longest lifetime; 24 hours by default. */\n readonly maxLifetimeMs?: number;\n /** For tests and proxies: the fetch to use. */\n readonly fetch?: typeof fetch;\n /** The API's address; `https://api.onkernel.com` by default. */\n readonly baseUrl?: string;\n}\n\nconst regions = ['us-east', 'eu-west', 'ap-southeast'] as const;\n/** A CDP WebSocket over TLS, or plain only on this machine (a local proxy or a test). */\nconst secureSocket = /^(?:wss:\\/\\/|ws:\\/\\/(?:127\\.0\\.0\\.1|localhost|\\[::1\\])[:/])/u;\n\n/**\n * Browsers from Kernel: hosted Chromium, driven over CDP from any runtime, with no dependency. Each browser is created\n * when opened and deleted when released. Kernel keeps a browser running while it is connected, so its lifetime is kept\n * by `createBrowsers`; a browser left without a connection is deleted after `standbyTimeoutSeconds`.\n * Give the result to `createBrowsers` from `mayura/browser`.\n */\nexport function kernelBrowsers(options: KernelBrowserOptions): BrowserProvider {\n if (!options || typeof options.apiKey !== 'string' || !/^[!-~]{8,512}$/u.test(options.apiKey)) throw new MayuraError('INVALID_CONFIG', 'kernelBrowsers(): apiKey must be a Kernel API key.');\n const liveView = options.liveView ?? 'view';\n if (liveView !== 'view' && liveView !== 'interact' && liveView !== false) throw new MayuraError('INVALID_CONFIG', \"kernelBrowsers(): liveView is 'view', 'interact' or false.\");\n if (options.stealth !== undefined && typeof options.stealth !== 'boolean') throw new MayuraError('INVALID_CONFIG', 'kernelBrowsers(): stealth must be a boolean.');\n if (options.region !== undefined && !regions.includes(options.region)) throw new MayuraError('INVALID_CONFIG', `kernelBrowsers(): region is one of ${regions.join(', ')}.`);\n const standby = options.standbyTimeoutSeconds ?? 60;\n if (!Number.isSafeInteger(standby) || standby < 10 || standby > 259_200) throw new MayuraError('INVALID_CONFIG', 'kernelBrowsers(): standbyTimeoutSeconds is 10 to 259,200.');\n const maxLifetimeMs = options.maxLifetimeMs ?? 86_400_000;\n if (!Number.isSafeInteger(maxLifetimeMs) || maxLifetimeMs < 1_000 || maxLifetimeMs > 259_200_000) throw new MayuraError('INVALID_CONFIG', 'kernelBrowsers(): maxLifetimeMs is 1 s to 72 hours.');\n if (options.fetch !== undefined && typeof options.fetch !== 'function') throw new MayuraError('INVALID_CONFIG', 'kernelBrowsers(): fetch must be a function.');\n const base = (() => {\n try { const url = new URL(options.baseUrl ?? 'https://api.onkernel.com'); if (url.protocol !== 'https:' && url.hostname !== '127.0.0.1' && url.hostname !== 'localhost') throw new Error(); return url.origin; }\n catch { throw new MayuraError('INVALID_CONFIG', 'kernelBrowsers(): baseUrl must be an https URL.'); }\n })();\n const fetcher = options.fetch ?? globalThis.fetch;\n const headers = (json = false) => ({ authorization: `Bearer ${options.apiKey}`, ...(json ? { 'content-type': 'application/json' } : {}) });\n\n const create = async (spec: ProviderBrowserSpec, { signal }: { readonly signal: AbortSignal }): Promise<BrowserBackend> => {\n const created = await fetcher(`${base}/browsers`, { method: 'POST', signal, headers: headers(true), body: JSON.stringify({\n timeout_seconds: standby,\n // Kernel's live view needs a browser with a screen.\n headless: liveView === false,\n stealth: options.stealth ?? false,\n viewport: { width: spec.viewport.width, height: spec.viewport.height },\n ...(options.region ? { region: options.region } : {}),\n ...(Object.keys(spec.labels).length ? { tags: { ...spec.labels } } : {}),\n }) });\n if (!created.ok) throw browserResponseFailure(created);\n const browser = await created.json().catch(() => undefined) as { session_id?: unknown; cdp_ws_url?: unknown; browser_live_view_url?: unknown } | undefined;\n if (typeof browser?.session_id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/u.test(browser.session_id) || typeof browser.cdp_ws_url !== 'string' || !secureSocket.test(browser.cdp_ws_url)) {\n throw new BrowserError('invalid_response');\n }\n const id = browser.session_id;\n let liveViewUrl: string | undefined;\n // Without liveView, createBrowsers shows none (and a headless browser has none).\n if (typeof browser.browser_live_view_url === 'string') {\n try { const view = new URL(browser.browser_live_view_url); if (liveView === 'view') view.searchParams.set('readOnly', 'true'); liveViewUrl = view.href; }\n catch { /* no live view */ }\n }\n return {\n id, cdp: { url: browser.cdp_ws_url }, ...(liveViewUrl ? { liveViewUrl } : {}),\n release: async ({ signal: callSignal }) => {\n const reply = await fetcher(`${base}/browsers/${id}`, { method: 'DELETE', signal: callSignal, headers: headers() });\n void reply.body?.cancel().catch(() => undefined);\n // 404: deleted already, which createBrowsers counts as released.\n if (!reply.ok) throw browserHttpFailure(reply.status);\n },\n };\n };\n\n return Object.freeze({ id: 'kernel', features: Object.freeze({ liveView: liveView !== false }), maxLifetimeMs, create });\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@mayurajs/browser-kernel",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "Kernel browsers for mayura/browser, over its browsers API.",
5
+ "author": {
6
+ "name": "Aryabh",
7
+ "email": "dev@rokad.co"
8
+ },
9
+ "license": "Apache-2.0",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/KartikeyAI/mayura.git",
13
+ "directory": "extensions/browser-kernel"
14
+ },
15
+ "homepage": "https://github.com/KartikeyAI/mayura#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/KartikeyAI/mayura/issues"
18
+ },
19
+ "type": "module",
20
+ "sideEffects": false,
21
+ "engines": {
22
+ "node": ">=22.12.0 <23 || >=24.14.1 <25"
23
+ },
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/index.js"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "src/**/*.ts",
33
+ "README.md",
34
+ "LICENSE",
35
+ "NOTICE"
36
+ ],
37
+ "dependencies": {},
38
+ "peerDependencies": {
39
+ "mayura": "^1.1.0"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public",
43
+ "provenance": true
44
+ }
45
+ }
package/src/index.ts ADDED
@@ -0,0 +1,94 @@
1
+ import { MayuraError } from 'mayura';
2
+ import {
3
+ BrowserError, browserHttpFailure, browserResponseFailure,
4
+ type BrowserBackend, type BrowserProvider, type ProviderBrowserSpec,
5
+ } from 'mayura/browser';
6
+
7
+ export interface KernelBrowserOptions {
8
+ /** A Kernel API key. Nothing is read from the environment. */
9
+ readonly apiKey: string;
10
+ /**
11
+ * Give each browser a live view (`liveViewUrl`), a link with a token in it: `'view'` (the default) only shows the
12
+ * browser; `'interact'` also lets whoever has the link use it; `false` gives none, and runs the browser headless.
13
+ */
14
+ readonly liveView?: 'view' | 'interact' | false;
15
+ /** Kernel's stealth mode, which also turns on its captcha solver; off by default. */
16
+ readonly stealth?: boolean;
17
+ /** Where browsers run: `us-east` (Kernel's default), `eu-west` or `ap-southeast`. */
18
+ readonly region?: 'us-east' | 'eu-west' | 'ap-southeast';
19
+ /**
20
+ * How long a browser waits once nothing is connected before Kernel deletes it, in seconds: 60 by default (10 to
21
+ * 259,200). It ends a browser whose release never came, such as when this process stops.
22
+ */
23
+ readonly standbyTimeoutSeconds?: number;
24
+ /** The longest lifetime; 24 hours by default. */
25
+ readonly maxLifetimeMs?: number;
26
+ /** For tests and proxies: the fetch to use. */
27
+ readonly fetch?: typeof fetch;
28
+ /** The API's address; `https://api.onkernel.com` by default. */
29
+ readonly baseUrl?: string;
30
+ }
31
+
32
+ const regions = ['us-east', 'eu-west', 'ap-southeast'] as const;
33
+ /** A CDP WebSocket over TLS, or plain only on this machine (a local proxy or a test). */
34
+ const secureSocket = /^(?:wss:\/\/|ws:\/\/(?:127\.0\.0\.1|localhost|\[::1\])[:/])/u;
35
+
36
+ /**
37
+ * Browsers from Kernel: hosted Chromium, driven over CDP from any runtime, with no dependency. Each browser is created
38
+ * when opened and deleted when released. Kernel keeps a browser running while it is connected, so its lifetime is kept
39
+ * by `createBrowsers`; a browser left without a connection is deleted after `standbyTimeoutSeconds`.
40
+ * Give the result to `createBrowsers` from `mayura/browser`.
41
+ */
42
+ export function kernelBrowsers(options: KernelBrowserOptions): BrowserProvider {
43
+ if (!options || typeof options.apiKey !== 'string' || !/^[!-~]{8,512}$/u.test(options.apiKey)) throw new MayuraError('INVALID_CONFIG', 'kernelBrowsers(): apiKey must be a Kernel API key.');
44
+ const liveView = options.liveView ?? 'view';
45
+ if (liveView !== 'view' && liveView !== 'interact' && liveView !== false) throw new MayuraError('INVALID_CONFIG', "kernelBrowsers(): liveView is 'view', 'interact' or false.");
46
+ if (options.stealth !== undefined && typeof options.stealth !== 'boolean') throw new MayuraError('INVALID_CONFIG', 'kernelBrowsers(): stealth must be a boolean.');
47
+ if (options.region !== undefined && !regions.includes(options.region)) throw new MayuraError('INVALID_CONFIG', `kernelBrowsers(): region is one of ${regions.join(', ')}.`);
48
+ const standby = options.standbyTimeoutSeconds ?? 60;
49
+ if (!Number.isSafeInteger(standby) || standby < 10 || standby > 259_200) throw new MayuraError('INVALID_CONFIG', 'kernelBrowsers(): standbyTimeoutSeconds is 10 to 259,200.');
50
+ const maxLifetimeMs = options.maxLifetimeMs ?? 86_400_000;
51
+ if (!Number.isSafeInteger(maxLifetimeMs) || maxLifetimeMs < 1_000 || maxLifetimeMs > 259_200_000) throw new MayuraError('INVALID_CONFIG', 'kernelBrowsers(): maxLifetimeMs is 1 s to 72 hours.');
52
+ if (options.fetch !== undefined && typeof options.fetch !== 'function') throw new MayuraError('INVALID_CONFIG', 'kernelBrowsers(): fetch must be a function.');
53
+ const base = (() => {
54
+ try { const url = new URL(options.baseUrl ?? 'https://api.onkernel.com'); if (url.protocol !== 'https:' && url.hostname !== '127.0.0.1' && url.hostname !== 'localhost') throw new Error(); return url.origin; }
55
+ catch { throw new MayuraError('INVALID_CONFIG', 'kernelBrowsers(): baseUrl must be an https URL.'); }
56
+ })();
57
+ const fetcher = options.fetch ?? globalThis.fetch;
58
+ const headers = (json = false) => ({ authorization: `Bearer ${options.apiKey}`, ...(json ? { 'content-type': 'application/json' } : {}) });
59
+
60
+ const create = async (spec: ProviderBrowserSpec, { signal }: { readonly signal: AbortSignal }): Promise<BrowserBackend> => {
61
+ const created = await fetcher(`${base}/browsers`, { method: 'POST', signal, headers: headers(true), body: JSON.stringify({
62
+ timeout_seconds: standby,
63
+ // Kernel's live view needs a browser with a screen.
64
+ headless: liveView === false,
65
+ stealth: options.stealth ?? false,
66
+ viewport: { width: spec.viewport.width, height: spec.viewport.height },
67
+ ...(options.region ? { region: options.region } : {}),
68
+ ...(Object.keys(spec.labels).length ? { tags: { ...spec.labels } } : {}),
69
+ }) });
70
+ if (!created.ok) throw browserResponseFailure(created);
71
+ const browser = await created.json().catch(() => undefined) as { session_id?: unknown; cdp_ws_url?: unknown; browser_live_view_url?: unknown } | undefined;
72
+ if (typeof browser?.session_id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/u.test(browser.session_id) || typeof browser.cdp_ws_url !== 'string' || !secureSocket.test(browser.cdp_ws_url)) {
73
+ throw new BrowserError('invalid_response');
74
+ }
75
+ const id = browser.session_id;
76
+ let liveViewUrl: string | undefined;
77
+ // Without liveView, createBrowsers shows none (and a headless browser has none).
78
+ if (typeof browser.browser_live_view_url === 'string') {
79
+ try { const view = new URL(browser.browser_live_view_url); if (liveView === 'view') view.searchParams.set('readOnly', 'true'); liveViewUrl = view.href; }
80
+ catch { /* no live view */ }
81
+ }
82
+ return {
83
+ id, cdp: { url: browser.cdp_ws_url }, ...(liveViewUrl ? { liveViewUrl } : {}),
84
+ release: async ({ signal: callSignal }) => {
85
+ const reply = await fetcher(`${base}/browsers/${id}`, { method: 'DELETE', signal: callSignal, headers: headers() });
86
+ void reply.body?.cancel().catch(() => undefined);
87
+ // 404: deleted already, which createBrowsers counts as released.
88
+ if (!reply.ok) throw browserHttpFailure(reply.status);
89
+ },
90
+ };
91
+ };
92
+
93
+ return Object.freeze({ id: 'kernel', features: Object.freeze({ liveView: liveView !== false }), maxLifetimeMs, create });
94
+ }