@parcha/pi-browser 0.1.0-beta.34 → 0.1.0-beta.341

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.
Files changed (78) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/NOTICE +6 -1
  3. package/README.md +70 -60
  4. package/dist/core/contract.d.ts +9 -6
  5. package/dist/core/contract.js +12 -30
  6. package/dist/core/custody.d.ts +6 -0
  7. package/dist/core/custody.js +15 -3
  8. package/dist/core/downloads.d.ts +37 -3
  9. package/dist/core/downloads.js +81 -57
  10. package/dist/core/driving-guard.d.ts +1 -1
  11. package/dist/core/driving-guard.js +1 -1
  12. package/dist/core/evidence.d.ts +1 -1
  13. package/dist/core/files.d.ts +20 -2
  14. package/dist/core/files.js +161 -10
  15. package/dist/core/host.d.ts +18 -75
  16. package/dist/core/images.d.ts +32 -4
  17. package/dist/core/images.js +81 -16
  18. package/dist/core/lease.d.ts +2 -1
  19. package/dist/core/page-scan.d.ts +81 -2
  20. package/dist/core/page-scan.js +487 -13
  21. package/dist/core/public-fetch.d.ts +70 -9
  22. package/dist/core/public-fetch.js +348 -51
  23. package/dist/core/read-page-worker.js +5 -4
  24. package/dist/core/read-page.d.ts +23 -8
  25. package/dist/core/read-page.js +64 -20
  26. package/dist/core/redact.d.ts +0 -2
  27. package/dist/core/redact.js +0 -32
  28. package/dist/core/session-control.d.ts +0 -2
  29. package/dist/core/session-control.js +0 -5
  30. package/dist/core/tools.d.ts +23 -1
  31. package/dist/core/tools.js +46 -4
  32. package/dist/core/usage.d.ts +4 -3
  33. package/dist/core/usage.js +5 -4
  34. package/dist/core/vault.d.ts +0 -10
  35. package/dist/core/vault.js +0 -13
  36. package/dist/core/web.d.ts +2 -111
  37. package/dist/core/web.js +0 -443
  38. package/dist/driver/cdp.js +3 -3
  39. package/dist/driver/page-driver.js +7 -3
  40. package/dist/driver/stagehand.d.ts +3 -1
  41. package/dist/driver/stagehand.js +4 -2
  42. package/dist/durable/store.d.ts +14 -3
  43. package/dist/durable/store.js +204 -51
  44. package/dist/durable.d.ts +32 -16
  45. package/dist/durable.js +68 -95
  46. package/dist/index.d.ts +3 -3
  47. package/dist/index.js +5 -3
  48. package/dist/live-view/index.d.ts +3 -1
  49. package/dist/live-view/index.js +4 -0
  50. package/dist/live-view/protocol.d.ts +1 -1
  51. package/dist/live-view/server.d.ts +30 -0
  52. package/dist/live-view/server.js +152 -25
  53. package/dist/providers/cdp.js +2 -2
  54. package/dist/providers/profiles.d.ts +1 -15
  55. package/dist/providers/profiles.js +1 -64
  56. package/dist/providers/shared.d.ts +1 -47
  57. package/dist/providers/shared.js +1 -82
  58. package/dist/providers/worker-extension.d.ts +14 -1
  59. package/dist/providers/worker-extension.js +69 -3
  60. package/dist/testing/backend.d.ts +6 -24
  61. package/dist/testing/backend.js +7 -30
  62. package/dist/vault-session.d.ts +4 -7
  63. package/dist/vault-session.js +26 -81
  64. package/dist/vendor/browser-use-pi/page.d.ts +3 -12
  65. package/dist/vendor/browser-use-pi/page.js +6 -19
  66. package/package.json +9 -22
  67. package/dist/core/sites.d.ts +0 -33
  68. package/dist/core/sites.js +0 -104
  69. package/dist/durable/web.d.ts +0 -47
  70. package/dist/durable/web.js +0 -41
  71. package/dist/providers/browserbase-net.d.ts +0 -12
  72. package/dist/providers/browserbase-net.js +0 -95
  73. package/dist/providers/browserbase.d.ts +0 -169
  74. package/dist/providers/browserbase.js +0 -319
  75. package/dist/providers/kernel.d.ts +0 -58
  76. package/dist/providers/kernel.js +0 -291
  77. /package/dist/{providers → core}/cdp-call.d.ts +0 -0
  78. /package/dist/{providers → core}/cdp-call.js +0 -0
@@ -1,4 +1,6 @@
1
- /** Any address but a public unicast one, v4 and v6 (see V4_PRIVATE and V6_PRIVATE); what does not parse as one too. */
1
+ /** Any address but a public unicast one, v4 and v6 (see V4_PRIVATE and V6_PRIVATE), or one in the hosting cluster's
2
+ * internal ranges (CLUSTER_INTERNAL_CIDRS_ENV); what does not parse as one too. The one address judgment every
3
+ * outbound guard here uses: web_fetch, web_save, the webhook and the MCP, calendar and feed checks. */
2
4
  export declare function isPrivateAddress(ip: string): boolean;
3
5
  /** Answers `address` for any name: the address a request was checked against is the one it connects to. */
