@jini-ai/diagnostics 0.7.3-next.2 → 0.7.3-next.3
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/README.md +41 -0
- package/dist/browser-diagnostics.d.ts +43 -0
- package/dist/browser-diagnostics.js +92 -0
- package/dist/console-tee.d.ts +21 -6
- package/dist/console-tee.js +16 -4
- package/dist/domain-dns/index.d.ts +6 -14
- package/dist/domain-dns/index.js +4 -6
- package/dist/local-text.d.ts +4 -1
- package/dist/local-text.js +3 -2
- package/dist/observability/error-events.d.ts +32 -0
- package/dist/observability/error-events.js +32 -0
- package/dist/observability/fanout.js +9 -1
- package/dist/observability/index.d.ts +2 -1
- package/dist/observability/index.js +1 -0
- package/dist/observability/report-error.d.ts +9 -4
- package/dist/observability/report-error.js +7 -6
- package/dist/observability/telemetry-test.d.ts +1 -1
- package/dist/observability/tool-registrations.d.ts +21 -0
- package/dist/observability/tool-registrations.js +38 -0
- package/dist/observability/tracker-noop.d.ts +1 -1
- package/dist/observability/tracker-types.d.ts +2 -57
- package/dist/observability/tracker.d.ts +2 -1
- package/dist/observability/tracker.js +5 -1
- package/dist/redaction/repo-secret-scan.d.ts +48 -0
- package/dist/redaction/repo-secret-scan.js +77 -0
- package/dist/redaction/repo-secret-scan.node.d.ts +56 -0
- package/dist/redaction/repo-secret-scan.node.js +174 -0
- package/dist/redaction/secret-scan.d.ts +15 -0
- package/dist/redaction/secret-scan.js +18 -0
- package/dist/redaction/secrets-only.d.ts +1 -0
- package/dist/redaction/secrets-only.js +2 -0
- package/dist/redaction.d.ts +6 -0
- package/dist/redaction.js +9 -5
- package/dist/server-logs/agent-tools.d.ts +34 -0
- package/dist/server-logs/agent-tools.js +19 -0
- package/dist/server-logs/read-server-logs.d.ts +49 -0
- package/dist/server-logs/read-server-logs.js +90 -0
- package/dist/server-logs/tool-registrations.d.ts +25 -0
- package/dist/server-logs/tool-registrations.js +39 -0
- package/dist/tool-audit/repo.d.ts +107 -0
- package/dist/tool-audit/repo.js +117 -0
- package/dist/tool-audit/repo.memory.d.ts +31 -0
- package/dist/tool-audit/repo.memory.js +30 -0
- package/dist/tool-audit/repo.rows.d.ts +19 -0
- package/dist/tool-audit/repo.rows.js +2 -0
- package/dist/tool-audit/tool-gaps.repo.d.ts +22 -0
- package/dist/tool-audit/tool-gaps.repo.js +36 -0
- package/dist/web-evidence/agent-tools.d.ts +31 -0
- package/dist/web-evidence/agent-tools.js +61 -0
- package/dist/web-evidence/capture-budget.d.ts +3 -10
- package/dist/web-evidence/live-url.d.ts +86 -0
- package/dist/web-evidence/live-url.js +191 -0
- package/dist/web-evidence/page-performance-script.js +30 -32
- package/dist/web-evidence/playwright-browser.d.ts +2 -0
- package/dist/web-evidence/playwright-page-capture.d.ts +129 -0
- package/dist/web-evidence/playwright-page-capture.js +226 -0
- package/dist/web-evidence/public-page.d.ts +2 -1
- package/dist/web-evidence/published-page.d.ts +180 -0
- package/dist/web-evidence/published-page.js +172 -0
- package/dist/web-evidence/request-guard.d.ts +1 -31
- package/dist/web-evidence/site-path-policy.d.ts +20 -0
- package/dist/web-evidence/site-path-policy.js +54 -0
- package/dist/web-evidence/web-screenshot/agent-tools.d.ts +28 -0
- package/dist/web-evidence/web-screenshot/agent-tools.js +34 -0
- package/dist/web-evidence/web-screenshot/tool-registrations.d.ts +79 -0
- package/dist/web-evidence/web-screenshot/tool-registrations.js +47 -0
- package/package.json +114 -6
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { HttpRequest, HttpResponse } from "@jini-ai/core/primitives";
|
|
2
|
+
import { type OriginRegistryPort } from "@jini-ai/core/contracts/server/verified-origin";
|
|
3
|
+
import { type PageBodyOptions } from "./page-body.js";
|
|
4
|
+
import type { PublishedPageResult } from "./published-page.js";
|
|
5
|
+
/** One publish-peer row as far as live-origin selection reads it; `sealed` is null for an unkeyed row. */
|
|
6
|
+
export interface LivePeerRow {
|
|
7
|
+
readonly baseUrl: string;
|
|
8
|
+
readonly sealed: unknown;
|
|
9
|
+
}
|
|
10
|
+
/** The publish-history slice this file reads: distinct live URLs recorded for one workspace. */
|
|
11
|
+
export interface LivePublishHistory {
|
|
12
|
+
listLiveUrls(input: {
|
|
13
|
+
workspaceId: string;
|
|
14
|
+
}): Promise<readonly string[]>;
|
|
15
|
+
}
|
|
16
|
+
/** The peer-repository slice this file reads. */
|
|
17
|
+
export interface LivePeerRepo {
|
|
18
|
+
listByWorkspace(input: {
|
|
19
|
+
workspaceId: string;
|
|
20
|
+
}): Promise<readonly LivePeerRow[]>;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The host's publish-peer rule: which unkeyed row is the connected destination. The returned row is
|
|
24
|
+
* compared by identity against the rows it was handed, so it must be one of them, never a copy.
|
|
25
|
+
*/
|
|
26
|
+
export interface LiveOriginPolicy {
|
|
27
|
+
selectConnectedDestination(required: {
|
|
28
|
+
rows: readonly LivePeerRow[];
|
|
29
|
+
}, _optional?: Record<string, never>): LivePeerRow | null;
|
|
30
|
+
}
|
|
31
|
+
/** The guarded HTTP client slice this file calls: one request, one bounded response. */
|
|
32
|
+
export interface LiveHttpClient {
|
|
33
|
+
send(request: HttpRequest): Promise<HttpResponse>;
|
|
34
|
+
}
|
|
35
|
+
/** Recognizes the host egress guard's refusal; only its caller-safe text reaches the model. */
|
|
36
|
+
export type LiveEgressRefusal = (error: unknown) => error is {
|
|
37
|
+
callerSafeMessage: string;
|
|
38
|
+
};
|
|
39
|
+
/** Read ports only; missing ports on a test/older composition do not invent an address. */
|
|
40
|
+
export interface LiveOriginSourceDeps {
|
|
41
|
+
workspaceId: string;
|
|
42
|
+
publishContentPeerRepo?: LivePeerRepo;
|
|
43
|
+
publishHistoryStore?: LivePublishHistory;
|
|
44
|
+
originRegistry?: Pick<OriginRegistryPort, "canonicalOrigin">;
|
|
45
|
+
}
|
|
46
|
+
export interface FetchLiveUrlDeps {
|
|
47
|
+
/** Fresh workspace-scoped reads, never request Host or a caller-supplied arbitrary URL. */
|
|
48
|
+
listKnownOrigins(): Promise<readonly string[]>;
|
|
49
|
+
/** The shared guarded client with redirects disabled and a raw 1 MB ceiling. */
|
|
50
|
+
httpClient: LiveHttpClient;
|
|
51
|
+
/** The host's reserved first path segments (its routing `RESERVED_SEGMENTS`), never fetched live. */
|
|
52
|
+
reservedSegments: ReadonlySet<string>;
|
|
53
|
+
/** The host egress guard's refusal test; a match is projected as a model-visible input error. */
|
|
54
|
+
isEgressRefusal: LiveEgressRefusal;
|
|
55
|
+
/** Optional host instrumentation; receives no body, headers, credentials or query parameters. */
|
|
56
|
+
observeFetch?: (event: {
|
|
57
|
+
origin: string;
|
|
58
|
+
status?: number;
|
|
59
|
+
durationMs: number;
|
|
60
|
+
outcome: "response" | "refused" | "failed";
|
|
61
|
+
}) => void;
|
|
62
|
+
}
|
|
63
|
+
export interface FetchLiveUrlInput extends PageBodyOptions {
|
|
64
|
+
path: string;
|
|
65
|
+
origin?: string | undefined;
|
|
66
|
+
}
|
|
67
|
+
export type LivePageResult = PublishedPageResult & {
|
|
68
|
+
url: string;
|
|
69
|
+
origin: string;
|
|
70
|
+
redirects: string[];
|
|
71
|
+
untrusted: true;
|
|
72
|
+
location?: string;
|
|
73
|
+
};
|
|
74
|
+
/** Reads connected + keyed peers, full-ledger publish URL projection, and the trusted configured origin. */
|
|
75
|
+
export declare function listKnownLiveOrigins(deps: LiveOriginSourceDeps & LiveOriginPolicy, _optional?: {}): Promise<string[]>;
|
|
76
|
+
/**
|
|
77
|
+
* GETs this site's own live copy through the existing pinned-public-peer guard. One 15 s deadline
|
|
78
|
+
* covers origin reads, DNS, redirects and body reads. Cross-origin and fourth redirects are results.
|
|
79
|
+
* @returns Visitor response evidence; third-party text is explicitly untrusted, cookie values omitted.
|
|
80
|
+
* @throws ToolInputError for address selection, unsafe input/egress, or timeout.
|
|
81
|
+
*/
|
|
82
|
+
export declare function fetchLiveUrl({ deps, input }: {
|
|
83
|
+
deps: FetchLiveUrlDeps;
|
|
84
|
+
input: FetchLiveUrlInput;
|
|
85
|
+
}, _optional?: {}): Promise<LivePageResult>;
|
|
86
|
+
//# sourceMappingURL=live-url.d.ts.map
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { ToolInputError } from "@jini-ai/core";
|
|
2
|
+
import { OriginNotVerifiedError, } from "@jini-ai/core/contracts/server/verified-origin";
|
|
3
|
+
import { readPageBodyOptions, shapePageBody, DEFAULT_MAX_BODY_BYTES, MAX_MAX_BODY_BYTES } from "./page-body.js";
|
|
4
|
+
import { SameOriginPathError as PublishedPagePathError } from "./path-guard.js";
|
|
5
|
+
import { toCookieShapes } from "./cookie-shapes.js";
|
|
6
|
+
import { resolveSitePath } from "./site-path-policy.js";
|
|
7
|
+
const REDIRECTS = new Set([301, 302, 303, 307, 308]);
|
|
8
|
+
const NO_LIVE_ADDRESS = "fetch_live_url: this site has no known live address yet. Publish it first, or use fetch_published_page to check the local render.";
|
|
9
|
+
const DEADLINE_MESSAGE = "fetch_live_url: fetching the live page exceeded 15000ms. Check the hosting service before retrying.";
|
|
10
|
+
/** Normalizes saved URLs to origins; embedded credentials never become an allowed origin. */
|
|
11
|
+
function liveOrigin({ raw }, _optional = {}) {
|
|
12
|
+
let url;
|
|
13
|
+
try {
|
|
14
|
+
url = new URL(raw);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
throw new ToolInputError({ message: "fetch_live_url: a saved live address is invalid. Correct the publishing address and retry." });
|
|
18
|
+
}
|
|
19
|
+
if (url.protocol !== "https:" || url.port !== "" || url.username || url.password)
|
|
20
|
+
throw new ToolInputError({ message: "fetch_live_url: live origins must use HTTPS on port 443 without credentials." });
|
|
21
|
+
return url.origin;
|
|
22
|
+
}
|
|
23
|
+
/** Reads connected + keyed peers, full-ledger publish URL projection, and the trusted configured origin. */
|
|
24
|
+
export async function listKnownLiveOrigins(deps, _optional = {}) {
|
|
25
|
+
const peers = await deps.publishContentPeerRepo?.listByWorkspace({ workspaceId: deps.workspaceId }) ?? [];
|
|
26
|
+
const connected = deps.selectConnectedDestination({ rows: peers });
|
|
27
|
+
const urls = peers.filter(peer => peer.sealed !== null || peer === connected).map(peer => peer.baseUrl);
|
|
28
|
+
const historyUrls = await deps.publishHistoryStore?.listLiveUrls({ workspaceId: deps.workspaceId }) ?? [];
|
|
29
|
+
if (historyUrls.length > 200)
|
|
30
|
+
throw new ToolInputError({ message: "fetch_live_url: more than 200 distinct live addresses are recorded. Review the publish history before fetching." });
|
|
31
|
+
urls.push(...historyUrls);
|
|
32
|
+
urls.push(...await configuredLiveOrigins(deps));
|
|
33
|
+
return [...new Set(urls.map((raw) => liveOrigin({ raw })))].sort();
|
|
34
|
+
}
|
|
35
|
+
/** Reads only explicitly configured trust evidence; absent verification supplies no address. */
|
|
36
|
+
async function configuredLiveOrigins({ originRegistry, workspaceId }, _options = {}) {
|
|
37
|
+
if (!originRegistry)
|
|
38
|
+
return [];
|
|
39
|
+
try {
|
|
40
|
+
const configured = await originRegistry.canonicalOrigin({ workspaceId });
|
|
41
|
+
if (configured.source !== "workspace-setting")
|
|
42
|
+
return [];
|
|
43
|
+
const base = `${configured.scheme}://${configured.host}`;
|
|
44
|
+
const port = configured.port ? `:${configured.port}` : "";
|
|
45
|
+
return [`${base}${port}`];
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
if (!(error instanceof OriginNotVerifiedError))
|
|
49
|
+
throw error;
|
|
50
|
+
return [];
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** Only the origin itself is accepted for explicit selection, never a path/userinfo-bearing URL. */
|
|
54
|
+
function selectOrigin({ known, requested }, _optional = {}) {
|
|
55
|
+
const origins = [...new Set(known.map((raw) => liveOrigin({ raw })))].sort();
|
|
56
|
+
if (origins.length === 0)
|
|
57
|
+
throw new ToolInputError({ message: NO_LIVE_ADDRESS });
|
|
58
|
+
if (requested !== undefined) {
|
|
59
|
+
const normalized = liveOrigin({ raw: requested });
|
|
60
|
+
const explicit = new URL(requested);
|
|
61
|
+
if (explicit.pathname !== "/" || explicit.search || explicit.hash)
|
|
62
|
+
throw new ToolInputError({ message: `fetch_live_url: origin is not a known live address. Pass one of: ${origins.join(", ")}.` });
|
|
63
|
+
if (!origins.includes(normalized))
|
|
64
|
+
throw new ToolInputError({ message: `fetch_live_url: origin is not a known live address. Pass one of: ${origins.join(", ")}.` });
|
|
65
|
+
return normalized;
|
|
66
|
+
}
|
|
67
|
+
if (origins.length > 1)
|
|
68
|
+
throw new ToolInputError({ message: `fetch_live_url: several live origins are known. Pass origin as one of: ${origins.join(", ")}.` });
|
|
69
|
+
const origin = origins[0];
|
|
70
|
+
if (origin === undefined)
|
|
71
|
+
throw new ToolInputError({ message: NO_LIVE_ADDRESS });
|
|
72
|
+
return origin;
|
|
73
|
+
}
|
|
74
|
+
/** Reuses the local path boundary while retaining actionable errors at the assistant boundary. */
|
|
75
|
+
function resolveLivePath({ path, origin, reservedSegments }, _optional = {}) {
|
|
76
|
+
try {
|
|
77
|
+
return resolveSitePath({ raw: path, base: origin, reservedSegments });
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
if (error instanceof PublishedPagePathError)
|
|
81
|
+
throw new ToolInputError({ message: `fetch_live_url: ${error.message}` });
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** Validates raw and resolved same-origin paths before URL normalization can erase traversal. */
|
|
86
|
+
function redirectTarget({ location, current, origin, reservedSegments }, _optional = {}) {
|
|
87
|
+
let next;
|
|
88
|
+
try {
|
|
89
|
+
next = new URL(location, current);
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
throw new ToolInputError({ message: "fetch_live_url: the live site returned an invalid redirect address. Check the hosting service before retrying." });
|
|
93
|
+
}
|
|
94
|
+
if (next.origin !== origin)
|
|
95
|
+
return null;
|
|
96
|
+
if (next.username || next.password)
|
|
97
|
+
throw new ToolInputError({ message: "fetch_live_url: redirects with embedded credentials are refused." });
|
|
98
|
+
const rawPath = location.replace(/^(?:[a-z][a-z0-9+.-]*:)?\/\/[^/?#]*/i, "").split("#")[0]; // split always returns a first piece
|
|
99
|
+
resolveLivePath({ path: rawPath.startsWith("/") ? rawPath : "/" + rawPath, origin, reservedSegments });
|
|
100
|
+
resolveLivePath({ path: next.pathname + next.search, origin, reservedSegments });
|
|
101
|
+
next.hash = "";
|
|
102
|
+
return next.href;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* GETs this site's own live copy through the existing pinned-public-peer guard. One 15 s deadline
|
|
106
|
+
* covers origin reads, DNS, redirects and body reads. Cross-origin and fourth redirects are results.
|
|
107
|
+
* @returns Visitor response evidence; third-party text is explicitly untrusted, cookie values omitted.
|
|
108
|
+
* @throws ToolInputError for address selection, unsafe input/egress, or timeout.
|
|
109
|
+
*/
|
|
110
|
+
export async function fetchLiveUrl({ deps, input }, _optional = {}) {
|
|
111
|
+
const options = readPageBodyOptions({ input: input });
|
|
112
|
+
const deadline = AbortSignal.timeout(15_000);
|
|
113
|
+
return awaitWithDeadline({ work: fetchWithinDeadline({ deps, input, options, deadline }), signal: deadline });
|
|
114
|
+
}
|
|
115
|
+
/** One bounded operation, including slow repositories and time between redirect hops. */
|
|
116
|
+
async function fetchWithinDeadline({ deps, input, options, deadline }, _optional = {}) {
|
|
117
|
+
const started = Date.now();
|
|
118
|
+
const origin = selectOrigin({ known: await deps.listKnownOrigins(), requested: input.origin });
|
|
119
|
+
const path = resolveLivePath({ path: input.path, origin, reservedSegments: deps.reservedSegments });
|
|
120
|
+
const rawReadCap = options.textOnly || options.find !== undefined ? MAX_MAX_BODY_BYTES : options.maxBytes ?? DEFAULT_MAX_BODY_BYTES;
|
|
121
|
+
let url = origin + path;
|
|
122
|
+
const redirects = [];
|
|
123
|
+
for (;;) {
|
|
124
|
+
deadline.throwIfAborted();
|
|
125
|
+
const response = await sendPage({ deps, url, signal: deadline, timeoutMs: Math.max(1, 15_000 - (Date.now() - started)), maxResponseBytes: rawReadCap });
|
|
126
|
+
const headers = pageHeaders(response);
|
|
127
|
+
const location = headers.location;
|
|
128
|
+
if (REDIRECTS.has(response.status) && location && redirects.length < 3) {
|
|
129
|
+
const next = redirectTarget({ location, current: url, origin, reservedSegments: deps.reservedSegments });
|
|
130
|
+
if (next !== null) {
|
|
131
|
+
redirects.push(next);
|
|
132
|
+
url = next;
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return livePageResult({ response, headers, options, url, origin, redirects });
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** Header names are case-insensitive; cookie values are projected separately. */
|
|
140
|
+
function pageHeaders({ headers }, _options = {}) {
|
|
141
|
+
const result = {};
|
|
142
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
143
|
+
if (key.toLowerCase() !== "set-cookie")
|
|
144
|
+
result[key.toLowerCase()] = value;
|
|
145
|
+
}
|
|
146
|
+
return result;
|
|
147
|
+
}
|
|
148
|
+
/** Shapes the final hop, retaining both upstream and local truncation evidence. */
|
|
149
|
+
function livePageResult({ response, headers, options, url, origin, redirects }, _options = {}) {
|
|
150
|
+
const cookies = new Headers();
|
|
151
|
+
for (const cookie of response.setCookies ?? [])
|
|
152
|
+
cookies.append("set-cookie", cookie);
|
|
153
|
+
const raw = Buffer.from(response.bodyText).subarray(0, MAX_MAX_BODY_BYTES).toString("utf8");
|
|
154
|
+
const shaped = shapePageBody({ body: raw }, options);
|
|
155
|
+
const location = headers.location;
|
|
156
|
+
return { path: new URL(url).pathname + new URL(url).search, status: response.status, ok: response.status >= 200 && response.status < 300, headers, cookies: toCookieShapes({ headers: cookies }), ...shaped, truncated: shaped.truncated || response.bodyTruncated === true || Buffer.byteLength(response.bodyText) > MAX_MAX_BODY_BYTES, url, origin, redirects, untrusted: true, ...(REDIRECTS.has(response.status) && location ? { location } : {}) };
|
|
157
|
+
}
|
|
158
|
+
/** Caller-safe egress refusals, following media-import's policy-error projection without leaking IPs. */
|
|
159
|
+
async function sendPage({ deps, url, signal, timeoutMs, maxResponseBytes }, _optional = {}) {
|
|
160
|
+
const started = Date.now();
|
|
161
|
+
try {
|
|
162
|
+
const response = await deps.httpClient.send({ method: "GET", url, headers: {}, timeoutMs, signal, maxResponseBytes });
|
|
163
|
+
deps.observeFetch?.({ origin: new URL(url).origin, status: response.status, durationMs: Date.now() - started, outcome: "response" });
|
|
164
|
+
return response;
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
deps.observeFetch?.({ origin: new URL(url).origin, durationMs: Date.now() - started, outcome: deps.isEgressRefusal(error) ? "refused" : "failed" });
|
|
168
|
+
if (deps.isEgressRefusal(error))
|
|
169
|
+
throw new ToolInputError({ message: `fetch_live_url: ${error.callerSafeMessage}` });
|
|
170
|
+
if (signal.aborted)
|
|
171
|
+
throw new ToolInputError({ message: DEADLINE_MESSAGE });
|
|
172
|
+
throw error;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
/** Bounds the whole operation while releasing its listener on either completion path. */
|
|
176
|
+
async function awaitWithDeadline({ work, signal }, _optional = {}) {
|
|
177
|
+
let abort;
|
|
178
|
+
try {
|
|
179
|
+
return await Promise.race([work, new Promise((_resolve, reject) => {
|
|
180
|
+
abort = () => reject(new ToolInputError({ message: DEADLINE_MESSAGE }));
|
|
181
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
182
|
+
if (signal.aborted)
|
|
183
|
+
abort();
|
|
184
|
+
})]);
|
|
185
|
+
}
|
|
186
|
+
finally {
|
|
187
|
+
if (abort)
|
|
188
|
+
signal.removeEventListener("abort", abort);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
//# sourceMappingURL=live-url.js.map
|
|
@@ -7,26 +7,31 @@
|
|
|
7
7
|
*/
|
|
8
8
|
export async function collectPagePerformance(_required, _options = {}) {
|
|
9
9
|
// Helpers stay nested: only this function's source is serialized into the page.
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
}
|
|
22
|
-
function countNode(node) {
|
|
23
|
-
if (node.nodeType === Node.ELEMENT_NODE) {
|
|
24
|
-
countElement(node);
|
|
25
|
-
return;
|
|
10
|
+
function sampleDom() {
|
|
11
|
+
const counts = { mountedHiddenPanels: 0, hiddenPreElements: 0, hiddenPreTextChars: 0, iframes: 0 };
|
|
12
|
+
function countElement(element) {
|
|
13
|
+
const hidden = element.getClientRects().length === 0;
|
|
14
|
+
if (element.tagName === 'IFRAME')
|
|
15
|
+
counts.iframes++;
|
|
16
|
+
if (element.matches('details:not([open]),[hidden],[aria-hidden="true"]') ||
|
|
17
|
+
(element.getAttribute('role') === 'tabpanel' && hidden))
|
|
18
|
+
counts.mountedHiddenPanels++;
|
|
19
|
+
if (element.tagName === 'PRE' && hidden)
|
|
20
|
+
counts.hiddenPreElements++;
|
|
26
21
|
}
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
counts.hiddenPreTextChars += node.textContent?.length ?? 0;
|
|
22
|
+
// Count text once, without copying hidden output into model context.
|
|
23
|
+
const countText = (node) => { if (node.parentElement?.closest('pre')?.getClientRects().length === 0)
|
|
24
|
+
counts.hiddenPreTextChars += node.textContent?.length ?? 0; };
|
|
25
|
+
const walker = document.createTreeWalker(document, NodeFilter.SHOW_ALL);
|
|
26
|
+
let domNodes = 0;
|
|
27
|
+
for (let node = walker.nextNode();; node = walker.nextNode()) {
|
|
28
|
+
if (!node || domNodes >= 100_000)
|
|
29
|
+
return { domNodes, domTruncated: node !== null, ...counts };
|
|
30
|
+
domNodes++;
|
|
31
|
+
if (node.nodeType === Node.ELEMENT_NODE)
|
|
32
|
+
countElement(node);
|
|
33
|
+
else if (node.nodeType === Node.TEXT_NODE)
|
|
34
|
+
countText(node);
|
|
30
35
|
}
|
|
31
36
|
}
|
|
32
37
|
async function sampleLongTasks() {
|
|
@@ -35,7 +40,7 @@ export async function collectPagePerformance(_required, _options = {}) {
|
|
|
35
40
|
return longTasks;
|
|
36
41
|
const observer = new PerformanceObserver(list => {
|
|
37
42
|
for (const entry of list.getEntries()) {
|
|
38
|
-
if (longTasks.count >=
|
|
43
|
+
if (longTasks.count >= 200) {
|
|
39
44
|
longTasks.truncated = true;
|
|
40
45
|
break;
|
|
41
46
|
}
|
|
@@ -54,24 +59,17 @@ export async function collectPagePerformance(_required, _options = {}) {
|
|
|
54
59
|
}
|
|
55
60
|
return longTasks;
|
|
56
61
|
}
|
|
57
|
-
const
|
|
58
|
-
let node = walker.nextNode();
|
|
59
|
-
while (node && counts.domNodes < maxNodes) {
|
|
60
|
-
counts.domNodes++;
|
|
61
|
-
countNode(node);
|
|
62
|
-
node = walker.nextNode();
|
|
63
|
-
}
|
|
62
|
+
const dom = sampleDom();
|
|
64
63
|
const memory = performance.memory;
|
|
65
64
|
const heap = memory ? { usedBytes: memory.usedJSHeapSize, allocatedBytes: memory.totalJSHeapSize, limitBytes: memory.jsHeapSizeLimit } : null;
|
|
66
65
|
const longTasks = await sampleLongTasks();
|
|
67
|
-
const { domNodes, mountedHiddenPanels, hiddenPreElements, hiddenPreTextChars, iframes } = counts;
|
|
68
66
|
const suspects = [
|
|
69
|
-
hiddenPreElements ? `${hiddenPreElements} hidden pre elements remain mounted with ${hiddenPreTextChars} text characters.` : '',
|
|
70
|
-
mountedHiddenPanels ? `${mountedHiddenPanels} hidden or collapsed panels remain mounted.` : '',
|
|
71
|
-
iframes ? `${iframes} iframes have separate documents; their DOM and heaps are outside this sample.` : '',
|
|
67
|
+
dom.hiddenPreElements ? `${dom.hiddenPreElements} hidden pre elements remain mounted with ${dom.hiddenPreTextChars} text characters.` : '',
|
|
68
|
+
dom.mountedHiddenPanels ? `${dom.mountedHiddenPanels} hidden or collapsed panels remain mounted.` : '',
|
|
69
|
+
dom.iframes ? `${dom.iframes} iframes have separate documents; their DOM and heaps are outside this sample.` : '',
|
|
72
70
|
longTasks.count ? `${longTasks.count} long tasks were observed; the longest took ${Math.round(longTasks.maxMs)} ms.` : '',
|
|
73
71
|
].filter(Boolean);
|
|
74
|
-
return { context: 'fresh-isolated-page', heap,
|
|
72
|
+
return { context: 'fresh-isolated-page', heap, ...dom, longTasks, suspects };
|
|
75
73
|
}
|
|
76
74
|
/** Use the same local name shim as the existing DOM evidence script so keepNames bundlers work.
|
|
77
75
|
* @complexity O(script length) for serialization; evaluation is performed only on explicit request.
|
|
@@ -4,6 +4,8 @@ export { openPlaywrightRenderBrowser, PUBLIC_RENDER_LAUNCH_OPTIONS } from "./pla
|
|
|
4
4
|
export type { PlaywrightLike, PlaywrightAdapterOptions } from "./playwright-runtime.js";
|
|
5
5
|
export * from "./render-page.js";
|
|
6
6
|
export { PageWorkTimeout } from "./page-work-budget.js";
|
|
7
|
+
/** Deprecated re-export: import these from `@jini-ai/core/contracts/site/web-evidence-playwright`; removed at the next major. */
|
|
8
|
+
export type { AbortReason, RequestDecision, RequestRouterReport, RoutedRequest } from "@jini-ai/core/contracts/site/web-evidence-playwright";
|
|
7
9
|
export * from "./request-guard.js";
|
|
8
10
|
export * from "./lazy-browser.js";
|
|
9
11
|
/** Evidence facade over the same browser opener and render lifecycle used for public reading. */
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import type { HttpRequest, HttpResponse } from "@jini-ai/core/primitives";
|
|
2
|
+
import type { PageCaptureFailureFields, PageCapturePort } from "@jini-ai/core/contracts/site/web-screenshot";
|
|
3
|
+
import { type CaptureBudgetLimits } from "./capture-budget.js";
|
|
4
|
+
import { type CaptureClock } from "./capture-clock.js";
|
|
5
|
+
import { type RenderBrowserPool } from "./playwright-browser.js";
|
|
6
|
+
import { type OwnSiteFetch, type RequestRouterOptions, type RouteLike } from "./playwright-browser.js";
|
|
7
|
+
/**
|
|
8
|
+
* @file `web_screenshot_page`'s {@link PageCapturePort}: headless Chromium through Playwright, on the
|
|
9
|
+
* shared lazy-browser core (`createLazyBrowser`, `@jini-ai/diagnostics/web-evidence/playwright`) the Sites card previews use.
|
|
10
|
+
*
|
|
11
|
+
* Isolation, per capture: a FRESH browser context (no cookies, storage or cache from any other
|
|
12
|
+
* call), service workers blocked (so every request reaches the router), downloads refused,
|
|
13
|
+
* WebSockets closed before they connect, and every HTTP request routed through Jini's `request-guard.ts`,
|
|
14
|
+
* which fetches it itself through the egress guard. As defence in depth, Chromium is launched with
|
|
15
|
+
* a dead proxy and no loopback bypass, so any request that somehow escaped routing would fail
|
|
16
|
+
* rather than reach a network, and WebRTC is limited to proxied UDP (none). That proxy is not
|
|
17
|
+
* hypothetical: Playwright does not route the next hop of a fulfilled 3xx, which is why the router
|
|
18
|
+
* never fulfills one and the page's own redirects are followed by {@link renderPage} instead.
|
|
19
|
+
*
|
|
20
|
+
* Unlike the preview capture, Chromium's own sandbox stays ON (`chromiumSandbox: true`): this
|
|
21
|
+
* browser renders arbitrary, untrusted pages. A host that cannot run the sandbox (some containers)
|
|
22
|
+
* gets `unavailable` unless its composition explicitly passes `allowUnsandboxed`.
|
|
23
|
+
*
|
|
24
|
+
* The browser launches on first use and closes after {@link IDLE_CLOSE_MS} without a capture.
|
|
25
|
+
*/
|
|
26
|
+
/** The slice of Playwright this adapter drives — structural, so tests pass a fake without mocking modules. */
|
|
27
|
+
export interface CapturePage {
|
|
28
|
+
goto(url: string, options: {
|
|
29
|
+
waitUntil: "domcontentloaded";
|
|
30
|
+
timeout: number;
|
|
31
|
+
}): Promise<{
|
|
32
|
+
status(): number;
|
|
33
|
+
} | null>;
|
|
34
|
+
waitForTimeout(ms: number): Promise<void>;
|
|
35
|
+
waitForLoadState?(state: "load", options: {
|
|
36
|
+
timeout: number;
|
|
37
|
+
}): Promise<void>;
|
|
38
|
+
/** Called with a string expression only, so no page-side function crosses the boundary. */
|
|
39
|
+
evaluate(expression: string): Promise<unknown>;
|
|
40
|
+
title(): Promise<string>;
|
|
41
|
+
url(): string;
|
|
42
|
+
screenshot(options: {
|
|
43
|
+
type: "png";
|
|
44
|
+
fullPage: boolean;
|
|
45
|
+
clip?: {
|
|
46
|
+
x: number;
|
|
47
|
+
y: number;
|
|
48
|
+
width: number;
|
|
49
|
+
height: number;
|
|
50
|
+
};
|
|
51
|
+
timeout: number;
|
|
52
|
+
animations: "disabled";
|
|
53
|
+
}): Promise<Buffer>;
|
|
54
|
+
}
|
|
55
|
+
export interface CaptureContext {
|
|
56
|
+
route(pattern: string, handler: (route: RouteLike) => Promise<void>): Promise<unknown>;
|
|
57
|
+
routeWebSocket(pattern: RegExp, handler: (socket: {
|
|
58
|
+
close(): Promise<void>;
|
|
59
|
+
}) => unknown): Promise<unknown>;
|
|
60
|
+
newPage(): Promise<CapturePage>;
|
|
61
|
+
close(): Promise<void>;
|
|
62
|
+
}
|
|
63
|
+
export interface CaptureContextOptions {
|
|
64
|
+
viewport: {
|
|
65
|
+
width: number;
|
|
66
|
+
height: number;
|
|
67
|
+
};
|
|
68
|
+
deviceScaleFactor: number;
|
|
69
|
+
isMobile: boolean;
|
|
70
|
+
hasTouch: boolean;
|
|
71
|
+
serviceWorkers: "block";
|
|
72
|
+
acceptDownloads: false;
|
|
73
|
+
ignoreHTTPSErrors: false;
|
|
74
|
+
javaScriptEnabled: true;
|
|
75
|
+
}
|
|
76
|
+
export interface CaptureBrowser {
|
|
77
|
+
newContext(options: CaptureContextOptions): Promise<CaptureContext>;
|
|
78
|
+
close(): Promise<void>;
|
|
79
|
+
}
|
|
80
|
+
export interface CaptureLaunchOptions {
|
|
81
|
+
headless: true;
|
|
82
|
+
chromiumSandbox: boolean;
|
|
83
|
+
args: string[];
|
|
84
|
+
}
|
|
85
|
+
export interface CaptureBrowserLauncher {
|
|
86
|
+
launch(options: CaptureLaunchOptions): Promise<CaptureBrowser>;
|
|
87
|
+
}
|
|
88
|
+
export declare const IDLE_CLOSE_MS = 60000;
|
|
89
|
+
/** The slice of the host's guarded HTTP client the router's hops go through (`send(HttpRequest)`). */
|
|
90
|
+
export interface CaptureHttpClient {
|
|
91
|
+
send(request: HttpRequest): Promise<HttpResponse>;
|
|
92
|
+
}
|
|
93
|
+
/** The slice of Playwright's `chromium` the default launcher drives. */
|
|
94
|
+
export interface CaptureChromium {
|
|
95
|
+
launch(options: Record<string, unknown>): Promise<unknown>;
|
|
96
|
+
}
|
|
97
|
+
/** What the host injects: its guarded client, its capture limits, its caller-safe error and its Playwright loader. */
|
|
98
|
+
export interface PlaywrightPageCaptureDeps {
|
|
99
|
+
/** Guarded client built from the host's web-screenshot egress policy; never a raw transport. */
|
|
100
|
+
httpClient: CaptureHttpClient;
|
|
101
|
+
/** The host's capture limits; each request's own total and work deadline are computed from them. */
|
|
102
|
+
limits: CaptureBudgetLimits;
|
|
103
|
+
/** Builds the screenshot service's caller-safe capture failure (the one error its {@link PageCapturePort} throws). */
|
|
104
|
+
createCaptureError: (required: PageCaptureFailureFields, optional?: {}) => Error;
|
|
105
|
+
/** Whether `error` is a capture failure of kind `timeout` built by `createCaptureError`. */
|
|
106
|
+
isCaptureTimeout: (required: {
|
|
107
|
+
error: unknown;
|
|
108
|
+
}, optional?: {}) => boolean;
|
|
109
|
+
/** The host's lazy Playwright `chromium` loader; used only when neither `browserPool` nor `loadLauncher` is given. */
|
|
110
|
+
importPlaywrightChromium: () => Promise<CaptureChromium>;
|
|
111
|
+
}
|
|
112
|
+
export interface PlaywrightPageCaptureOptions {
|
|
113
|
+
loadLauncher?: () => Promise<CaptureBrowserLauncher>;
|
|
114
|
+
/** Host shares this pool with public reading; its composition owns sandbox/loader choices. */
|
|
115
|
+
browserPool?: RenderBrowserPool;
|
|
116
|
+
ownSiteFetch?: OwnSiteFetch;
|
|
117
|
+
routerOptions?: RequestRouterOptions;
|
|
118
|
+
/** Only for hosts that cannot run Chromium's sandbox; never set from env. */
|
|
119
|
+
allowUnsandboxed?: boolean;
|
|
120
|
+
/** One time source for the render's budget, its hard stop and this adapter's outer race; tests pass a fake of it. */
|
|
121
|
+
clock?: CaptureClock;
|
|
122
|
+
idleCloseMs?: number;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* @param required.httpClient - Guarded client built from `WEB_SCREENSHOT_EGRESS_POLICY`.
|
|
126
|
+
* @complexity O(1) per capture beyond the page load and screenshot; at most one browser per adapter.
|
|
127
|
+
*/
|
|
128
|
+
export declare function createPlaywrightPageCapture({ httpClient, limits, createCaptureError, isCaptureTimeout, importPlaywrightChromium }: PlaywrightPageCaptureDeps, { loadLauncher, ownSiteFetch, routerOptions, allowUnsandboxed, clock, idleCloseMs, browserPool }?: PlaywrightPageCaptureOptions): PageCapturePort;
|
|
129
|
+
//# sourceMappingURL=playwright-page-capture.d.ts.map
|