@mayurajs/cloudflare-quick-action 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 +50 -2
- package/dist/client.d.ts +93 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +134 -0
- package/dist/client.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/tools.d.ts +42 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/tools.js +197 -0
- package/dist/tools.js.map +1 -0
- package/package.json +43 -4
- package/src/client.ts +162 -0
- package/src/index.ts +4 -0
- package/src/tools.ts +201 -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,51 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mayurajs/cloudflare-quick-action
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[Cloudflare Browser Run](https://developers.cloudflare.com/browser-run/quick-actions/)'s quick actions for Mayura —
|
|
4
|
+
one call renders a page in Cloudflare's browser and gives back what was asked for — as a client and as tools, from
|
|
5
|
+
any runtime with no dependency.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install mayura @mayurajs/cloudflare-quick-action
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { cloudflareQuickActions, quickActionTools } from '@mayurajs/cloudflare-quick-action';
|
|
13
|
+
|
|
14
|
+
const actions = cloudflareQuickActions({ accountId, apiToken });
|
|
15
|
+
const markdown = await actions.markdown({ url: 'https://example.com/' });
|
|
16
|
+
|
|
17
|
+
const tools = quickActionTools(actions, { origins: ['https://docs.example.com'], screenshot: true });
|
|
18
|
+
// cloudflare.markdown, cloudflare.links, cloudflare.scrape and cloudflare.screenshot, permission web:cloudflare:read.
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
`apiToken` needs the **Browser Rendering - Edit** permission.
|
|
22
|
+
|
|
23
|
+
## The client
|
|
24
|
+
|
|
25
|
+
`cloudflareQuickActions({ accountId, apiToken })` has `markdown`, `content` (the rendered HTML), `links`, `scrape`
|
|
26
|
+
(elements by CSS selector), `screenshot` (PNG), `pdf`, `json` (structured data by Cloudflare's model, billed as Workers
|
|
27
|
+
AI), and `crawl.start`, `crawl.status` and `crawl.cancel`. Each takes the page's `url`, and optionally
|
|
28
|
+
`allowRequestPattern`: regular expressions, outside which the page loads nothing. A failure names only its HTTP
|
|
29
|
+
status, never what Cloudflare wrote.
|
|
30
|
+
|
|
31
|
+
## Tools
|
|
32
|
+
|
|
33
|
+
| Tool | Permission | Option |
|
|
34
|
+
| --- | --- | --- |
|
|
35
|
+
| `<name>.markdown`, `<name>.links`, `<name>.scrape` | `web:<name>:read` | always |
|
|
36
|
+
| `<name>.screenshot`: the page as an image | `web:<name>:read` | `screenshot: true` |
|
|
37
|
+
| `<name>.json`: structured data, by prompt and optional JSON Schema | `web:<name>:extract` | `json: true` |
|
|
38
|
+
| `<name>.crawl`: up to `maxCrawlPages` pages of a site, as markdown | `web:<name>:crawl` | `crawl: true` |
|
|
39
|
+
|
|
40
|
+
- **`origins` is required**: the sites the tools may read, as `createBrowsers` takes them, or `'all'`. A URL outside
|
|
41
|
+
them is refused, and comes back as the tool's result so the model can choose another. The page Cloudflare renders
|
|
42
|
+
is also kept to them: it loads no scripts, images or frames from elsewhere (`allowRequestPattern`).
|
|
43
|
+
- A crawl stays on its site, polls until done, keeps only pages read within `origins`, and is cancelled when its call
|
|
44
|
+
is or after `crawlTimeoutMs` (5 minutes), so it stops spending.
|
|
45
|
+
- Content is cut at `maxPageBytes` (64 KiB). `costMicros` charges each tool's calls to the run's budget; Cloudflare
|
|
46
|
+
bills browser time on its side (its free plan allows 10 browser-minutes a day, and REST calls slowly).
|
|
47
|
+
- Page content is the tools' result for the model to read: treat it as untrusted text.
|
|
48
|
+
- Options: `name` (`cloudflare`), `origins`, `screenshot`, `json`, `crawl`, `maxPageBytes`, `maxCrawlPages` (10, at most
|
|
49
|
+
100), `crawlTimeoutMs`, `costMicros`.
|
|
50
|
+
|
|
51
|
+
For a browser to drive, see `@mayurajs/browser-cloudflare`. Apache-2.0.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
export interface QuickActionsOptions {
|
|
2
|
+
/** Your Cloudflare account id (32 hex characters). */
|
|
3
|
+
readonly accountId: string;
|
|
4
|
+
/** A Cloudflare API token with the "Browser Rendering - Edit" permission. Nothing is read from the environment. */
|
|
5
|
+
readonly apiToken: string;
|
|
6
|
+
/** For tests and proxies: the fetch to use. */
|
|
7
|
+
readonly fetch?: typeof fetch;
|
|
8
|
+
/** The API's address; `https://api.cloudflare.com` by default. */
|
|
9
|
+
readonly baseUrl?: string;
|
|
10
|
+
}
|
|
11
|
+
/** What every action renders: a page, and optionally only the requests it may make. */
|
|
12
|
+
export interface PageRequest {
|
|
13
|
+
readonly url: string;
|
|
14
|
+
/** Regular expressions: the page loads only what matches one. */
|
|
15
|
+
readonly allowRequestPattern?: readonly string[];
|
|
16
|
+
}
|
|
17
|
+
export interface CallOptions {
|
|
18
|
+
readonly signal?: AbortSignal;
|
|
19
|
+
}
|
|
20
|
+
export interface ScrapedElement {
|
|
21
|
+
readonly text: string;
|
|
22
|
+
readonly html: string;
|
|
23
|
+
readonly attributes: readonly {
|
|
24
|
+
readonly name: string;
|
|
25
|
+
readonly value: string;
|
|
26
|
+
}[];
|
|
27
|
+
}
|
|
28
|
+
export interface CrawlStart {
|
|
29
|
+
readonly url: string;
|
|
30
|
+
/** Pages to read; 10 by default. */
|
|
31
|
+
readonly limit?: number;
|
|
32
|
+
readonly depth?: number;
|
|
33
|
+
readonly formats?: readonly ('markdown' | 'html')[];
|
|
34
|
+
readonly includePatterns?: readonly string[];
|
|
35
|
+
readonly excludePatterns?: readonly string[];
|
|
36
|
+
readonly allowRequestPattern?: readonly string[];
|
|
37
|
+
}
|
|
38
|
+
export type CrawlStatus = 'running' | 'completed' | 'errored' | 'cancelled_due_to_timeout' | 'cancelled_due_to_limits' | 'cancelled_by_user';
|
|
39
|
+
export interface CrawlRecord {
|
|
40
|
+
readonly url: string;
|
|
41
|
+
readonly status: string;
|
|
42
|
+
readonly markdown?: string;
|
|
43
|
+
readonly html?: string;
|
|
44
|
+
readonly title?: string;
|
|
45
|
+
readonly httpStatus?: number;
|
|
46
|
+
}
|
|
47
|
+
export interface CrawlResult {
|
|
48
|
+
readonly id: string;
|
|
49
|
+
readonly status: CrawlStatus;
|
|
50
|
+
readonly total: number;
|
|
51
|
+
readonly finished: number;
|
|
52
|
+
readonly records: readonly CrawlRecord[];
|
|
53
|
+
readonly cursor?: string | number;
|
|
54
|
+
}
|
|
55
|
+
/** Cloudflare Browser Run's quick actions: one call renders a page and gives back what was asked for. */
|
|
56
|
+
export interface QuickActions {
|
|
57
|
+
markdown(request: PageRequest, options?: CallOptions): Promise<string>;
|
|
58
|
+
/** The page's HTML once rendered. */
|
|
59
|
+
content(request: PageRequest, options?: CallOptions): Promise<string>;
|
|
60
|
+
links(request: PageRequest & {
|
|
61
|
+
readonly visibleLinksOnly?: boolean;
|
|
62
|
+
readonly excludeExternalLinks?: boolean;
|
|
63
|
+
}, options?: CallOptions): Promise<readonly string[]>;
|
|
64
|
+
scrape(request: PageRequest & {
|
|
65
|
+
readonly selectors: readonly string[];
|
|
66
|
+
}, options?: CallOptions): Promise<readonly {
|
|
67
|
+
readonly selector: string;
|
|
68
|
+
readonly results: readonly ScrapedElement[];
|
|
69
|
+
}[]>;
|
|
70
|
+
screenshot(request: PageRequest & {
|
|
71
|
+
readonly fullPage?: boolean;
|
|
72
|
+
}, options?: CallOptions): Promise<Uint8Array>;
|
|
73
|
+
pdf(request: PageRequest, options?: CallOptions): Promise<Uint8Array>;
|
|
74
|
+
/** Structured data from the page by Cloudflare's model (Workers AI, billed as such): a prompt, a JSON Schema, or both. */
|
|
75
|
+
json(request: PageRequest & {
|
|
76
|
+
readonly prompt?: string;
|
|
77
|
+
readonly schema?: Record<string, unknown>;
|
|
78
|
+
}, options?: CallOptions): Promise<unknown>;
|
|
79
|
+
readonly crawl: {
|
|
80
|
+
start(request: CrawlStart, options?: CallOptions): Promise<string>;
|
|
81
|
+
status(id: string, options?: CallOptions & {
|
|
82
|
+
readonly cursor?: string | number;
|
|
83
|
+
readonly limit?: number;
|
|
84
|
+
}): Promise<CrawlResult>;
|
|
85
|
+
cancel(id: string, options?: CallOptions): Promise<void>;
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* A client for Cloudflare Browser Run's REST quick actions, from any runtime with no dependency. Nothing it reads of
|
|
90
|
+
* Cloudflare's errors reaches its own: a failure names only its HTTP status.
|
|
91
|
+
*/
|
|
92
|
+
export declare function cloudflareQuickActions(options: QuickActionsOptions): QuickActions;
|
|
93
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRo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MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;KAC1D,CAAC;CACH;AAOD;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,mBAAmB,GAAG,YAAY,CAmGjF"}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { MayuraError } from 'mayura';
|
|
2
|
+
const statuses = ['running', 'completed', 'errored', 'cancelled_due_to_timeout', 'cancelled_due_to_limits', 'cancelled_by_user'];
|
|
3
|
+
const failure = (status) => new MayuraError('TOOL_FAILED', status === 429 ? 'Cloudflare is rate limiting Browser Run requests (HTTP 429).' : `Cloudflare refused the request (HTTP ${status}).`);
|
|
4
|
+
const invalid = () => new MayuraError('TOOL_FAILED', 'Cloudflare returned a response that is not valid.');
|
|
5
|
+
/**
|
|
6
|
+
* A client for Cloudflare Browser Run's REST quick actions, from any runtime with no dependency. Nothing it reads of
|
|
7
|
+
* Cloudflare's errors reaches its own: a failure names only its HTTP status.
|
|
8
|
+
*/
|
|
9
|
+
export function cloudflareQuickActions(options) {
|
|
10
|
+
if (!options || typeof options.accountId !== 'string' || !/^[0-9a-f]{32}$/u.test(options.accountId))
|
|
11
|
+
throw new MayuraError('INVALID_CONFIG', 'cloudflareQuickActions(): accountId must be a Cloudflare account id.');
|
|
12
|
+
if (typeof options.apiToken !== 'string' || !/^[A-Za-z0-9_-]{20,512}$/u.test(options.apiToken))
|
|
13
|
+
throw new MayuraError('INVALID_CONFIG', 'cloudflareQuickActions(): apiToken must be a Cloudflare API token.');
|
|
14
|
+
if (options.fetch !== undefined && typeof options.fetch !== 'function')
|
|
15
|
+
throw new MayuraError('INVALID_CONFIG', 'cloudflareQuickActions(): fetch must be a function.');
|
|
16
|
+
const base = (() => {
|
|
17
|
+
try {
|
|
18
|
+
const url = new URL(options.baseUrl ?? 'https://api.cloudflare.com');
|
|
19
|
+
if (url.protocol !== 'https:' && url.hostname !== '127.0.0.1' && url.hostname !== 'localhost')
|
|
20
|
+
throw new Error();
|
|
21
|
+
return url.origin;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
throw new MayuraError('INVALID_CONFIG', 'cloudflareQuickActions(): baseUrl must be an https URL.');
|
|
25
|
+
}
|
|
26
|
+
})();
|
|
27
|
+
const root = `${base}/client/v4/accounts/${options.accountId}/browser-run`;
|
|
28
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
29
|
+
const headers = { authorization: `Bearer ${options.apiToken}`, 'content-type': 'application/json' };
|
|
30
|
+
const page = (request) => {
|
|
31
|
+
if (!request || typeof request.url !== 'string' || !/^https?:\/\//u.test(request.url))
|
|
32
|
+
throw new MayuraError('INVALID_INPUT', 'url must be an http(s) URL.');
|
|
33
|
+
return { url: request.url, ...(request.allowRequestPattern ? { allowRequestPattern: [...request.allowRequestPattern] } : {}) };
|
|
34
|
+
};
|
|
35
|
+
const send = async (method, path, body, signal) => {
|
|
36
|
+
const reply = await fetcher(`${root}${path}`, { method, headers, ...(signal ? { signal } : {}), ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
|
|
37
|
+
if (!reply.ok) {
|
|
38
|
+
void reply.body?.cancel().catch(() => undefined);
|
|
39
|
+
throw failure(reply.status);
|
|
40
|
+
}
|
|
41
|
+
return reply;
|
|
42
|
+
};
|
|
43
|
+
/** The `result` of Cloudflare's JSON envelope. */
|
|
44
|
+
const result = async (reply) => {
|
|
45
|
+
const data = await reply.json().catch(() => undefined);
|
|
46
|
+
if (!data || data.success !== true)
|
|
47
|
+
throw invalid();
|
|
48
|
+
return data.result;
|
|
49
|
+
};
|
|
50
|
+
const bytes = async (reply) => {
|
|
51
|
+
if (/json/u.test(reply.headers.get('content-type') ?? '')) {
|
|
52
|
+
void reply.body?.cancel().catch(() => undefined);
|
|
53
|
+
throw invalid();
|
|
54
|
+
}
|
|
55
|
+
return new Uint8Array(await reply.arrayBuffer());
|
|
56
|
+
};
|
|
57
|
+
const text = (value) => { if (typeof value !== 'string')
|
|
58
|
+
throw invalid(); return value; };
|
|
59
|
+
const actions = {
|
|
60
|
+
markdown: async (request, call = {}) => text(await result(await send('POST', '/markdown', page(request), call.signal))),
|
|
61
|
+
content: async (request, call = {}) => {
|
|
62
|
+
const reply = await send('POST', '/content', page(request), call.signal);
|
|
63
|
+
// Cloudflare does not document whether HTML comes in its envelope or as itself: either is taken.
|
|
64
|
+
return /json/u.test(reply.headers.get('content-type') ?? '') ? text(await result(reply)) : reply.text();
|
|
65
|
+
},
|
|
66
|
+
links: async (request, call = {}) => {
|
|
67
|
+
const value = await result(await send('POST', '/links', { ...page(request), ...(request.visibleLinksOnly ? { visibleLinksOnly: true } : {}), ...(request.excludeExternalLinks ? { excludeExternalLinks: true } : {}) }, call.signal));
|
|
68
|
+
if (!Array.isArray(value))
|
|
69
|
+
throw invalid();
|
|
70
|
+
return value.filter((link) => typeof link === 'string');
|
|
71
|
+
},
|
|
72
|
+
scrape: async (request, call = {}) => {
|
|
73
|
+
if (!Array.isArray(request.selectors) || request.selectors.length === 0 || request.selectors.length > 20 || request.selectors.some(item => typeof item !== 'string' || item === '' || item.length > 500)) {
|
|
74
|
+
throw new MayuraError('INVALID_INPUT', 'selectors are 1 to 20 CSS selectors.');
|
|
75
|
+
}
|
|
76
|
+
const value = await result(await send('POST', '/scrape', { ...page(request), elements: request.selectors.map(selector => ({ selector })) }, call.signal));
|
|
77
|
+
if (!Array.isArray(value))
|
|
78
|
+
throw invalid();
|
|
79
|
+
return value.map(item => {
|
|
80
|
+
const entry = item;
|
|
81
|
+
return { selector: typeof entry?.selector === 'string' ? entry.selector : '', results: (Array.isArray(entry?.results) ? entry.results : []).map(found => {
|
|
82
|
+
const element = found;
|
|
83
|
+
return { text: typeof element?.text === 'string' ? element.text : '', html: typeof element?.html === 'string' ? element.html : '',
|
|
84
|
+
attributes: (Array.isArray(element?.attributes) ? element.attributes : []).filter((attribute) => typeof attribute?.name === 'string' && typeof attribute?.value === 'string').map(({ name, value }) => ({ name, value })) };
|
|
85
|
+
}) };
|
|
86
|
+
});
|
|
87
|
+
},
|
|
88
|
+
screenshot: async (request, call = {}) => bytes(await send('POST', '/screenshot', { ...page(request), screenshotOptions: { type: 'png', fullPage: request.fullPage === true } }, call.signal)),
|
|
89
|
+
pdf: async (request, call = {}) => bytes(await send('POST', '/pdf', page(request), call.signal)),
|
|
90
|
+
json: async (request, call = {}) => {
|
|
91
|
+
if (request.prompt === undefined && request.schema === undefined)
|
|
92
|
+
throw new MayuraError('INVALID_INPUT', 'json needs a prompt, a schema, or both.');
|
|
93
|
+
return result(await send('POST', '/json', { ...page(request), ...(request.prompt ? { prompt: request.prompt } : {}),
|
|
94
|
+
...(request.schema ? { response_format: { type: 'json_schema', json_schema: request.schema } } : {}) }, call.signal));
|
|
95
|
+
},
|
|
96
|
+
crawl: Object.freeze({
|
|
97
|
+
start: async (request, call = {}) => {
|
|
98
|
+
const id = await result(await send('POST', '/crawl', { ...page(request), limit: request.limit ?? 10, ...(request.depth ? { depth: request.depth } : {}),
|
|
99
|
+
formats: [...(request.formats ?? ['markdown'])],
|
|
100
|
+
options: { includeSubdomains: false, includeExternalLinks: false,
|
|
101
|
+
...(request.includePatterns ? { includePatterns: [...request.includePatterns] } : {}), ...(request.excludePatterns ? { excludePatterns: [...request.excludePatterns] } : {}) } }, call.signal));
|
|
102
|
+
if (typeof id !== 'string' || !/^[A-Za-z0-9-]{1,128}$/u.test(id))
|
|
103
|
+
throw invalid();
|
|
104
|
+
return id;
|
|
105
|
+
},
|
|
106
|
+
status: async (id, call = {}) => {
|
|
107
|
+
if (typeof id !== 'string' || !/^[A-Za-z0-9-]{1,128}$/u.test(id))
|
|
108
|
+
throw new MayuraError('INVALID_INPUT', 'id must be a crawl job id.');
|
|
109
|
+
const query = new URLSearchParams({ limit: String(call.limit ?? 100), ...(call.cursor !== undefined ? { cursor: String(call.cursor) } : {}) });
|
|
110
|
+
const value = await result(await send('GET', `/crawl/${id}?${query}`, undefined, call.signal));
|
|
111
|
+
if (!value || !statuses.includes(value.status))
|
|
112
|
+
throw invalid();
|
|
113
|
+
const records = (Array.isArray(value.records) ? value.records : []).flatMap(item => {
|
|
114
|
+
const record = item;
|
|
115
|
+
if (typeof record?.url !== 'string')
|
|
116
|
+
return [];
|
|
117
|
+
return [{ url: record.url, status: typeof record.status === 'string' ? record.status : '', ...(typeof record.markdown === 'string' ? { markdown: record.markdown } : {}),
|
|
118
|
+
...(typeof record.html === 'string' ? { html: record.html } : {}), ...(typeof record.metadata?.title === 'string' ? { title: record.metadata.title } : {}),
|
|
119
|
+
...(typeof record.metadata?.status === 'number' ? { httpStatus: record.metadata.status } : {}) }];
|
|
120
|
+
});
|
|
121
|
+
return { id, status: value.status, total: Number(value.total) || 0, finished: Number(value.finished) || 0, records,
|
|
122
|
+
...(typeof value.cursor === 'string' || typeof value.cursor === 'number' ? { cursor: value.cursor } : {}) };
|
|
123
|
+
},
|
|
124
|
+
cancel: async (id, call = {}) => {
|
|
125
|
+
if (typeof id !== 'string' || !/^[A-Za-z0-9-]{1,128}$/u.test(id))
|
|
126
|
+
throw new MayuraError('INVALID_INPUT', 'id must be a crawl job id.');
|
|
127
|
+
const reply = await send('DELETE', `/crawl/${id}`, undefined, call.signal);
|
|
128
|
+
void reply.body?.cancel().catch(() => undefined);
|
|
129
|
+
},
|
|
130
|
+
}),
|
|
131
|
+
};
|
|
132
|
+
return Object.freeze(actions);
|
|
133
|
+
}
|
|
134
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAqDrC,MAAM,QAAQ,GAA2B,CAAC,SAAS,EAAE,WAAW,EAAE,SAAS,EAAE,0BAA0B,EAAE,yBAAyB,EAAE,mBAAmB,CAAC,CAAC;AACzJ,MAAM,OAAO,GAAG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C,CAAC,EAAE,UAAU,EAAE,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;gBACtG,CAAC,CAAC,CAAC;gBACH,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,CAAC,MAAqB,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO;oBAC/H,GAAG,CAAC,OAAO,KAAK,CAAC,MAAM,KAAK,QAAQ,IAAI,OAAO,KAAK,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;YAChH,CAAC;YACD,MAAM,EAAE,KAAK,EAAE,EAAU,EAAE,IAAI,GAAgB,EAAE,EAAE,EAAE;gBACnD,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,EAAE,CAAC;oBAAE,MAAM,IAAI,WAAW,CAAC,eAAe,EAAE,4BAA4B,CAAC,CAAC;gBACvI,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,QAAQ,EAAE,UAAU,EAAE,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;gBAC3E,KAAK,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;YACnD,CAAC;SACF,CAAC;KACH,CAAC;IACF,OAAO,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;AAChC,CAAC","sourcesContent":["import { MayuraError } from 'mayura';\n\nexport interface QuickActionsOptions {\n /** Your Cloudflare account id (32 hex characters). */\n readonly accountId: string;\n /** A Cloudflare API token with the \"Browser Rendering - Edit\" permission. Nothing is read from the environment. */\n readonly apiToken: string;\n /** For tests and proxies: the fetch to use. */\n readonly fetch?: typeof fetch;\n /** The API's address; `https://api.cloudflare.com` by default. */\n readonly baseUrl?: string;\n}\n\n/** What every action renders: a page, and optionally only the requests it may make. */\nexport interface PageRequest {\n readonly url: string;\n /** Regular expressions: the page loads only what matches one. */\n readonly allowRequestPattern?: readonly string[];\n}\nexport interface CallOptions { readonly signal?: AbortSignal }\nexport interface ScrapedElement { readonly text: string; readonly html: string; readonly attributes: readonly { readonly name: string; readonly value: string }[] }\nexport interface CrawlStart {\n readonly url: string;\n /** Pages to read; 10 by default. */\n readonly limit?: number;\n readonly depth?: number;\n readonly formats?: readonly ('markdown' | 'html')[];\n readonly includePatterns?: readonly string[];\n readonly excludePatterns?: readonly string[];\n readonly allowRequestPattern?: readonly string[];\n}\nexport type CrawlStatus = 'running' | 'completed' | 'errored' | 'cancelled_due_to_timeout' | 'cancelled_due_to_limits' | 'cancelled_by_user';\nexport interface CrawlRecord { readonly url: string; readonly status: string; readonly markdown?: string; readonly html?: string; readonly title?: string; readonly httpStatus?: number }\nexport interface CrawlResult { readonly id: string; readonly status: CrawlStatus; readonly total: number; readonly finished: number; readonly records: readonly CrawlRecord[]; readonly cursor?: string | number }\n\n/** Cloudflare Browser Run's quick actions: one call renders a page and gives back what was asked for. */\nexport interface QuickActions {\n markdown(request: PageRequest, options?: CallOptions): Promise<string>;\n /** The page's HTML once rendered. */\n content(request: PageRequest, options?: CallOptions): Promise<string>;\n links(request: PageRequest & { readonly visibleLinksOnly?: boolean; readonly excludeExternalLinks?: boolean }, options?: CallOptions): Promise<readonly string[]>;\n scrape(request: PageRequest & { readonly selectors: readonly string[] }, options?: CallOptions): Promise<readonly { readonly selector: string; readonly results: readonly ScrapedElement[] }[]>;\n screenshot(request: PageRequest & { readonly fullPage?: boolean }, options?: CallOptions): Promise<Uint8Array>;\n pdf(request: PageRequest, options?: CallOptions): Promise<Uint8Array>;\n /** Structured data from the page by Cloudflare's model (Workers AI, billed as such): a prompt, a JSON Schema, or both. */\n json(request: PageRequest & { readonly prompt?: string; readonly schema?: Record<string, unknown> }, options?: CallOptions): Promise<unknown>;\n readonly crawl: {\n start(request: CrawlStart, options?: CallOptions): Promise<string>;\n status(id: string, options?: CallOptions & { readonly cursor?: string | number; readonly limit?: number }): Promise<CrawlResult>;\n cancel(id: string, options?: CallOptions): Promise<void>;\n };\n}\n\nconst statuses: readonly CrawlStatus[] = ['running', 'completed', 'errored', 'cancelled_due_to_timeout', 'cancelled_due_to_limits', 'cancelled_by_user'];\nconst failure = (status: number) => new MayuraError('TOOL_FAILED',\n status === 429 ? 'Cloudflare is rate limiting Browser Run requests (HTTP 429).' : `Cloudflare refused the request (HTTP ${status}).`);\nconst invalid = () => new MayuraError('TOOL_FAILED', 'Cloudflare returned a response that is not valid.');\n\n/**\n * A client for Cloudflare Browser Run's REST quick actions, from any runtime with no dependency. Nothing it reads of\n * Cloudflare's errors reaches its own: a failure names only its HTTP status.\n */\nexport function cloudflareQuickActions(options: QuickActionsOptions): QuickActions {\n if (!options || typeof options.accountId !== 'string' || !/^[0-9a-f]{32}$/u.test(options.accountId)) throw new MayuraError('INVALID_CONFIG', 'cloudflareQuickActions(): accountId must be a Cloudflare account id.');\n if (typeof options.apiToken !== 'string' || !/^[A-Za-z0-9_-]{20,512}$/u.test(options.apiToken)) throw new MayuraError('INVALID_CONFIG', 'cloudflareQuickActions(): apiToken must be a Cloudflare API token.');\n if (options.fetch !== undefined && typeof options.fetch !== 'function') throw new MayuraError('INVALID_CONFIG', 'cloudflareQuickActions(): fetch must be a function.');\n const base = (() => {\n try { const url = new URL(options.baseUrl ?? 'https://api.cloudflare.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', 'cloudflareQuickActions(): baseUrl must be an https URL.'); }\n })();\n const root = `${base}/client/v4/accounts/${options.accountId}/browser-run`;\n const fetcher = options.fetch ?? globalThis.fetch;\n const headers = { authorization: `Bearer ${options.apiToken}`, 'content-type': 'application/json' };\n const page = (request: PageRequest) => {\n if (!request || typeof request.url !== 'string' || !/^https?:\\/\\//u.test(request.url)) throw new MayuraError('INVALID_INPUT', 'url must be an http(s) URL.');\n return { url: request.url, ...(request.allowRequestPattern ? { allowRequestPattern: [...request.allowRequestPattern] } : {}) };\n };\n const send = async (method: 'GET' | 'POST' | 'DELETE', path: string, body: unknown, signal: AbortSignal | undefined) => {\n const reply = await fetcher(`${root}${path}`, { method, headers, ...(signal ? { signal } : {}), ...(body === undefined ? {} : { body: JSON.stringify(body) }) });\n if (!reply.ok) { void reply.body?.cancel().catch(() => undefined); throw failure(reply.status); }\n return reply;\n };\n /** The `result` of Cloudflare's JSON envelope. */\n const result = async (reply: Response): Promise<unknown> => {\n const data = await reply.json().catch(() => undefined) as { success?: unknown; result?: unknown } | undefined;\n if (!data || data.success !== true) throw invalid();\n return data.result;\n };\n const bytes = async (reply: Response): Promise<Uint8Array> => {\n if (/json/u.test(reply.headers.get('content-type') ?? '')) { void reply.body?.cancel().catch(() => undefined); throw invalid(); }\n return new Uint8Array(await reply.arrayBuffer());\n };\n const text = (value: unknown) => { if (typeof value !== 'string') throw invalid(); return value; };\n\n const actions: QuickActions = {\n markdown: async (request, call = {}) => text(await result(await send('POST', '/markdown', page(request), call.signal))),\n content: async (request, call = {}) => {\n const reply = await send('POST', '/content', page(request), call.signal);\n // Cloudflare does not document whether HTML comes in its envelope or as itself: either is taken.\n return /json/u.test(reply.headers.get('content-type') ?? '') ? text(await result(reply)) : reply.text();\n },\n links: async (request, call = {}) => {\n const value = await result(await send('POST', '/links', { ...page(request), ...(request.visibleLinksOnly ? { visibleLinksOnly: true } : {}), ...(request.excludeExternalLinks ? { excludeExternalLinks: true } : {}) }, call.signal));\n if (!Array.isArray(value)) throw invalid();\n return value.filter((link): link is string => typeof link === 'string');\n },\n scrape: async (request, call = {}) => {\n if (!Array.isArray(request.selectors) || request.selectors.length === 0 || request.selectors.length > 20 || request.selectors.some(item => typeof item !== 'string' || item === '' || item.length > 500)) {\n throw new MayuraError('INVALID_INPUT', 'selectors are 1 to 20 CSS selectors.');\n }\n const value = await result(await send('POST', '/scrape', { ...page(request), elements: request.selectors.map(selector => ({ selector })) }, call.signal));\n if (!Array.isArray(value)) throw invalid();\n return value.map(item => {\n const entry = item as { selector?: unknown; results?: unknown };\n return { selector: typeof entry?.selector === 'string' ? entry.selector : '', results: (Array.isArray(entry?.results) ? entry.results : []).map(found => {\n const element = found as { text?: unknown; html?: unknown; attributes?: unknown };\n return { text: typeof element?.text === 'string' ? element.text : '', html: typeof element?.html === 'string' ? element.html : '',\n attributes: (Array.isArray(element?.attributes) ? element.attributes : []).filter((attribute): attribute is { name: string; value: string } =>\n typeof (attribute as { name?: unknown })?.name === 'string' && typeof (attribute as { value?: unknown })?.value === 'string').map(({ name, value }) => ({ name, value })) };\n }) };\n });\n },\n screenshot: async (request, call = {}) => bytes(await send('POST', '/screenshot', { ...page(request), screenshotOptions: { type: 'png', fullPage: request.fullPage === true } }, call.signal)),\n pdf: async (request, call = {}) => bytes(await send('POST', '/pdf', page(request), call.signal)),\n json: async (request, call = {}) => {\n if (request.prompt === undefined && request.schema === undefined) throw new MayuraError('INVALID_INPUT', 'json needs a prompt, a schema, or both.');\n return result(await send('POST', '/json', { ...page(request), ...(request.prompt ? { prompt: request.prompt } : {}),\n ...(request.schema ? { response_format: { type: 'json_schema', json_schema: request.schema } } : {}) }, call.signal));\n },\n crawl: Object.freeze({\n start: async (request: CrawlStart, call: CallOptions = {}) => {\n const id = await result(await send('POST', '/crawl', { ...page(request), limit: request.limit ?? 10, ...(request.depth ? { depth: request.depth } : {}),\n formats: [...(request.formats ?? ['markdown'])],\n options: { includeSubdomains: false, includeExternalLinks: false,\n ...(request.includePatterns ? { includePatterns: [...request.includePatterns] } : {}), ...(request.excludePatterns ? { excludePatterns: [...request.excludePatterns] } : {}) } }, call.signal));\n if (typeof id !== 'string' || !/^[A-Za-z0-9-]{1,128}$/u.test(id)) throw invalid();\n return id;\n },\n status: async (id: string, call: CallOptions & { readonly cursor?: string | number; readonly limit?: number } = {}) => {\n if (typeof id !== 'string' || !/^[A-Za-z0-9-]{1,128}$/u.test(id)) throw new MayuraError('INVALID_INPUT', 'id must be a crawl job id.');\n const query = new URLSearchParams({ limit: String(call.limit ?? 100), ...(call.cursor !== undefined ? { cursor: String(call.cursor) } : {}) });\n const value = await result(await send('GET', `/crawl/${id}?${query}`, undefined, call.signal)) as { id?: unknown; status?: unknown; total?: unknown; finished?: unknown; records?: unknown; cursor?: unknown } | undefined;\n if (!value || !statuses.includes(value.status as CrawlStatus)) throw invalid();\n const records = (Array.isArray(value.records) ? value.records : []).flatMap(item => {\n const record = item as { url?: unknown; status?: unknown; markdown?: unknown; html?: unknown; metadata?: { title?: unknown; status?: unknown } };\n if (typeof record?.url !== 'string') return [];\n return [{ url: record.url, status: typeof record.status === 'string' ? record.status : '', ...(typeof record.markdown === 'string' ? { markdown: record.markdown } : {}),\n ...(typeof record.html === 'string' ? { html: record.html } : {}), ...(typeof record.metadata?.title === 'string' ? { title: record.metadata.title } : {}),\n ...(typeof record.metadata?.status === 'number' ? { httpStatus: record.metadata.status } : {}) }];\n });\n return { id, status: value.status as CrawlStatus, total: Number(value.total) || 0, finished: Number(value.finished) || 0, records,\n ...(typeof value.cursor === 'string' || typeof value.cursor === 'number' ? { cursor: value.cursor } : {}) };\n },\n cancel: async (id: string, call: CallOptions = {}) => {\n if (typeof id !== 'string' || !/^[A-Za-z0-9-]{1,128}$/u.test(id)) throw new MayuraError('INVALID_INPUT', 'id must be a crawl job id.');\n const reply = await send('DELETE', `/crawl/${id}`, undefined, call.signal);\n void reply.body?.cancel().catch(() => undefined);\n },\n }),\n };\n return Object.freeze(actions);\n}\n"]}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { cloudflareQuickActions } from './client.js';
|
|
2
|
+
export type { CallOptions, CrawlRecord, CrawlResult, CrawlStart, CrawlStatus, PageRequest, QuickActions, QuickActionsOptions, ScrapedElement } from './client.js';
|
|
3
|
+
export { originPatterns, quickActionTools } from './tools.js';
|
|
4
|
+
export type { QuickActionToolsOptions } from './tools.js';
|
|
5
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AACrD,YAAY,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,UAAU,EAAE,WAAW,EAAE,WAAW,EAAE,YAAY,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAClK,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9D,YAAY,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAErD,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC","sourcesContent":["export { cloudflareQuickActions } from './client.js';\nexport type { CallOptions, CrawlRecord, CrawlResult, CrawlStart, CrawlStatus, PageRequest, QuickActions, QuickActionsOptions, ScrapedElement } from './client.js';\nexport { originPatterns, quickActionTools } from './tools.js';\nexport type { QuickActionToolsOptions } from './tools.js';\n"]}
|
package/dist/tools.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { type AnyTool } from 'mayura';
|
|
2
|
+
import type { QuickActions } from './client.js';
|
|
3
|
+
export interface QuickActionToolsOptions {
|
|
4
|
+
/** Names the tools (`<name>.markdown`, ...) and their permissions (`web:<name>:read`, ...); `cloudflare` by default. */
|
|
5
|
+
readonly name?: string;
|
|
6
|
+
/**
|
|
7
|
+
* The sites the tools may read, as `createBrowsers` takes them: `['https://example.com', 'https://*.example.com']`,
|
|
8
|
+
* or `'all'`. Required: nothing is allowed by default. The page Cloudflare renders loads nothing from other sites.
|
|
9
|
+
*/
|
|
10
|
+
readonly origins: 'all' | readonly string[];
|
|
11
|
+
/** Make `<name>.screenshot`, an image of a page; permission `web:<name>:read`. Off by default. */
|
|
12
|
+
readonly screenshot?: boolean;
|
|
13
|
+
/** Make `<name>.json`, structured data from a page by Cloudflare's model (Workers AI); permission `web:<name>:extract`. Off by default. */
|
|
14
|
+
readonly json?: boolean;
|
|
15
|
+
/** Make `<name>.crawl`, which reads many pages of a site; permission `web:<name>:crawl`. Off by default. */
|
|
16
|
+
readonly crawl?: boolean;
|
|
17
|
+
/** The most bytes of a page's content returned to the model; 64 KiB by default. */
|
|
18
|
+
readonly maxPageBytes?: number;
|
|
19
|
+
/** The most pages one crawl reads; 10 by default (at most 100). */
|
|
20
|
+
readonly maxCrawlPages?: number;
|
|
21
|
+
/** The longest one crawl runs before it is cancelled; 5 minutes by default. */
|
|
22
|
+
readonly crawlTimeoutMs?: number;
|
|
23
|
+
/** What each call costs at most, in micro-units of your budget currency, by tool; 0 by default. */
|
|
24
|
+
readonly costMicros?: {
|
|
25
|
+
readonly markdown?: number;
|
|
26
|
+
readonly links?: number;
|
|
27
|
+
readonly scrape?: number;
|
|
28
|
+
readonly screenshot?: number;
|
|
29
|
+
readonly json?: number;
|
|
30
|
+
readonly crawl?: number;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** Request patterns that let a page load only from the origins (already checked by originPolicy). */
|
|
34
|
+
export declare function originPatterns(origins: readonly string[]): string[];
|
|
35
|
+
/**
|
|
36
|
+
* Cloudflare Browser Run's quick actions as tools: `<name>.markdown`, `<name>.links` and `<name>.scrape` read pages
|
|
37
|
+
* (`web:<name>:read`); screenshots, JSON extraction and crawls are each off until enabled. Every URL must be within
|
|
38
|
+
* `origins`, and the page Cloudflare renders loads nothing from elsewhere. Page content comes back as the tools'
|
|
39
|
+
* results, for the model to read: treat it as untrusted text.
|
|
40
|
+
*/
|
|
41
|
+
export declare function quickActionTools(actions: QuickActions, options: QuickActionToolsOptions): AnyTool[];
|
|
42
|
+
//# sourceMappingURL=tools.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../src/tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6C,KAAK,OAAO,EAAgC,MAAM,QAAQ,CAAC;AAE/G,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,MAAM,WAAW,uBAAuB;IACtC,wHAAwH;IACxH,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB;;;OAGG;IACH,QAAQ,CAAC,OAAO,EAAE,KAAK,GAAG,SAAS,MAAM,EAAE,CAAC;IAC5C,kGAAkG;IAClG,QAAQ,CAAC,UAAU,CAAC,EAAE,OAAO,CAAC;IAC9B,2IAA2I;IAC3I,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC;IACxB,4GAA4G;IAC5G,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;IACzB,mFAAmF;IACnF,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,mEAAmE;IACnE,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,+EAA+E;IAC/E,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACjC,mGAAmG;IACnG,QAAQ,CAAC,UAAU,CAAC,EAAE;QAAE,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,U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