4
6
  export declare const pinnedLookup: (address: string) => (_host: string, options: {
@@ -13,20 +15,79 @@ export type PublicFetchOptions = {
13
15
  signal?: AbortSignal;
14
16
  /** Default 5 MiB. */
15
17
  maxBytes?: number;
18
+ /** Refuse http as well, on the first hop and at every redirect: https only. Default false. */
19
+ httpsOnly?: boolean;
20
+ /** The most redirects followed, a whole number from 0 to 5; with 0 any redirect is refused before its target is
21
+ * dialled. Default 5. */
22
+ maxRedirects?: number;
23
+ /** Asked with each redirect's target (its href) once that hop's checks pass, before it is dialled; never with the
24
+ * first hop. What it throws ends the fetch there, the target unsent, as it was thrown. The signal bounds it. */
25
+ beforeRedirect?: (url: string) => void | Promise<void>;
26
+ /** The User-Agent every hop sends, the first and each redirect's. Default `pi-browser`. */
27
+ userAgent?: string;
16
28
  };
17
- /** The answer that ended the redirects: its URL, status and type, and its body when it is a 2xx text answer. */
29
+ /** The answer that ended the redirects: its URL, status and type, and its body when it is a 2xx text answer. `cut` when
30
+ * that body is only its first `maxBytes` (publicFetch's `cut`): the rest was not read. */
18
31
  export type PublicAnswer = {
19
32
  url: string;
20
33
  status: number;
21
34
  contentType: string;
22
35
  body: string | null;
36
+ cut?: true;
37
+ };
38
+ /** The answer that ended the redirects, as `publicDownload` gives it: its URL, status and type, and its bytes when it is a
39
+ * 2xx answer (an empty array for a 2xx with no body). */
40
+ export type PublicFile = {
41
+ url: string;
42
+ status: number;
43
+ contentType: string;
44
+ bytes: Uint8Array | null;
45
+ };
46
+ type Lookup = (host: string) => Promise<string[]>;
47
+ /** Whether publicFetch's first hop would be dialled for `url`: hopUrl's and hopAddresses' checks, http(s), with nothing
48
+ * sent. Resolves when it passes; throws publicFetch's own refusal when it does not. */
49
+ export declare function publicCheck(url: string, options?: {
50
+ lookup?: Lookup;
51
+ signal?: AbortSignal;
52
+ }): Promise<void>;
53
+ /**
54
+ * Fetches `url` from a public host, following at most 5 redirects (or `maxRedirects`), each hop resolved, checked and dialled at the
55
+ * address checked. A 2xx answer of a text type is read whole, up to `maxBytes`, and
56
+ * decoded by the charset it declares (pageText); another status comes back without its
57
+ * body. Refused (`BrowserFailureError` `refused`), on the first hop or a redirect: a scheme other than http(s) (other
58
+ * than https, with `httpsOnly`); a URL holding a user name or password; a host that is local by name or resolves to any
59
+ * private address; a port other than 80
60
+ * or 443; too many redirects (any, with `maxRedirects` 0); a 2xx body that is not text or is over the cap. With `cut`, a
61
+ * body over the cap is not refused: its first `maxBytes` are read and decoded (a character the cut splits dropped), the
62
+ * rest is never read, and the answer says `cut`. `signal` ends the fetch at any point, a
63
+ * hop's name lookup included (it rejects with the signal's reason), and an aborted hop is never dialled.
64
+ */
65
+ export declare function publicFetch(url: string, options?: PublicFetchOptions & {
66
+ cut?: boolean;
67
+ }): Promise<PublicAnswer>;
68
+ /**
69
+ * Downloads `url` from a public host: publicFetch's hops and refusals (scheme, user name or password, local or private host, port, redirects,
70
+ * the signal), with any content type accepted and the body kept as bytes, up to `maxBytes` (default 5 MiB). A 2xx answer
71
+ * is read whole; another status comes back with `bytes` null. A body over the cap is refused (`refused: the file is over
72
+ * <cap>`): before a byte is read when its content-length says so, else as soon as it passes it. A body whose length its
73
+ * host states (an unencoded reply's content-length) is read into one buffer of that length, so it is held once; one longer
74
+ * than stated is refused as it runs past it, one shorter at its end. With no stated length the chunks are joined at the
75
+ * end, about twice the file's size at the peak. `signal` ends the body's read too, with its reason.
76
+ */
77
+ export declare function publicDownload(url: string, options?: PublicFetchOptions): Promise<PublicFile>;
78
+ /** What publicUpload answers: the URL the bytes were sent to and the status its host answered. */
79
+ export type PublicUpload = {
80
+ url: string;
81
+ status: number;
23
82
  };
24
83
  /**
25
- * Fetches `url` from a public host, following at most 5 redirects, each hop resolved, checked and dialled at the
26
- * address checked. A 2xx answer of a text type is read whole, up to `maxBytes`; another status comes back without its
27
- * body. Refused (`BrowserFailureError` `refused`), on the first hop or a redirect: a scheme other than http(s); a host
28
- * that is local by name or resolves to any private address; a port other than 80 or 443; too many redirects; a 2xx body
29
- * that is not text or is over the cap. `signal` ends the fetch at any point, a hop's name lookup included (it rejects
30
- * with the signal's reason), and an aborted hop is never dialled.
84
+ * Uploads `bytes` to `url` on a public host, as one PUT: publicFetch's checks of its one hop (a user name or password,
85
+ * a local or private host, a port, the signal), https only, and no redirect followed, so the bytes go to the URL given
86
+ * or nowhere (a redirect is refused before its target is dialled). `contentType`, when given, is sent as the body's
87
+ * type; else none is. The answer's body is not read; its status comes back for the caller to judge, an error status
88
+ * included.
31
89
  */
32
- export declare function publicFetch(url: string, options?: PublicFetchOptions): Promise<PublicAnswer>;
90
+ export declare function publicUpload(url: string, bytes: Uint8Array, options?: Omit<PublicFetchOptions, "maxBytes" | "httpsOnly" | "maxRedirects" | "beforeRedirect"> & {
91
+ contentType?: string;
92
+ }): Promise<PublicUpload>;
93
+ export {};
@@ -11,9 +11,10 @@ import { refusedError } from "./custody.js";
11
11
  * included). */
12
12
  const V4_PRIVATE = [[0x00000000, 8], [0x0a000000, 8], [0x64400000, 10], [0x7f000000, 8], [0xa9fe0000, 16], [0xac100000, 12], [0xc0000000, 24], [0xc0a80000, 16], [0xc6120000, 15], [0xe0000000, 4], [0xf0000000, 4]];
13
13
  /** ::/8 reserved by the IETF (the unspecified and loopback addresses, IPv4-compatible ones, and the NAT64 prefixes
14
- * 64:ff9b::/96 and 64:ff9b:1::/48), fc00::/7 unique-local, fe80::/10 link-local, fec0::/10 site-local and ff00::/8
15
- * multicast. An IPv4-mapped address (::ffff:0:0/96) is checked as the IPv4 address it carries. */
16
- const V6_PRIVATE = [["::", 8], ["fc00::", 7], ["fe80::", 10], ["fec0::", 10], ["ff00::", 8]];
14
+ * 64:ff9b::/96 and 64:ff9b:1::/48), 2001::/32 Teredo (a relay delivers it to the IPv4 address its last 32 bits hide,
15
+ * so it is refused whole), fc00::/7 unique-local, fe80::/10 link-local, fec0::/10 site-local and ff00::/8 multicast.
16
+ * An IPv4-mapped address (::ffff:0:0/96) is checked as the IPv4 address it carries. */
17
+ const V6_PRIVATE = [["::", 8], ["2001::", 32], ["fc00::", 7], ["fe80::", 10], ["fec0::", 10], ["ff00::", 8]];
17
18
  const v4 = (ip) => ip.split(".").reduce((n, octet) => n * 256 + Number(octet), 0);
