@mayurajs/browser-anchor 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 +201 -0
- package/NOTICE +8 -0
- package/README.md +37 -2
- package/dist/index.d.ts +32 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +87 -0
- package/dist/index.js.map +1 -0
- package/package.json +43 -4
- package/src/index.ts +103 -0
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,38 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mayurajs/browser-anchor
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[Anchor Browser](https://docs.anchorbrowser.io) browsers for `mayura/browser`: hosted Chromium sessions, created over
|
|
4
|
+
Anchor's sessions API and driven over CDP, from any runtime, with no dependency.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
npm install mayura @mayurajs/browser-anchor
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { createBrowsers } from 'mayura/browser';
|
|
12
|
+
import { anchorBrowsers } from '@mayurajs/browser-anchor';
|
|
13
|
+
|
|
14
|
+
const browsers = createBrowsers(anchorBrowsers({ 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 a session: created when opened, ended when released. Anchor ends it at its lifetime, given as its
|
|
24
|
+
maximum duration in whole minutes (Anchor's docs disagree on its default, so it is always given), and
|
|
25
|
+
`idleTimeoutMinutes` (1 by default) after nothing is connected, such as when this process stops.
|
|
26
|
+
- **Recording and ad blocking are off**, though Anchor's own defaults are on; turn them on with `recording` and
|
|
27
|
+
`adblock`. No proxy and no captcha solving. Labels become the session's tags, as `key=value`.
|
|
28
|
+
- `liveViewUrl` is Anchor's live view: by default it only shows the session (`liveView: 'view'`); `'interact'` lets
|
|
29
|
+
whoever has the link use it too, and `false` gives none and runs the browser headless.
|
|
30
|
+
- Anchor answers ending a session it no longer has with "invalid API key or session id" (401). Since the key worked
|
|
31
|
+
when the session was created, that counts as already ended.
|
|
32
|
+
- Anchor's CDP URL carries the API key: treat it as a secret; Mayura never logs it.
|
|
33
|
+
- Origins are enforced inside the browser, by intercepting its requests over CDP. This has not yet been tried against
|
|
34
|
+
Anchor itself: should its connection not allow that, opening a browser fails rather than running unchecked.
|
|
35
|
+
- Options: `apiKey`, `liveView`, `adblock`, `recording`, `idleTimeoutMinutes`, `maxLifetimeMs` (24 hours), `fetch`,
|
|
36
|
+
`baseUrl`.
|
|
37
|
+
|
|
38
|
+
See the [browser guide](https://mayurajs.com/docs/guides/browsers/). Apache-2.0.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type BrowserProvider } from 'mayura/browser';
|
|
2
|
+
export interface AnchorBrowserOptions {
|
|
3
|
+
/** An Anchor Browser API key. Nothing is read from the environment. */
|
|
4
|
+
readonly apiKey: string;
|
|
5
|
+
/**
|
|
6
|
+
* Give each browser a live view (`liveViewUrl`): `'view'` (the default) only shows the session; `'interact'` also
|
|
7
|
+
* lets whoever has the link use it; `false` gives none and runs the browser headless.
|
|
8
|
+
*/
|
|
9
|
+
readonly liveView?: 'view' | 'interact' | false;
|
|
10
|
+
/** Block ads; off here, though Anchor's own default is on. */
|
|
11
|
+
readonly adblock?: boolean;
|
|
12
|
+
/** Record sessions; off here, though Anchor's own default is on. */
|
|
13
|
+
readonly recording?: boolean;
|
|
14
|
+
/**
|
|
15
|
+
* How long a session waits once nothing is connected before Anchor ends it, in minutes: 1 by default. It ends a
|
|
16
|
+
* session whose release never came, such as when this process stops.
|
|
17
|
+
*/
|
|
18
|
+
readonly idleTimeoutMinutes?: 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.anchorbrowser.io` by default. */
|
|
24
|
+
readonly baseUrl?: string;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Browsers as Anchor Browser sessions: hosted Chromium, driven over CDP from any runtime, with no dependency. Each
|
|
28
|
+
* browser is a session created when opened and ended when released; Anchor ends it at its lifetime, or soon after
|
|
29
|
+
* nothing is connected, too. Give the result to `createBrowsers` from `mayura/browser`.
|
|
30
|
+
*/
|
|
31
|
+
export declare function anchorBrowsers(options: AnchorBrowserOptions): BrowserProvider;
|
|
32
|
+
//# 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,uEAAuE;IACvE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,UAAU,GAAG,KAAK,CAAC;IAChD,8DAA8D;IAC9D,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;IAC3B,oEAAoE;IACpE,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC;IAC7B;;;OAGG;IACH,QAAQ,CAAC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IACrC,iDAAiD;IACjD,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,+CAA+C;IAC/C,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IAC9B,oEAAoE;IACpE,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;CAC3B;AAKD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,oBAAoB,GAAG,eAAe,CA+D7E"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { MayuraError } from 'mayura';
|
|
2
|
+
import { BrowserError, browserHttpFailure, browserResponseFailure, } from 'mayura/browser';
|
|
3
|
+
/** A CDP WebSocket over TLS, or plain only on this machine (a local proxy or a test). */
|
|
4
|
+
const secureSocket = /^(?:wss:\/\/|ws:\/\/(?:127\.0\.0\.1|localhost|\[::1\])[:/])/u;
|
|
5
|
+
/**
|
|
6
|
+
* Browsers as Anchor Browser sessions: hosted Chromium, driven over CDP from any runtime, with no dependency. Each
|
|
7
|
+
* browser is a session created when opened and ended when released; Anchor ends it at its lifetime, or soon after
|
|
8
|
+
* nothing is connected, too. Give the result to `createBrowsers` from `mayura/browser`.
|
|
9
|
+
*/
|
|
10
|
+
export function anchorBrowsers(options) {
|
|
11
|
+
if (!options || typeof options.apiKey !== 'string' || !/^[!-~]{8,512}$/u.test(options.apiKey))
|
|
12
|
+
throw new MayuraError('INVALID_CONFIG', 'anchorBrowsers(): apiKey must be an Anchor Browser API key.');
|
|
13
|
+
const liveView = options.liveView ?? 'view';
|
|
14
|
+
if (liveView !== 'view' && liveView !== 'interact' && liveView !== false)
|
|
15
|
+
throw new MayuraError('INVALID_CONFIG', "anchorBrowsers(): liveView is 'view', 'interact' or false.");
|
|
16
|
+
for (const flag of ['adblock', 'recording']) {
|
|
17
|
+
if (options[flag] !== undefined && typeof options[flag] !== 'boolean')
|
|
18
|
+
throw new MayuraError('INVALID_CONFIG', `anchorBrowsers(): ${flag} must be a boolean.`);
|
|
19
|
+
}
|
|
20
|
+
const idle = options.idleTimeoutMinutes ?? 1;
|
|
21
|
+
if (!Number.isSafeInteger(idle) || idle < 1 || idle > 1_440)
|
|
22
|
+
throw new MayuraError('INVALID_CONFIG', 'anchorBrowsers(): idleTimeoutMinutes is 1 to 1,440.');
|
|
23
|
+
const maxLifetimeMs = options.maxLifetimeMs ?? 86_400_000;
|
|
24
|
+
// createBrowsers keeps lifetimes within what its timers reach.
|
|
25
|
+
if (!Number.isSafeInteger(maxLifetimeMs) || maxLifetimeMs < 60_000)
|
|
26
|
+
throw new MayuraError('INVALID_CONFIG', 'anchorBrowsers(): maxLifetimeMs is at least 1 minute.');
|
|
27
|
+
if (options.fetch !== undefined && typeof options.fetch !== 'function')
|
|
28
|
+
throw new MayuraError('INVALID_CONFIG', 'anchorBrowsers(): fetch must be a function.');
|
|
29
|
+
const base = (() => {
|
|
30
|
+
try {
|
|
31
|
+
const url = new URL(options.baseUrl ?? 'https://api.anchorbrowser.io');
|
|
32
|
+
if (url.protocol !== 'https:' && url.hostname !== '127.0.0.1' && url.hostname !== 'localhost')
|
|
33
|
+
throw new Error();
|
|
34
|
+
return url.origin;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
throw new MayuraError('INVALID_CONFIG', 'anchorBrowsers(): baseUrl must be an https URL.');
|
|
38
|
+
}
|
|
39
|
+
})();
|
|
40
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
41
|
+
const headers = (json = false) => ({ 'anchor-api-key': options.apiKey, ...(json ? { 'content-type': 'application/json' } : {}) });
|
|
42
|
+
const create = async (spec, { signal }) => {
|
|
43
|
+
const created = await fetcher(`${base}/v1/sessions`, { method: 'POST', signal, headers: headers(true), body: JSON.stringify({
|
|
44
|
+
session: {
|
|
45
|
+
// Anchor ends the session at its maximum duration, should a release never come; its docs disagree on the
|
|
46
|
+
// default, so it is always given.
|
|
47
|
+
timeout: { max_duration: Math.ceil(spec.lifetimeMs / 60_000), idle_timeout: idle },
|
|
48
|
+
recording: { active: options.recording ?? false },
|
|
49
|
+
proxy: { active: false },
|
|
50
|
+
...(liveView ? { live_view: { read_only: liveView === 'view' } } : {}),
|
|
51
|
+
...(Object.keys(spec.labels).length ? { tags: Object.entries(spec.labels).map(([key, value]) => `${key}=${value}`) } : {}),
|
|
52
|
+
},
|
|
53
|
+
browser: {
|
|
54
|
+
viewport: { width: spec.viewport.width, height: spec.viewport.height },
|
|
55
|
+
adblock: { active: options.adblock ?? false },
|
|
56
|
+
// Anchor turns its popup blocker on by default, and refuses it without the ad blocker: it follows adblock.
|
|
57
|
+
popup_blocker: { active: options.adblock ?? false },
|
|
58
|
+
captcha_solver: { active: false },
|
|
59
|
+
// Anchor's live view needs a browser with a screen.
|
|
60
|
+
headless: { active: liveView === false },
|
|
61
|
+
},
|
|
62
|
+
}) });
|
|
63
|
+
if (!created.ok)
|
|
64
|
+
throw browserResponseFailure(created);
|
|
65
|
+
const session = (await created.json().catch(() => undefined))?.data;
|
|
66
|
+
if (typeof session?.id !== 'string' || !/^[A-Za-z0-9-]{1,128}$/u.test(session.id) || typeof session.cdp_url !== 'string' || !secureSocket.test(session.cdp_url)) {
|
|
67
|
+
throw new BrowserError('invalid_response');
|
|
68
|
+
}
|
|
69
|
+
const id = session.id;
|
|
70
|
+
return {
|
|
71
|
+
id, cdp: { url: session.cdp_url },
|
|
72
|
+
// Without liveView, createBrowsers shows no live view.
|
|
73
|
+
...(typeof session.live_view_url === 'string' ? { liveViewUrl: session.live_view_url } : {}),
|
|
74
|
+
release: async ({ signal: callSignal }) => {
|
|
75
|
+
const reply = await fetcher(`${base}/v1/sessions/${id}`, { method: 'DELETE', signal: callSignal, headers: headers() });
|
|
76
|
+
void reply.body?.cancel().catch(() => undefined);
|
|
77
|
+
if (reply.ok)
|
|
78
|
+
return;
|
|
79
|
+
// Anchor answers a session it no longer has as "invalid API key or session id" (401); the key worked when the
|
|
80
|
+
// session was created, so that is a session already ended.
|
|
81
|
+
throw browserHttpFailure(reply.status === 401 ? 404 : reply.status);
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
};
|
|
85
|
+
return Object.freeze({ id: 'anchor', features: Object.freeze({ liveView: liveView !== false }), maxLifetimeMs, create });
|
|
86
|
+
}
|
|
87
|
+
//# 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,yFAAyF;AACzF,MAAM,YAAY,GAAG,8DAA8D,CAAC;AAEpF;;;;GAIG;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,6DAA6D,CAAC,CAAC;IACtM,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,MAAM,CAAC;IAC5C,IAAI,QAAQ,KAAK,MAAM,IAAI,QAAQ,KAAK,UAAU,IAAI,QAAQ,KAA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AAC,CAAC;QAC7C,CAAC;QACD,MAAM,EAAE,GAAG,OAAO,CAAC,EAAE,CAAC;QACtB,OAAO;YACL,EAAE,EAAE,GAAG,EAAE,EAAE,GAAG,EAAE,OAAO,CAAC,OAAO,EAAE;YACjC,uDAAuD;YACvD,GAAG,CAAC,OAAO,OAAO,CAAC,aAAa,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC5F,OAAO,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE,EAAE;gBACxC,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC,GAAG,IAAI,gBAAgB,EAAE,EAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC;gBACvH,KAAK,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;gBACjD,IAAI,KAAK,CAAC,EAAE;oBAAE,OAAO;gBACrB,8GAA8G;gBAC9G,2DAA2D;gBAC3D,MAAM,kBAAkB,CAAC,KAAK,CAAC,MAAM,KAAK,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YACtE,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 AnchorBrowserOptions {\n /** An Anchor Browser API key. Nothing is read from the environment. */\n readonly apiKey: string;\n /**\n * Give each browser a live view (`liveViewUrl`): `'view'` (the default) only shows the session; `'interact'` also\n * lets whoever has the link use it; `false` gives none and runs the browser headless.\n */\n readonly liveView?: 'view' | 'interact' | false;\n /** Block ads; off here, though Anchor's own default is on. */\n readonly adblock?: boolean;\n /** Record sessions; off here, though Anchor's own default is on. */\n readonly recording?: boolean;\n /**\n * How long a session waits once nothing is connected before Anchor ends it, in minutes: 1 by default. It ends a\n * session whose release never came, such as when this process stops.\n */\n readonly idleTimeoutMinutes?: 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.anchorbrowser.io` by default. */\n readonly baseUrl?: string;\n}\n\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 as Anchor Browser sessions: hosted Chromium, driven over CDP from any runtime, with no dependency. Each\n * browser is a session created when opened and ended when released; Anchor ends it at its lifetime, or soon after\n * nothing is connected, too. Give the result to `createBrowsers` from `mayura/browser`.\n */\nexport function anchorBrowsers(options: AnchorBrowserOptions): BrowserProvider {\n if (!options || typeof options.apiKey !== 'string' || !/^[!-~]{8,512}$/u.test(options.apiKey)) throw new MayuraError('INVALID_CONFIG', 'anchorBrowsers(): apiKey must be an Anchor Browser API key.');\n const liveView = options.liveView ?? 'view';\n if (liveView !== 'view' && liveView !== 'interact' && liveView !== false) throw new MayuraError('INVALID_CONFIG', \"anchorBrowsers(): liveView is 'view', 'interact' or false.\");\n for (const flag of ['adblock', 'recording'] as const) {\n if (options[flag] !== undefined && typeof options[flag] !== 'boolean') throw new MayuraError('INVALID_CONFIG', `anchorBrowsers(): ${flag} must be a boolean.`);\n }\n const idle = options.idleTimeoutMinutes ?? 1;\n if (!Number.isSafeInteger(idle) || idle < 1 || idle > 1_440) throw new MayuraError('INVALID_CONFIG', 'anchorBrowsers(): idleTimeoutMinutes is 1 to 1,440.');\n const maxLifetimeMs = options.maxLifetimeMs ?? 86_400_000;\n // createBrowsers keeps lifetimes within what its timers reach.\n if (!Number.isSafeInteger(maxLifetimeMs) || maxLifetimeMs < 60_000) throw new MayuraError('INVALID_CONFIG', 'anchorBrowsers(): maxLifetimeMs is at least 1 minute.');\n if (options.fetch !== undefined && typeof options.fetch !== 'function') throw new MayuraError('INVALID_CONFIG', 'anchorBrowsers(): fetch must be a function.');\n const base = (() => {\n try { const url = new URL(options.baseUrl ?? 'https://api.anchorbrowser.io'); 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', 'anchorBrowsers(): baseUrl must be an https URL.'); }\n })();\n const fetcher = options.fetch ?? globalThis.fetch;\n const headers = (json = false) => ({ 'anchor-api-key': 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}/v1/sessions`, { method: 'POST', signal, headers: headers(true), body: JSON.stringify({\n session: {\n // Anchor ends the session at its maximum duration, should a release never come; its docs disagree on the\n // default, so it is always given.\n timeout: { max_duration: Math.ceil(spec.lifetimeMs / 60_000), idle_timeout: idle },\n recording: { active: options.recording ?? false },\n proxy: { active: false },\n ...(liveView ? { live_view: { read_only: liveView === 'view' } } : {}),\n ...(Object.keys(spec.labels).length ? { tags: Object.entries(spec.labels).map(([key, value]) => `${key}=${value}`) } : {}),\n },\n browser: {\n viewport: { width: spec.viewport.width, height: spec.viewport.height },\n adblock: { active: options.adblock ?? false },\n // Anchor turns its popup blocker on by default, and refuses it without the ad blocker: it follows adblock.\n popup_blocker: { active: options.adblock ?? false },\n captcha_solver: { active: false },\n // Anchor's live view needs a browser with a screen.\n headless: { active: liveView === false },\n },\n }) });\n if (!created.ok) throw browserResponseFailure(created);\n const session = (await created.json().catch(() => undefined) as { data?: { id?: unknown; cdp_url?: unknown; live_view_url?: unknown } } | undefined)?.data;\n if (typeof session?.id !== 'string' || !/^[A-Za-z0-9-]{1,128}$/u.test(session.id) || typeof session.cdp_url !== 'string' || !secureSocket.test(session.cdp_url)) {\n throw new BrowserError('invalid_response');\n }\n const id = session.id;\n return {\n id, cdp: { url: session.cdp_url },\n // Without liveView, createBrowsers shows no live view.\n ...(typeof session.live_view_url === 'string' ? { liveViewUrl: session.live_view_url } : {}),\n release: async ({ signal: callSignal }) => {\n const reply = await fetcher(`${base}/v1/sessions/${id}`, { method: 'DELETE', signal: callSignal, headers: headers() });\n void reply.body?.cancel().catch(() => undefined);\n if (reply.ok) return;\n // Anchor answers a session it no longer has as \"invalid API key or session id\" (401); the key worked when the\n // session was created, so that is a session already ended.\n throw browserHttpFailure(reply.status === 401 ? 404 : reply.status);\n },\n };\n };\n\n return Object.freeze({ id: 'anchor', 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-anchor",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Anchor Browser browsers for mayura/browser, over its sessions 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-anchor"
|
|
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,103 @@
|
|
|
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 AnchorBrowserOptions {
|
|
8
|
+
/** An Anchor Browser API key. Nothing is read from the environment. */
|
|
9
|
+
readonly apiKey: string;
|
|
10
|
+
/**
|
|
11
|
+
* Give each browser a live view (`liveViewUrl`): `'view'` (the default) only shows the session; `'interact'` also
|
|
12
|
+
* lets whoever has the link use it; `false` gives none and runs the browser headless.
|
|
13
|
+
*/
|
|
14
|
+
readonly liveView?: 'view' | 'interact' | false;
|
|
15
|
+
/** Block ads; off here, though Anchor's own default is on. */
|
|
16
|
+
readonly adblock?: boolean;
|
|
17
|
+
/** Record sessions; off here, though Anchor's own default is on. */
|
|
18
|
+
readonly recording?: boolean;
|
|
19
|
+
/**
|
|
20
|
+
* How long a session waits once nothing is connected before Anchor ends it, in minutes: 1 by default. It ends a
|
|
21
|
+
* session whose release never came, such as when this process stops.
|
|
22
|
+
*/
|
|
23
|
+
readonly idleTimeoutMinutes?: 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.anchorbrowser.io` by default. */
|
|
29
|
+
readonly baseUrl?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** A CDP WebSocket over TLS, or plain only on this machine (a local proxy or a test). */
|
|
33
|
+
const secureSocket = /^(?:wss:\/\/|ws:\/\/(?:127\.0\.0\.1|localhost|\[::1\])[:/])/u;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Browsers as Anchor Browser sessions: hosted Chromium, driven over CDP from any runtime, with no dependency. Each
|
|
37
|
+
* browser is a session created when opened and ended when released; Anchor ends it at its lifetime, or soon after
|
|
38
|
+
* nothing is connected, too. Give the result to `createBrowsers` from `mayura/browser`.
|
|
39
|
+
*/
|
|
40
|
+
export function anchorBrowsers(options: AnchorBrowserOptions): BrowserProvider {
|
|
41
|
+
if (!options || typeof options.apiKey !== 'string' || !/^[!-~]{8,512}$/u.test(options.apiKey)) throw new MayuraError('INVALID_CONFIG', 'anchorBrowsers(): apiKey must be an Anchor Browser API key.');
|
|
42
|
+
const liveView = options.liveView ?? 'view';
|
|
43
|
+
if (liveView !== 'view' && liveView !== 'interact' && liveView !== false) throw new MayuraError('INVALID_CONFIG', "anchorBrowsers(): liveView is 'view', 'interact' or false.");
|
|
44
|
+
for (const flag of ['adblock', 'recording'] as const) {
|
|
45
|
+
if (options[flag] !== undefined && typeof options[flag] !== 'boolean') throw new MayuraError('INVALID_CONFIG', `anchorBrowsers(): ${flag} must be a boolean.`);
|
|
46
|
+
}
|
|
47
|
+
const idle = options.idleTimeoutMinutes ?? 1;
|
|
48
|
+
if (!Number.isSafeInteger(idle) || idle < 1 || idle > 1_440) throw new MayuraError('INVALID_CONFIG', 'anchorBrowsers(): idleTimeoutMinutes is 1 to 1,440.');
|
|
49
|
+
const maxLifetimeMs = options.maxLifetimeMs ?? 86_400_000;
|
|
50
|
+
// createBrowsers keeps lifetimes within what its timers reach.
|
|
51
|
+
if (!Number.isSafeInteger(maxLifetimeMs) || maxLifetimeMs < 60_000) throw new MayuraError('INVALID_CONFIG', 'anchorBrowsers(): maxLifetimeMs is at least 1 minute.');
|
|
52
|
+
if (options.fetch !== undefined && typeof options.fetch !== 'function') throw new MayuraError('INVALID_CONFIG', 'anchorBrowsers(): fetch must be a function.');
|
|
53
|
+
const base = (() => {
|
|
54
|
+
try { const url = new URL(options.baseUrl ?? 'https://api.anchorbrowser.io'); 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', 'anchorBrowsers(): baseUrl must be an https URL.'); }
|
|
56
|
+
})();
|
|
57
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
58
|
+
const headers = (json = false) => ({ 'anchor-api-key': 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}/v1/sessions`, { method: 'POST', signal, headers: headers(true), body: JSON.stringify({
|
|
62
|
+
session: {
|
|
63
|
+
// Anchor ends the session at its maximum duration, should a release never come; its docs disagree on the
|
|
64
|
+
// default, so it is always given.
|
|
65
|
+
timeout: { max_duration: Math.ceil(spec.lifetimeMs / 60_000), idle_timeout: idle },
|
|
66
|
+
recording: { active: options.recording ?? false },
|
|
67
|
+
proxy: { active: false },
|
|
68
|
+
...(liveView ? { live_view: { read_only: liveView === 'view' } } : {}),
|
|
69
|
+
...(Object.keys(spec.labels).length ? { tags: Object.entries(spec.labels).map(([key, value]) => `${key}=${value}`) } : {}),
|
|
70
|
+
},
|
|
71
|
+
browser: {
|
|
72
|
+
viewport: { width: spec.viewport.width, height: spec.viewport.height },
|
|
73
|
+
adblock: { active: options.adblock ?? false },
|
|
74
|
+
// Anchor turns its popup blocker on by default, and refuses it without the ad blocker: it follows adblock.
|
|
75
|
+
popup_blocker: { active: options.adblock ?? false },
|
|
76
|
+
captcha_solver: { active: false },
|
|
77
|
+
// Anchor's live view needs a browser with a screen.
|
|
78
|
+
headless: { active: liveView === false },
|
|
79
|
+
},
|
|
80
|
+
}) });
|
|
81
|
+
if (!created.ok) throw browserResponseFailure(created);
|
|
82
|
+
const session = (await created.json().catch(() => undefined) as { data?: { id?: unknown; cdp_url?: unknown; live_view_url?: unknown } } | undefined)?.data;
|
|
83
|
+
if (typeof session?.id !== 'string' || !/^[A-Za-z0-9-]{1,128}$/u.test(session.id) || typeof session.cdp_url !== 'string' || !secureSocket.test(session.cdp_url)) {
|
|
84
|
+
throw new BrowserError('invalid_response');
|
|
85
|
+
}
|
|
86
|
+
const id = session.id;
|
|
87
|
+
return {
|
|
88
|
+
id, cdp: { url: session.cdp_url },
|
|
89
|
+
// Without liveView, createBrowsers shows no live view.
|
|
90
|
+
...(typeof session.live_view_url === 'string' ? { liveViewUrl: session.live_view_url } : {}),
|
|
91
|
+
release: async ({ signal: callSignal }) => {
|
|
92
|
+
const reply = await fetcher(`${base}/v1/sessions/${id}`, { method: 'DELETE', signal: callSignal, headers: headers() });
|
|
93
|
+
void reply.body?.cancel().catch(() => undefined);
|
|
94
|
+
if (reply.ok) return;
|
|
95
|
+
// Anchor answers a session it no longer has as "invalid API key or session id" (401); the key worked when the
|
|
96
|
+
// session was created, so that is a session already ended.
|
|
97
|
+
throw browserHttpFailure(reply.status === 401 ? 404 : reply.status);
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
return Object.freeze({ id: 'anchor', features: Object.freeze({ liveView: liveView !== false }), maxLifetimeMs, create });
|
|
103
|
+
}
|