18
19
  /** An IPv6 address's eight 16-bit groups, read through the URL parser's canonical form; null when it does not parse
19
20
  * (a zone index among them). */
@@ -32,16 +33,80 @@ function v6Groups(ip) {
32
33
  return [...head, ...new Array(8 - head.length - tail.length).fill(0), ...tail];
33
34
  }
34
35
  const inV6 = (groups, base, bits) => groups.every((group, i) => { const span = Math.max(0, Math.min(16, bits - 16 * i)); const mask = (0xffff << (16 - span)) & 0xffff; return (group & mask) === (base[i] & mask); });
35
- /** Any address but a public unicast one, v4 and v6 (see V4_PRIVATE and V6_PRIVATE); what does not parse as one too. */
36
+ /** The environment variable listing the hosting cluster's own internal ranges: comma-separated CIDRs (an address alone is
37
+ * one host) that are public address space on paper but internal where the server runs, such as a
38
+ * managed Kubernetes cluster's Service range. Its value replaces the default; unset or blank, the default holds. */
39
+ const CLUSTER_INTERNAL_CIDRS_ENV = "CLUSTER_INTERNAL_CIDRS";
40
+ /** GKE's default Service range: Google-owned space that is never routed publicly, where in-cluster names resolve. */
41
+ const DEFAULT_CLUSTER_INTERNAL_CIDRS = "34.118.224.0/20";
42
+ let parsedClusterRanges;
43
+ /** One CIDR (or a lone address) as its base and prefix length; null when it is not one, or when it sets bits past its
44
+ * prefix (a typo such as `34.118.236.1/20` is refused, not read as a wider or narrower range). */
45
+ function clusterRange(entry) {
46
+ const [address, prefix, extra] = entry.split("/");
47
+ if (extra !== undefined || !address)
48
+ return null;
49
+ const family = net.isIPv4(address) ? 4 : net.isIPv6(address) ? 6 : 0;
50
+ if (!family)
51
+ return null;
52
+ const width = family === 4 ? 32 : 128;
53
+ const bits = prefix === undefined ? width : /^\d{1,3}$/.test(prefix) ? Number(prefix) : NaN;
54
+ if (!(bits >= 0 && bits <= width))
55
+ return null;
56
+ if (family === 4) {
57
+ const base = v4(address);
58
+ return base % 2 ** (32 - bits) === 0 ? { family, base, bits } : null;
59
+ }
60
+ const groups = v6Groups(address);
61
+ if (!groups)
62
+ return null;
63
+ const hostBits = groups.some((group, i) => { const span = Math.max(0, Math.min(16, bits - 16 * i)); return (group & ~(0xffff << (16 - span)) & 0xffff) !== 0; });
64
+ return hostBits ? null : { family, groups, bits };
65
+ }
66
+ /** The cluster's internal ranges, read from this process's environment at each use (CLUSTER_INTERNAL_CIDRS_ENV); null when
67
+ * the value holds an entry that is not a CIDR, or names none, so a bad setting refuses every address instead of opening
68
+ * one. */
69
+ function clusterInternalRanges() {
70
+ const value = process.env[CLUSTER_INTERNAL_CIDRS_ENV]?.trim() || DEFAULT_CLUSTER_INTERNAL_CIDRS;
71
+ if (parsedClusterRanges?.value === value)
72
+ return parsedClusterRanges.ranges;
73
+ let ranges = { v4: [], v6: [] };
74
+ for (const entry of value.split(",").map((part) => part.trim()).filter(Boolean)) {
75
+ const range = clusterRange(entry);
76
+ if (!range) {
77
+ ranges = null;
78
+ break;
79
+ }
80
+ if (range.family === 4)
81
+ ranges.v4.push([range.base, range.bits]);
82
+ else
83
+ ranges.v6.push([range.groups, range.bits]);
84
+ }
85
+ // A value of separators alone names no range: as malformed as a bad entry, never an empty list.
86
+ if (ranges && !ranges.v4.length && !ranges.v6.length)
87
+ ranges = null;
88
+ parsedClusterRanges = { value, ranges };
89
+ return ranges;
90
+ }
91
+ const inV4 = (ip, base, bits) => Math.floor(v4(ip) / 2 ** (32 - bits)) === Math.floor(base / 2 ** (32 - bits));
92
+ /** Any address but a public unicast one, v4 and v6 (see V4_PRIVATE and V6_PRIVATE), or one in the hosting cluster's
93
+ * internal ranges (CLUSTER_INTERNAL_CIDRS_ENV); what does not parse as one too. The one address judgment every
94
+ * outbound guard here uses: web_fetch, web_save, the webhook and the MCP, calendar and feed checks. */
36
95
  export function isPrivateAddress(ip) {
96
+ const cluster = clusterInternalRanges();
97
+ if (!cluster)
98
+ return true;
37
99
  if (net.isIPv4(ip))
38
- return V4_PRIVATE.some(([base, bits]) => Math.floor(v4(ip) / 2 ** (32 - bits)) === Math.floor(base / 2 ** (32 - bits)));
100
+ return V4_PRIVATE.some(([base, bits]) => inV4(ip, base, bits)) || cluster.v4.some(([base, bits]) => inV4(ip, base, bits));
39
101
  const groups = net.isIPv6(ip) ? v6Groups(ip) : null;
40
102
  if (!groups)
41
103
  return true;
42
104
  if (groups.slice(0, 5).every((group) => group === 0) && groups[5] === 0xffff)
43
105
  return isPrivateAddress([groups[6] >> 8, groups[6] & 0xff, groups[7] >> 8, groups[7] & 0xff].join("."));
44
- return V6_PRIVATE.some(([base, bits]) => inV6(groups, v6Groups(base), bits));
106
+ // 6to4 (2002::/16, RFC 3056) carries an IPv4 address in its next 32 bits, which a relay delivers to: judged as that one.
107
+ if (groups[0] === 0x2002)
108
+ return isPrivateAddress([groups[1] >> 8, groups[1] & 0xff, groups[2] >> 8, groups[2] & 0xff].join("."));
109
+ return V6_PRIVATE.some(([base, bits]) => inV6(groups, v6Groups(base), bits)) || cluster.v6.some(([base, bits]) => inV6(groups, base, bits));
45
110
  }
46
111
  /** Answers `address` for any name: the address a request was checked against is the one it connects to. */
47
112
  export const pinnedLookup = (address) => (_host, options, callback) => {
@@ -66,63 +131,147 @@ function untilAborted(work, signal) {
66
131
  work().then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
67
132
  });
68
133
  }
69
- /**
70
- * Fetches `url` from a public host, following at most 5 redirects, each hop resolved, checked and dialled at the
71
- * address checked. A 2xx answer of a text type is read whole, up to `maxBytes`; another status comes back without its
72
- * body. Refused (`BrowserFailureError` `refused`), on the first hop or a redirect: a scheme other than http(s); a host
73
- * that is local by name or resolves to any private address; a port other than 80 or 443; too many redirects; a 2xx body
74
- * that is not text or is over the cap. `signal` ends the fetch at any point, a hop's name lookup included (it rejects
75
- * with the signal's reason), and an aborted hop is never dialled.
76
- */
77
- export async function publicFetch(url, options = {}) {
78
- const lookup = options.lookup ?? (async (host) => (await dns.lookup(host, { all: true })).map((a) => a.address));
79
- const request = options.fetchImpl ?? ((target, init) => undiciFetch(target, init));
134
+ /** The content types read as text: any text/*, application/json and application/xml, and any application/<name>+xml
135
+ * or application/<name>+json (atom, rss, xhtml, ld+json), so a site's feed reads like its pages. Anything else (a PDF,
136
+ * a zip, octet-stream, an image/svg+xml) is refused. */
137
+ const TEXT_TYPE = /^(text\/|application\/(json|xml|[\w.!#$&^-]+\+(xml|json)\b))/i;
138
+ /** The types whose own <meta> may name their charset: HTML and XHTML. */
139
+ const HTML_TYPE = /^(text\/html|application\/xhtml\+xml)\s*(;|$)/i;
140
+ /** How far into a page a <meta> charset counts: the first 1024 bytes, as a browser's prescan reads. */
141
+ const PRESCAN_BYTES = 1024;
142
+ /** The charset a `charset=` parameter in `words` names (a Content-Type, or a <meta http-equiv> tag's content), quotes
143
+ * taken off; undefined when there is none. */
144
+ const charsetParam = (words) => /(?:^|[;\s])charset\s*=\s*["']?([^"';\s]+)/i.exec(words)?.[1];
145
+ /** A decoder for `label`, or undefined when no encoding goes by it. A page's <meta> naming UTF-16 is read as UTF-8, as a
146
+ * browser does: a page whose bytes are UTF-16 could not have spelled the tag in ASCII. */
147
+ function decoderFor(label, fromMeta) {
148
+ if (label === undefined)
149
+ return undefined;
150
+ let decoder;
151
+ try {
152
+ decoder = new TextDecoder(label);
153
+ }
154
+ catch {
155
+ return undefined;
156
+ }
157
+ return fromMeta && decoder.encoding.startsWith("utf-16") ? new TextDecoder("utf-8") : decoder;
158
+ }
159
+ /** A decoder for the charset an HTML page's own <meta> names in its first 1024 bytes: the first `<meta charset>` or
160
+ * `<meta http-equiv="Content-Type" content="...; charset=...">` whose label an encoding goes by, as a browser's
161
+ * prescan takes it. A tag inside a comment is not read. Undefined when none does. */
162
+ function metaDecoder(bytes) {
163
+ // latin1 maps each byte to one char: an ASCII tag reads the same whatever the page's charset. A comment, and one left
164
+ // open at the scan's end, is dropped first.
165
+ const head = Buffer.from(bytes.buffer, bytes.byteOffset, Math.min(bytes.byteLength, PRESCAN_BYTES)).toString("latin1").replace(/<!--[\s\S]*?(?:-->|$)/g, "");
166
+ for (const [tag] of head.matchAll(/<meta\b[^>]*>/gi)) {
167
+ const attributes = new Map();
168
+ for (const [, name, double, single, bare] of tag.slice(5).matchAll(/([^\s"'>/=]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/g)) {
169
+ const key = name.toLowerCase();
170
+ if (!attributes.has(key))
171
+ attributes.set(key, (double ?? single ?? bare ?? "").trim());
172
+ }
173
+ const charset = attributes.get("charset");
174
+ const said = charset ? charset : attributes.get("http-equiv")?.toLowerCase() === "content-type" ? charsetParam(attributes.get("content") ?? "") : undefined;
175
+ const decoder = decoderFor(said, true);
176
+ if (decoder)
177
+ return decoder;
178
+ }
179
+ return undefined;
180
+ }
181
+ /** The encoding a page's byte order mark names (UTF-8, UTF-16LE, UTF-16BE), or undefined with none. */
182
+ function bomEncoding(bytes) {
183
+ if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf)
184
+ return "utf-8";
185
+ if (bytes[0] === 0xff && bytes[1] === 0xfe)
186
+ return "utf-16le";
187
+ if (bytes[0] === 0xfe && bytes[1] === 0xff)
188
+ return "utf-16be";
189
+ return undefined;
190
+ }
191
+ /** A text page's `bytes` as text, decoded as a browser decodes it: by its byte order mark, else its Content-Type's
192
+ * `charset`, else (an HTML page) its <meta> charset in the first 1024 bytes, else UTF-8. A label no encoding goes by is
193
+ * passed over for the next. The mark itself is not kept. Bytes the charset cannot read become U+FFFD. Of a body `cut`
194
+ * short, a character the cut splits is left out, never decoded as U+FFFD: the decoder is not flushed at the end. */
195
+ function pageText(bytes, contentType, cut = false) {
196
+ const bom = bomEncoding(bytes);
197
+ const decoder = (bom ? new TextDecoder(bom) : undefined) ?? decoderFor(charsetParam(contentType), false) ?? (HTML_TYPE.test(contentType) ? metaDecoder(bytes) : undefined) ?? new TextDecoder("utf-8");
198
+ return cut ? decoder.decode(bytes, { stream: true }) : decoder.decode(bytes);
199
+ }
200
+ const MIB = 1024 * 1024;
201
+ /** The options checked before any lookup: `maxBytes` (default 5 MiB) a whole number of bytes above 0, and
202
+ * `maxRedirects` a whole number from 0 to 5. */
203
+ function capOf(options) {
80
204
  const maxBytes = options.maxBytes ?? PUBLIC_MAX_BYTES;
81
205
  if (!Number.isSafeInteger(maxBytes) || maxBytes < 1)
82
206
  throw new RangeError(`maxBytes must be a whole number of bytes above 0, not ${maxBytes}`);
207
+ const redirects = options.maxRedirects ?? MAX_REDIRECTS;
208
+ if (!Number.isSafeInteger(redirects) || redirects < 0 || redirects > MAX_REDIRECTS)
209
+ throw new RangeError(`maxRedirects must be a whole number from 0 to ${MAX_REDIRECTS}, not ${redirects}`);
210
+ return maxBytes;
211
+ }
212
+ const systemLookup = async (host) => (await dns.lookup(host, { all: true })).map((a) => a.address);
213
+ /** One hop's checks before it is dialled: its name is not a local one, every address it resolves to is public, and its
214
+ * port is 80 or 443. Answers the addresses, the first of which the hop dials; throws the refusal otherwise. */
215
+ async function hopAddresses(target, lookup, signal) {
216
+ const host = target.hostname.replace(/^\[|\]$/g, "");
217
+ // Trailing dots name the same host (WHATWG keeps them): the name checks read the host without any.
218
+ const name = host.replace(/\.+$/, "");
219
+ if (name === "localhost" || name.endsWith(".localhost") || name.endsWith(".local") || name.endsWith(".internal"))
220
+ throw refusedError(`refused: ${host} is not a public host`);
221
+ const addresses = net.isIP(host) ? [host] : await untilAborted(() => lookup(host), signal);
222
+ if (!addresses.length || addresses.some(isPrivateAddress))
223
+ throw refusedError(`refused: ${host} is not a public host`);
224
+ if (!PORTS.has(target.port))
225
+ throw refusedError(`refused: port ${target.port} is not 80 or 443`);
226
+ signal?.throwIfAborted();
227
+ return addresses;
228
+ }
229
+ /** One hop's URL checks, before its name is resolved: its scheme matches `scheme`, and it holds no user name or password
230
+ * (no credentials go out, and undici's own refusal of such a URL quotes it whole). `redirected` when the hop is a
231
+ * redirect's target. The refusal never quotes the URL. */
232
+ function hopUrl(target, [scheme, schemeName], redirected) {
233
+ if (!scheme.test(target.protocol))
234
+ throw refusedError(redirected ? `refused: a redirect left ${schemeName}` : `refused: ${target.protocol} is not ${schemeName}`);
235
+ if (target.username || target.password)
236
+ throw refusedError(`refused: ${redirected ? "a redirect to a URL holding" : "the URL holds"} a user name or password`);
237
+ }
238
+ /** Whether publicFetch's first hop would be dialled for `url`: hopUrl's and hopAddresses' checks, http(s), with nothing
239
+ * sent. Resolves when it passes; throws publicFetch's own refusal when it does not. */
240
+ export async function publicCheck(url, options = {}) {
241
+ const target = new URL(url);
242
+ hopUrl(target, [/^https?:$/, "http(s)"], false);
243
+ await hopAddresses(target, options.lookup ?? systemLookup, options.signal);
244
+ }
245
+ /**
246
+ * The hop loop both answers share: `url` fetched from a public host, following at most 5 redirects, each hop, the first
247
+ * and every redirect's alike, checked (hopUrl, then hopAddresses) and dialled at the address checked (a redirect's once
248
+ * `beforeRedirect` lets it), asking for `accept`. The answer that ends the redirects goes to `answer`, which reads what
249
+ * it needs of it; whatever it leaves unread is cancelled, and the hop's connection closed, once it returns or throws.
250
+ */
251
+ async function publicHops(url, options, accept, answer, send = undefined) {
252
+ const lookup = options.lookup ?? systemLookup;
253
+ const request = options.fetchImpl ?? ((target, init) => undiciFetch(target, init));
254
+ const scheme = options.httpsOnly ? [/^https:$/, "https"] : [/^https?:$/, "http(s)"];
255
+ const most = options.maxRedirects ?? MAX_REDIRECTS;
83
256
  let target = new URL(url);
84
- if (!/^https?:$/.test(target.protocol))
85
- throw refusedError(`refused: ${target.protocol} is not http(s)`);
86
257
  for (let hop = 0;; hop += 1) {
87
- const host = target.hostname.replace(/^\[|\]$/g, "");
88
- if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal"))
89
- throw refusedError(`refused: ${host} is not a public host`);
90
- const addresses = net.isIP(host) ? [host] : await untilAborted(() => lookup(host), options.signal);
91
- if (!addresses.length || addresses.some(isPrivateAddress))
92
- throw refusedError(`refused: ${host} is not a public host`);
93
- if (!PORTS.has(target.port))
94
- throw refusedError(`refused: port ${target.port} is not 80 or 443`);
95
- options.signal?.throwIfAborted();
258
+ hopUrl(target, scheme, hop > 0);
259
+ const addresses = await hopAddresses(target, lookup, options.signal);
260
+ // A redirect's target, checked, is the caller's to refuse before it is dialled (beforeRedirect).
261
+ const ask = options.beforeRedirect;
262
+ if (hop > 0 && ask)
263
+ await untilAborted(async () => ask(target.href), options.signal);
96
264
  const dispatcher = new Agent({ connect: { lookup: pinnedLookup(addresses[0]) } });
97
265
  let res;
98
266
  try {
99
- res = await request(target, { redirect: "manual", signal: options.signal, dispatcher, headers: { accept: "text/html,text/plain;q=0.9,*/*;q=0.1", "user-agent": "pi-browser" } });
267
+ res = await request(target, { redirect: "manual", signal: options.signal, dispatcher, ...(send ? { method: send.method, body: send.body } : {}), headers: { accept, "user-agent": options.userAgent ?? "pi-browser", ...send?.headers } });
100
268
  if (res.status >= 300 && res.status < 400 && res.headers.get("location")) {
101
- if (hop >= MAX_REDIRECTS)
102
- throw refusedError("refused: too many redirects");
269
+ if (hop >= most)
270
+ throw refusedError(most === 0 ? `refused: a redirect, and this ${send ? "upload" : "download"} follows none` : "refused: too many redirects");
103
271
  target = new URL(res.headers.get("location"), target);
104
- if (!/^https?:$/.test(target.protocol))
105
- throw refusedError("refused: a redirect left http(s)");
106
272
  continue;
107
273
  }
108
- const contentType = res.headers.get("content-type") ?? "";
109
- if (!res.ok)
110
- return { url: target.href, status: res.status, contentType, body: null };
111
- if (!/^(text\/|application\/(xhtml\+xml|json|xml))/i.test(contentType))
112
- throw refusedError(`refused: ${contentType || "an unknown content type"} is not text`);
113
- const chunks = [];
114
- let size = 0;
115
- for (const reader = res.body.getReader();;) {
116
- const { done, value } = await reader.read();
117
- if (done)
118
- break;
119
- if ((size += value.length) > maxBytes) {
120
- await reader.cancel();
121
- throw refusedError(`refused: the page is over ${maxBytes === PUBLIC_MAX_BYTES ? "5 MiB" : `${maxBytes} bytes`}`);
122
- }
123
- chunks.push(value);
124
- }
125
- return { url: target.href, status: res.status, contentType, body: Buffer.concat(chunks).toString("utf8") };
274
+ return await answer(res, target);
126
275
  }
127
276
  finally {
128
277
  // A reply refused unread (not text, an error status, a redirect) still holds its connection: close() waits
@@ -132,3 +281,151 @@ export async function publicFetch(url, options = {}) {
132
281
  }
133
282
  }
134
283
  }
284
+ /** `reader`'s next chunk; with `signal`, ended at the signal's abort with its reason (the body cancelled), whatever the
285
+ * fetch does with the signal. */
286
+ const nextChunk = (reader, signal) => signal ? untilAborted(() => reader.read(), signal).catch(async (error) => { await reader.cancel(error).catch(() => undefined); throw error; }) : reader.read();
287
+ /** `body` read whole, refused (`over`'s words) once it passes `maxBytes`: cut off while it is read, not after. With
288
+ * `signal`, each read also ends at the signal's abort, with its reason. The chunks are kept and joined at the end, so a
289
+ * body peaks at about twice its size in memory: readStated is the path for a body whose length is stated. */
290
+ async function readCapped(body, maxBytes, over, signal) {
291
+ const chunks = [];
292
+ let size = 0;
293
+ for (const reader = body.getReader();;) {
294
+ const { done, value } = await nextChunk(reader, signal);
295
+ if (done)
296
+ break;
297
+ // Refused as it passes the cap, before anything read is joined: a refused body is never copied.
298
+ if ((size += value.length) > maxBytes) {
299
+ await reader.cancel();
300
+ throw refusedError(over);
301
+ }
302
+ chunks.push(value);
303
+ }
304
+ return Buffer.concat(chunks);
305
+ }
306
+ /** `body`'s first `maxBytes`, and whether it went on past them (`cut`): read until it ends or passes them, then the rest
307
+ * cancelled unread (publicFetch's `cut`; readCapped refuses instead). `signal` as readCapped's. */
308
+ async function readUpTo(body, maxBytes, signal) {
309
+ const chunks = [];
310
+ let size = 0;
311
+ for (const reader = body.getReader();;) {
312
+ const { done, value } = await nextChunk(reader, signal);
313
+ if (done)
314
+ break;
315
+ if (size + value.length > maxBytes) {
316
+ chunks.push(value.subarray(0, maxBytes - size));
317
+ await reader.cancel();
318
+ return { bytes: Buffer.concat(chunks), cut: true };
319
+ }
320
+ size += value.length;
321
+ chunks.push(value);
322
+ }
323
+ return { bytes: Buffer.concat(chunks), cut: false };
324
+ }
325
+ /** `body`, whose host stated it is `length` bytes, read into one buffer of that length, allocated before the first chunk:
326
+ * the file is held once, never joined into a second copy. A chunk that runs past `length` is refused as it comes, the
327
+ * body cancelled; a body that ends short of it is refused at its end. `signal` as readCapped's. */
328
+ async function readStated(body, length, signal) {
329
+ const bytes = new Uint8Array(length);
330
+ let at = 0;
331
+ for (const reader = body.getReader();;) {
332
+ const { done, value } = await nextChunk(reader, signal);
333
+ if (done)
334
+ break;
335
+ if (value.length > length - at) {
336
+ await reader.cancel();
337
+ throw refusedError(`refused: the file is longer than the ${length} bytes its host stated`);
338
+ }
339
+ bytes.set(value, at);
340
+ at += value.length;
341
+ }
342
+ if (at !== length)
343
+ throw refusedError(`refused: the file ended at ${at} of the ${length} bytes its host stated`);
344
+ return bytes;
345
+ }
346
+ /** The length a 2xx reply states for the body a fetch hands over: its content-length when that is a plain count and the
347
+ * body is not encoded (a gzip reply's length counts the bytes on the wire, not the decoded ones); else undefined. */
348
+ function statedLength(headers) {
349
+ const said = headers.get("content-length")?.trim();
350
+ if (said === undefined || !/^\d{1,16}$/.test(said))
351
+ return undefined;
352
+ const encoding = headers.get("content-encoding")?.trim().toLowerCase();
353
+ if (encoding && encoding !== "identity")
354
+ return undefined;
355
+ const length = Number(said);
356
+ return Number.isSafeInteger(length) ? length : undefined;
357
+ }
358
+ /**
359
+ * Fetches `url` from a public host, following at most 5 redirects (or `maxRedirects`), each hop resolved, checked and dialled at the
360
+ * address checked. A 2xx answer of a text type is read whole, up to `maxBytes`, and
361
+ * decoded by the charset it declares (pageText); another status comes back without its
362
+ * body. Refused (`BrowserFailureError` `refused`), on the first hop or a redirect: a scheme other than http(s) (other
363
+ * than https, with `httpsOnly`); a URL holding a user name or password; a host that is local by name or resolves to any
364
+ * private address; a port other than 80
365
+ * or 443; too many redirects (any, with `maxRedirects` 0); a 2xx body that is not text or is over the cap. With `cut`, a
366
+ * body over the cap is not refused: its first `maxBytes` are read and decoded (a character the cut splits dropped), the
367
+ * rest is never read, and the answer says `cut`. `signal` ends the fetch at any point, a
368
+ * hop's name lookup included (it rejects with the signal's reason), and an aborted hop is never dialled.
369
+ */
370
+ export async function publicFetch(url, options = {}) {
371
+ const maxBytes = capOf(options);
372
+ return publicHops(url, options, "text/html,text/plain;q=0.9,*/*;q=0.1", async (res, target) => {
373
+ const contentType = res.headers.get("content-type") ?? "";
374
+ if (!res.ok)
375
+ return { url: target.href, status: res.status, contentType, body: null };
376
+ // A 2xx with no body at all (204, 205) is an empty page, whatever type it names.
377
+ if (!res.body)
378
+ return { url: target.href, status: res.status, contentType, body: "" };
379
+ if (!TEXT_TYPE.test(contentType))
380
+ throw refusedError(`refused: ${contentType || "an unknown content type"} is not text`);
381
+ if (options.cut) {
382
+ const { bytes, cut } = await readUpTo(res.body, maxBytes);
383
+ if (!cut)
384
+ return { url: target.href, status: res.status, contentType, body: pageText(bytes, contentType) };
385
+ return { url: target.href, status: res.status, contentType, body: pageText(bytes, contentType, true), cut: true };
386
+ }
387
+ const body = await readCapped(res.body, maxBytes, `refused: the page is over ${maxBytes === PUBLIC_MAX_BYTES ? "5 MiB" : `${maxBytes} bytes`}`);
388
+ return { url: target.href, status: res.status, contentType, body: pageText(body, contentType) };
389
+ });
390
+ }
391
+ /**
392
+ * Downloads `url` from a public host: publicFetch's hops and refusals (scheme, user name or password, local or private host, port, redirects,
393
+ * the signal), with any content type accepted and the body kept as bytes, up to `maxBytes` (default 5 MiB). A 2xx answer
394
+ * is read whole; another status comes back with `bytes` null. A body over the cap is refused (`refused: the file is over
395
+ * <cap>`): before a byte is read when its content-length says so, else as soon as it passes it. A body whose length its
396
+ * host states (an unencoded reply's content-length) is read into one buffer of that length, so it is held once; one longer
397
+ * than stated is refused as it runs past it, one shorter at its end. With no stated length the chunks are joined at the
398
+ * end, about twice the file's size at the peak. `signal` ends the body's read too, with its reason.
399
+ */
400
+ export async function publicDownload(url, options = {}) {
401
+ const maxBytes = capOf(options);
402
+ const over = `refused: the file is over ${maxBytes % MIB === 0 ? `${maxBytes / MIB} MiB` : `${maxBytes} bytes`}`;
403
+ return publicHops(url, options, "*/*", async (res, target) => {
404
+ const contentType = res.headers.get("content-type") ?? "";
405
+ if (!res.ok)
406
+ return { url: target.href, status: res.status, contentType, bytes: null };
407
+ if (!res.body)
408
+ return { url: target.href, status: res.status, contentType, bytes: new Uint8Array(0) };
409
+ const declared = Number(res.headers.get("content-length") ?? Number.NaN);
410
+ if (Number.isFinite(declared) && declared > maxBytes)
411
+ throw refusedError(over);
412
+ // A stated length (at most the cap, checked above): the bytes read into one buffer of it. None: the chunks joined at
413
+ // the end, about twice the file's size at its peak.
414
+ const length = statedLength(res.headers);
415
+ if (length !== undefined)
416
+ return { url: target.href, status: res.status, contentType, bytes: await readStated(res.body, length, options.signal) };
417
+ const body = await readCapped(res.body, maxBytes, over, options.signal);
418
+ return { url: target.href, status: res.status, contentType, bytes: new Uint8Array(body.buffer, body.byteOffset, body.byteLength) };
419
+ });
420
+ }
421
+ /**
422
+ * Uploads `bytes` to `url` on a public host, as one PUT: publicFetch's checks of its one hop (a user name or password,
423
+ * a local or private host, a port, the signal), https only, and no redirect followed, so the bytes go to the URL given
424
+ * or nowhere (a redirect is refused before its target is dialled). `contentType`, when given, is sent as the body's
425
+ * type; else none is. The answer's body is not read; its status comes back for the caller to judge, an error status
426
+ * included.
427
+ */
428
+ export async function publicUpload(url, bytes, options = {}) {
429
+ const { contentType, ...rest } = options;
430
+ return publicHops(url, { ...rest, httpsOnly: true, maxRedirects: 0 }, "*/*", async (res, target) => ({ url: target.href, status: res.status }), { method: "PUT", body: bytes, headers: contentType ? { "content-type": contentType } : {} });
431
+ }
@@ -1,6 +1,7 @@
1
1
  // read-page.ts's worker. For `workerData`, a Job: the page's markdown, posted once as { text } (with { title, links }
2
- // when the job has a `url`, and { truncated, html_chars } when the worker cut the page), or as { error } when the
3
- // conversion threw (a page nested past the stack, say).
2
+ // when the job has a `url`, { links_truncated } too when the link caps stopped their resolution, and { truncated,
3
+ // html_chars } when the worker cut the page), or as { error } when the conversion threw (a page nested past the stack,
4
+ // say).
4
5
  import { parentPort, workerData } from "node:worker_threads";
5
6
  import { TextNode } from "node-html-parser";
6
7
  import { markdownOf } from "./page-markdown.js";
@@ -21,8 +22,8 @@ if (parentPort) {
21
22
  if (job.url !== undefined) {
22
23
  const scan = new PageScan(html, job.url, (text) => new TextNode(text).text, false);
23
24
  scan.step(Number.POSITIVE_INFINITY);
24
- const { title, links } = scan.result();
25
- read = { title, links };
25
+ const { title, links, linksCut } = scan.result();
26
+ read = { title, links, ...(linksCut ? { links_truncated: true } : {}) };
26
27
  }
27
28
  parentPort.postMessage({ ...read, ...cut, text: markdownOf(html) });
28
29
  }
@@ -1,41 +1,56 @@
1
+ export { READ_LINKS_MAX, READ_LINKS_MAX_CHARS } from "./page-scan.js";
1
2
  /** The most of a page's HTML that is read, counted once its script, style, svg, noscript and template blocks and its
2
3
  * comments are dropped. A million characters of go.dev/dl converts in about 0.8 s on a busy 48-core host and gives
3
4
  * 590,000 characters of markdown, ten times the 60,000 one web_fetch answer carries. */
4
5
  export declare const READ_MAX_CHARS = 1000000;
5
6
  /** How long the worker has for the markdown by default: six times what READ_MAX_CHARS of tables took. */
6
7
  export declare const READ_DEADLINE_MS = 5000;
8
+ /** The worker's heap by default, in MB (`heapMb`). */
9
+ export declare const READ_WORKER_HEAP_MB = 1024;
7
10
  /** `n` with its digits in groups of three ("3,154,060"): Intl's first use costs tens of milliseconds on the loop. */
8
11
  export declare const thousands: (n: number) => string;
9
12
  /** `converted`: "markdown", or "text" when the conversion did not finish in time (or failed) and the text is the page's
10
13
  * plain text. `truncated` and `html_chars` (the page's whole length, in characters) when the page was cut at
11
- * READ_MAX_CHARS before it was read: the text, the title and the links are then the cut page's. */
14
+ * READ_MAX_CHARS before it was read: the text, the title and the links are then the cut page's. `links_truncated` when
15
+ * READ_LINKS_MAX or READ_LINKS_MAX_CHARS stopped the links' resolution: `links` are then the page's first ones. */
12
16
  export type PageRead = {
13
17
  title: string;
14
18
  text: string;
15
19
  links: string[];
20
+ links_truncated?: true;
16
21
  converted: "markdown" | "text";
17
22
  truncated?: true;
18
23
  html_chars?: number;
19
24
  };
20
- /** `deadlineMs`: how long the conversion to markdown has (default READ_DEADLINE_MS). `signal` ends the read, the
21
- * conversion stopped, with the signal's reason. */
25
+ /** `deadlineMs`: how long the conversion to markdown has (default READ_DEADLINE_MS). `heapMb`: the worker's heap
26
+ * (default READ_WORKER_HEAP_MB, at least 16). `signal` ends the read, the conversion stopped, with the signal's reason. */
22
27
  export type ReadPageOptions = {
23
28
  deadlineMs?: number;
29
+ heapMb?: number;
24
30
  signal?: AbortSignal;
25
31
  };
32
+ /** readPage's refusal of a page whose read filled the worker's heap: it is not read again on the caller's thread. */
33
+ export declare class PageReadOutOfMemory extends Error {
34
+ readonly heapMb: number;
35
+ readonly name = "PageReadOutOfMemory";
36
+ readonly code = "PAGE_READ_OUT_OF_MEMORY";
37
+ constructor(heapMb: number);
38
+ }
26
39
  /**
27
40
  * An HTML page's title, its text as markdown, and the absolute http(s) URLs it links to (resolved against its
28
41
  * `<base href>` or `url`), each once, in page order. The event loop is never held for longer than one linear step of a
29
- * bounded part of the page (see the file's head and PageRead). Rejects only with `signal`'s reason.
42
+ * bounded part of the page (see the file's head and PageRead). Rejects with `signal`'s reason, or with
43
+ * PageReadOutOfMemory when the worker ran out of memory (the page is then not read on this thread).
30
44
  */
31
- export declare function readPage(html: string, url: string, { deadlineMs, signal }?: ReadPageOptions): Promise<PageRead>;
45
+ export declare function readPage(html: string, url: string, { deadlineMs, heapMb, signal }?: ReadPageOptions): Promise<PageRead>;
32
46
  /**
33
47
  * `html`'s markdown, made in the worker within `deadlineMs` (default READ_DEADLINE_MS): of its first article, else its
34
48
  * main, else its body element when `main` (mainOf), once its inert blocks are dropped, cut at READ_MAX_CHARS (then
35
- * `truncated`, and `html_chars` is the page's whole length). Null when the worker has not answered in time, failed, or
36
- * could not start. The event loop does no more than hand the worker the page. Rejects only with `signal`'s reason.
49
+ * `truncated`, and `html_chars` is the page's whole length). Null when the worker has not answered in time, failed (ran
50
+ * out of memory included), or could not start. The event loop does no more than hand the worker the page. Rejects only
51
+ * with `signal`'s reason.
37
52
  */
38
- export declare function htmlMarkdown(html: string, { main, deadlineMs, signal }?: {
53
+ export declare function htmlMarkdown(html: string, { main, deadlineMs, heapMb, signal }?: {
39
54
  main?: boolean;
40
55
  } & ReadPageOptions): Promise<{
41
56
  text: string;