@libo11y/webext 0.0.0-bootstrap.0 → 0.2.1
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 +202 -0
- package/README.md +226 -0
- package/dist/chrome.d.ts +57 -0
- package/dist/chrome.js +16 -0
- package/dist/consent-sync.d.ts +37 -0
- package/dist/consent-sync.js +97 -0
- package/dist/content.d.ts +55 -0
- package/dist/content.js +170 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +11 -0
- package/dist/messaging-transport.d.ts +13 -0
- package/dist/messaging-transport.js +47 -0
- package/dist/messaging.d.ts +20 -0
- package/dist/messaging.js +91 -0
- package/dist/options.d.ts +66 -0
- package/dist/options.js +1 -0
- package/dist/protocol.d.ts +54 -0
- package/dist/protocol.js +44 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +2 -0
- package/dist/worker.d.ts +62 -0
- package/dist/worker.js +353 -0
- package/package.json +41 -1
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WP5 (webext). setupContentScript for content scripts and extension pages.
|
|
3
|
+
*/
|
|
4
|
+
import { type Platform } from "@libo11y/core";
|
|
5
|
+
import { type DocumentLoadOptions, type HttpInstrumentationOptions } from "@libo11y/web";
|
|
6
|
+
import { type ConsentController, type ConsentControllerOptions, type Delivery, type DeliveryOptions, type PersistentQueue, type QueueOptions, type VisibilitySource, type WebPlatformOptions } from "@libo11y/web/internal";
|
|
7
|
+
import { type ChromeLike } from "./chrome.ts";
|
|
8
|
+
import type { ContentScriptSetupOptions, ContentScriptTelemetry } from "./options.ts";
|
|
9
|
+
/**
|
|
10
|
+
* The endpoint every signal of a content script or extension page reports: a marker, not a URL,
|
|
11
|
+
* because the batches leave through the worker.
|
|
12
|
+
*/
|
|
13
|
+
export declare const WORKER_ENDPOINT = "libo11y-webext:worker";
|
|
14
|
+
/**
|
|
15
|
+
* What setupContentScriptWith builds on. Internal: the default is the real modules and this
|
|
16
|
+
* context's document, window and location; tests replace any of them.
|
|
17
|
+
*/
|
|
18
|
+
export interface ContentDeps {
|
|
19
|
+
readonly chrome: ChromeLike | undefined;
|
|
20
|
+
readonly createConsentController: (opts: ConsentControllerOptions) => ConsentController;
|
|
21
|
+
readonly createMemoryQueue: (opts: QueueOptions) => PersistentQueue;
|
|
22
|
+
readonly createDelivery: (opts: DeliveryOptions) => Delivery;
|
|
23
|
+
readonly webPlatform: (opts: WebPlatformOptions) => Platform;
|
|
24
|
+
readonly installFetchInstrumentation: (opts: HttpInstrumentationOptions) => () => void;
|
|
25
|
+
readonly installXhrInstrumentation: (opts: HttpInstrumentationOptions) => () => void;
|
|
26
|
+
readonly recordDocumentLoad: (opts: DocumentLoadOptions) => Promise<void>;
|
|
27
|
+
readonly installFlushOnHide: (target: VisibilitySource, win: EventTarget | undefined, flush: () => Promise<unknown>) => () => void;
|
|
28
|
+
/** Whose hide flushes. Undefined outside a document. */
|
|
29
|
+
readonly document: VisibilitySource | undefined;
|
|
30
|
+
/** Where pagehide fires. */
|
|
31
|
+
readonly window: EventTarget | undefined;
|
|
32
|
+
/** Tells an extension page (chrome-extension:) from a content script. */
|
|
33
|
+
readonly location: {
|
|
34
|
+
readonly protocol: string;
|
|
35
|
+
} | undefined;
|
|
36
|
+
}
|
|
37
|
+
/** The real dependencies, reading document, window and location now. */
|
|
38
|
+
export declare function defaultContentDeps(): ContentDeps;
|
|
39
|
+
/**
|
|
40
|
+
* Builds and installs telemetry whose exporters forward to the worker. In order: the consent
|
|
41
|
+
* controller from readStoredConsent (default "pending") and syncConsent; a memory queue; the
|
|
42
|
+
* messaging transport; a delivery (mode "normal", always online, because messaging the worker
|
|
43
|
+
* needs no network and the worker handles being offline); webPlatform with name "webext" and endpoints
|
|
44
|
+
* set for all three signals to the marker "libo11y-webext:worker" (the batches never leave by
|
|
45
|
+
* HTTP from here); setupWith with console defaulting to false; the instrumentations; flush on hide
|
|
46
|
+
* when there is a document. Records cross to the worker as ExportMessages, and the application's
|
|
47
|
+
* own messages carry context through the handle's sendMessage and onMessage.
|
|
48
|
+
*
|
|
49
|
+
* This context reads no privacy signals; the worker's consent options decide them for the whole
|
|
50
|
+
* extension. A grant here that the worker's respected DNT or GPC signal refuses is undone: the
|
|
51
|
+
* worker stores "denied", and this context revokes, clearing its buffers.
|
|
52
|
+
*/
|
|
53
|
+
export declare function setupContentScript(options?: ContentScriptSetupOptions): Promise<ContentScriptTelemetry>;
|
|
54
|
+
/** setupContentScript over deps. Internal: the seam the unit tests use. */
|
|
55
|
+
export declare function setupContentScriptWith(options: ContentScriptSetupOptions, deps: ContentDeps): Promise<ContentScriptTelemetry>;
|
package/dist/content.js
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WP5 (webext). setupContentScript for content scripts and extension pages.
|
|
3
|
+
*/
|
|
4
|
+
import { setupWith } from "@libo11y/core";
|
|
5
|
+
import { installXhrInstrumentation, recordDocumentLoad, } from "@libo11y/web";
|
|
6
|
+
import { activeConsent, createConsentController, createDelivery, createMemoryQueue, installFetchInstrumentation, installFlushOnHide, setActiveConsent, webPlatform, } from "@libo11y/web/internal";
|
|
7
|
+
import { diag } from "@opentelemetry/api";
|
|
8
|
+
import { getChrome } from "./chrome.js";
|
|
9
|
+
import { readStoredConsent, syncConsent } from "./consent-sync.js";
|
|
10
|
+
import { createTracedMessaging } from "./messaging.js";
|
|
11
|
+
import { createMessagingTransport } from "./messaging-transport.js";
|
|
12
|
+
/**
|
|
13
|
+
* The endpoint every signal of a content script or extension page reports: a marker, not a URL,
|
|
14
|
+
* because the batches leave through the worker.
|
|
15
|
+
*/
|
|
16
|
+
export const WORKER_ENDPOINT = "libo11y-webext:worker";
|
|
17
|
+
const EXTENSION_PROTOCOLS = [
|
|
18
|
+
"chrome-extension:",
|
|
19
|
+
"moz-extension:",
|
|
20
|
+
"safari-web-extension:",
|
|
21
|
+
];
|
|
22
|
+
/** The real dependencies, reading document, window and location now. */
|
|
23
|
+
export function defaultContentDeps() {
|
|
24
|
+
const g = globalThis;
|
|
25
|
+
const doc = g.document;
|
|
26
|
+
return {
|
|
27
|
+
chrome: getChrome(),
|
|
28
|
+
createConsentController,
|
|
29
|
+
createMemoryQueue,
|
|
30
|
+
createDelivery,
|
|
31
|
+
webPlatform,
|
|
32
|
+
installFetchInstrumentation,
|
|
33
|
+
installXhrInstrumentation,
|
|
34
|
+
recordDocumentLoad,
|
|
35
|
+
installFlushOnHide,
|
|
36
|
+
document: doc,
|
|
37
|
+
window: doc !== undefined && typeof g.addEventListener === "function" ? globalThis : undefined,
|
|
38
|
+
location: g.location,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Builds and installs telemetry whose exporters forward to the worker. In order: the consent
|
|
43
|
+
* controller from readStoredConsent (default "pending") and syncConsent; a memory queue; the
|
|
44
|
+
* messaging transport; a delivery (mode "normal", always online, because messaging the worker
|
|
45
|
+
* needs no network and the worker handles being offline); webPlatform with name "webext" and endpoints
|
|
46
|
+
* set for all three signals to the marker "libo11y-webext:worker" (the batches never leave by
|
|
47
|
+
* HTTP from here); setupWith with console defaulting to false; the instrumentations; flush on hide
|
|
48
|
+
* when there is a document. Records cross to the worker as ExportMessages, and the application's
|
|
49
|
+
* own messages carry context through the handle's sendMessage and onMessage.
|
|
50
|
+
*
|
|
51
|
+
* This context reads no privacy signals; the worker's consent options decide them for the whole
|
|
52
|
+
* extension. A grant here that the worker's respected DNT or GPC signal refuses is undone: the
|
|
53
|
+
* worker stores "denied", and this context revokes, clearing its buffers.
|
|
54
|
+
*/
|
|
55
|
+
export function setupContentScript(options = {}) {
|
|
56
|
+
return setupContentScriptWith(options, defaultContentDeps());
|
|
57
|
+
}
|
|
58
|
+
async function cleanup(steps) {
|
|
59
|
+
for (const step of steps) {
|
|
60
|
+
try {
|
|
61
|
+
await step();
|
|
62
|
+
}
|
|
63
|
+
catch (err) {
|
|
64
|
+
diag.warn("o11y: webext content script shutdown step failed", err);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** setupContentScript over deps. Internal: the seam the unit tests use. */
|
|
69
|
+
export async function setupContentScriptWith(options, deps) {
|
|
70
|
+
const chrome = deps.chrome;
|
|
71
|
+
if (chrome === undefined) {
|
|
72
|
+
throw new Error("o11y: setupContentScript needs the extension API (chrome.runtime)");
|
|
73
|
+
}
|
|
74
|
+
const stored = await readStoredConsent(chrome);
|
|
75
|
+
const controller = deps.createConsentController(stored === undefined ? {} : { initial: stored });
|
|
76
|
+
const steps = [syncConsent(controller, chrome).stop];
|
|
77
|
+
const queue = deps.createMemoryQueue({});
|
|
78
|
+
steps.push(() => queue.close());
|
|
79
|
+
const delivery = deps.createDelivery({
|
|
80
|
+
transport: createMessagingTransport(chrome),
|
|
81
|
+
queue,
|
|
82
|
+
gate: controller,
|
|
83
|
+
mode: () => "normal",
|
|
84
|
+
// Messaging the worker needs no network; the worker queues while the browser is offline.
|
|
85
|
+
isOnline: () => true,
|
|
86
|
+
});
|
|
87
|
+
steps.unshift(() => delivery.shutdown());
|
|
88
|
+
const endpoints = {
|
|
89
|
+
traces: WORKER_ENDPOINT,
|
|
90
|
+
metrics: WORKER_ENDPOINT,
|
|
91
|
+
logs: WORKER_ENDPOINT,
|
|
92
|
+
};
|
|
93
|
+
const exportOptions = {
|
|
94
|
+
...(options.env === undefined ? {} : { env: options.env }),
|
|
95
|
+
...(options.userAgent === undefined ? {} : { userAgent: options.userAgent }),
|
|
96
|
+
};
|
|
97
|
+
let telemetry;
|
|
98
|
+
try {
|
|
99
|
+
const platform = deps.webPlatform({
|
|
100
|
+
name: "webext",
|
|
101
|
+
exportOptions,
|
|
102
|
+
endpoints,
|
|
103
|
+
delivery,
|
|
104
|
+
gate: controller,
|
|
105
|
+
mode: () => "normal",
|
|
106
|
+
...(options.contextManager === undefined ? {} : { contextManager: options.contextManager }),
|
|
107
|
+
});
|
|
108
|
+
const coreOptions = { ...options, console: options.console ?? false };
|
|
109
|
+
telemetry = await setupWith(coreOptions, platform);
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
await cleanup(steps);
|
|
113
|
+
throw err;
|
|
114
|
+
}
|
|
115
|
+
const core = telemetry;
|
|
116
|
+
const doc = deps.document;
|
|
117
|
+
if (doc !== undefined)
|
|
118
|
+
steps.unshift(deps.installFlushOnHide(doc, deps.window, () => core.forceFlush()));
|
|
119
|
+
steps.unshift(controller.onRevoke(async () => {
|
|
120
|
+
await core.forceFlush();
|
|
121
|
+
await delivery.clear();
|
|
122
|
+
}));
|
|
123
|
+
const messaging = createTracedMessaging(chrome, core.propagator);
|
|
124
|
+
const uninstalls = [];
|
|
125
|
+
// Core's handle extended in place, so identity-keyed lookups such as exemplarStoreOf still work.
|
|
126
|
+
const handle = core;
|
|
127
|
+
Object.defineProperty(handle, "consent", { value: controller.consent, enumerable: true });
|
|
128
|
+
Object.assign(handle, { onMessage: messaging.onMessage, sendMessage: messaging.sendMessage });
|
|
129
|
+
const coreShutdown = core.shutdown.bind(core);
|
|
130
|
+
let shutdownPromise;
|
|
131
|
+
handle.shutdown = (opts) => {
|
|
132
|
+
shutdownPromise ??= (async () => {
|
|
133
|
+
const report = await coreShutdown(opts);
|
|
134
|
+
await cleanup([
|
|
135
|
+
...uninstalls,
|
|
136
|
+
() => {
|
|
137
|
+
if (activeConsent() === controller.consent)
|
|
138
|
+
setActiveConsent(undefined);
|
|
139
|
+
},
|
|
140
|
+
...steps,
|
|
141
|
+
]);
|
|
142
|
+
return report;
|
|
143
|
+
})();
|
|
144
|
+
return shutdownPromise;
|
|
145
|
+
};
|
|
146
|
+
try {
|
|
147
|
+
setActiveConsent(controller.consent);
|
|
148
|
+
const instr = options.instrumentations ?? {};
|
|
149
|
+
const http = {
|
|
150
|
+
telemetry: handle,
|
|
151
|
+
propagateTo: instr.propagateTo ?? [],
|
|
152
|
+
ignoreUrls: instr.ignoreUrls ?? [],
|
|
153
|
+
};
|
|
154
|
+
if (instr.fetch !== false)
|
|
155
|
+
uninstalls.push(deps.installFetchInstrumentation(http));
|
|
156
|
+
if (instr.xhr !== false)
|
|
157
|
+
uninstalls.push(deps.installXhrInstrumentation(http));
|
|
158
|
+
const extensionPage = EXTENSION_PROTOCOLS.includes(deps.location?.protocol ?? "");
|
|
159
|
+
if (instr.documentLoad ?? extensionPage) {
|
|
160
|
+
const abort = new AbortController();
|
|
161
|
+
uninstalls.push(() => abort.abort());
|
|
162
|
+
void deps.recordDocumentLoad({ telemetry: handle, signal: abort.signal });
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
catch (err) {
|
|
166
|
+
await handle.shutdown();
|
|
167
|
+
throw err;
|
|
168
|
+
}
|
|
169
|
+
return handle;
|
|
170
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The libo11y Manifest V3 extension platform: setupWorker for the service worker, which persists
|
|
3
|
+
* every batch to IndexedDB before sending because the worker can stop at any time, and
|
|
4
|
+
* setupContentScript for content scripts and extension pages, which forward their records to the
|
|
5
|
+
* worker by runtime messaging. Trace context crosses with every traced message. No RUM features.
|
|
6
|
+
*
|
|
7
|
+
* Scaffold, frozen: the public API. Changing it needs the architect's sign-off.
|
|
8
|
+
*/
|
|
9
|
+
export type { Consent, ConsentOptions, ConsentState, WebTelemetry } from "@libo11y/web";
|
|
10
|
+
export type { ChromeLike, ExtensionEvent, MessageSenderLike, RuntimeMessageListener, StorageChangeLike, } from "./chrome.ts";
|
|
11
|
+
export { setupContentScript } from "./content.ts";
|
|
12
|
+
export type { ContentScriptSetupOptions, ContentScriptTelemetry, TracedMessageListener, TracedMessaging, WorkerSetupOptions, WorkerTelemetry, } from "./options.ts";
|
|
13
|
+
export { type ExportMessage, type ExportReply, type Libo11yMessage, PROTOCOL_VERSION, type TracedMessage, type TracedReply, } from "./protocol.ts";
|
|
14
|
+
export { setupWorker } from "./worker.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The libo11y Manifest V3 extension platform: setupWorker for the service worker, which persists
|
|
3
|
+
* every batch to IndexedDB before sending because the worker can stop at any time, and
|
|
4
|
+
* setupContentScript for content scripts and extension pages, which forward their records to the
|
|
5
|
+
* worker by runtime messaging. Trace context crosses with every traced message. No RUM features.
|
|
6
|
+
*
|
|
7
|
+
* Scaffold, frozen: the public API. Changing it needs the architect's sign-off.
|
|
8
|
+
*/
|
|
9
|
+
export { setupContentScript } from "./content.js";
|
|
10
|
+
export { PROTOCOL_VERSION, } from "./protocol.js";
|
|
11
|
+
export { setupWorker } from "./worker.js";
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WP5 (webext). The Transport a content script or extension page uses: each batch goes to the
|
|
3
|
+
* worker as an ExportMessage.
|
|
4
|
+
*/
|
|
5
|
+
import type { Transport } from "@libo11y/web/internal";
|
|
6
|
+
import type { ChromeLike } from "./chrome.ts";
|
|
7
|
+
/**
|
|
8
|
+
* A Transport over runtime.sendMessage. An ExportReply with ok true is "ok", with ok false is
|
|
9
|
+
* "fatal" with its reason; no answer, a rejected sendMessage (the worker is starting or the
|
|
10
|
+
* extension reloaded) or a timeout of timeoutMillis (default 10000) is "retry". The mode is
|
|
11
|
+
* ignored: messaging has no unload budget.
|
|
12
|
+
*/
|
|
13
|
+
export declare function createMessagingTransport(chrome: ChromeLike, timeoutMillis?: number): Transport;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { isReply, PROTOCOL_VERSION } from "./protocol.js";
|
|
2
|
+
const DEFAULT_TIMEOUT_MILLIS = 10_000;
|
|
3
|
+
const TIMEOUT = Symbol("timeout");
|
|
4
|
+
function errorText(err) {
|
|
5
|
+
return err instanceof Error ? err.message : String(err);
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* A Transport over runtime.sendMessage. An ExportReply with ok true is "ok", with ok false is
|
|
9
|
+
* "fatal" with its reason; no answer, a rejected sendMessage (the worker is starting or the
|
|
10
|
+
* extension reloaded) or a timeout of timeoutMillis (default 10000) is "retry". The mode is
|
|
11
|
+
* ignored: messaging has no unload budget.
|
|
12
|
+
*/
|
|
13
|
+
export function createMessagingTransport(chrome, timeoutMillis = DEFAULT_TIMEOUT_MILLIS) {
|
|
14
|
+
return {
|
|
15
|
+
async send(req) {
|
|
16
|
+
const message = {
|
|
17
|
+
libo11y: PROTOCOL_VERSION,
|
|
18
|
+
type: "export",
|
|
19
|
+
signal: req.signal,
|
|
20
|
+
body: req.body,
|
|
21
|
+
};
|
|
22
|
+
let timer;
|
|
23
|
+
const expired = new Promise((resolve) => {
|
|
24
|
+
timer = setTimeout(() => resolve(TIMEOUT), timeoutMillis);
|
|
25
|
+
});
|
|
26
|
+
let reply;
|
|
27
|
+
try {
|
|
28
|
+
reply = await Promise.race([chrome.runtime.sendMessage(message), expired]);
|
|
29
|
+
}
|
|
30
|
+
catch (err) {
|
|
31
|
+
return { kind: "retry", reason: `o11y: messaging the worker: ${errorText(err)}` };
|
|
32
|
+
}
|
|
33
|
+
finally {
|
|
34
|
+
clearTimeout(timer);
|
|
35
|
+
}
|
|
36
|
+
if (reply === TIMEOUT) {
|
|
37
|
+
return { kind: "retry", reason: `o11y: messaging the worker: timeout after ${timeoutMillis} ms` };
|
|
38
|
+
}
|
|
39
|
+
if (!isReply(reply) || reply.type !== "export-reply") {
|
|
40
|
+
return { kind: "retry", reason: "o11y: messaging the worker: no export reply" };
|
|
41
|
+
}
|
|
42
|
+
if (reply.ok)
|
|
43
|
+
return { kind: "ok" };
|
|
44
|
+
return { kind: "fatal", reason: `o11y: the worker refused the batch: ${reply.reason ?? "no reason"}` };
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WP5 (webext). Trace context across runtime messages.
|
|
3
|
+
*/
|
|
4
|
+
import { type TextMapPropagator } from "@opentelemetry/api";
|
|
5
|
+
import type { ChromeLike, RuntimeMessageListener } from "./chrome.ts";
|
|
6
|
+
import type { TracedMessageListener, TracedMessaging } from "./options.ts";
|
|
7
|
+
/**
|
|
8
|
+
* The runtime.onMessage listener behind TracedMessaging.onMessage: it extracts the carrier, runs
|
|
9
|
+
* listener under context.with(extracted), answers with a TracedReply (awaiting a promise result,
|
|
10
|
+
* returning true), and ignores any message that is not a TracedMessage.
|
|
11
|
+
*/
|
|
12
|
+
export declare function tracedListener(propagator: TextMapPropagator, listener: TracedMessageListener): RuntimeMessageListener;
|
|
13
|
+
/**
|
|
14
|
+
* Traced messaging over chrome with propagator (the telemetry's, so the baggage egress filter
|
|
15
|
+
* applies). sendMessage injects the active context into a TracedMessage and unwraps the
|
|
16
|
+
* TracedReply. onMessage adds a tracedListener.
|
|
17
|
+
*/
|
|
18
|
+
export declare function createTracedMessaging(chrome: ChromeLike, propagator: TextMapPropagator): TracedMessaging;
|
|
19
|
+
/** tabs.sendMessage counterpart of TracedMessaging.sendMessage. */
|
|
20
|
+
export declare function sendTracedTabMessage<R>(chrome: ChromeLike, propagator: TextMapPropagator, tabId: number, payload: unknown): Promise<R>;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WP5 (webext). Trace context across runtime messages.
|
|
3
|
+
*/
|
|
4
|
+
import { context, defaultTextMapGetter, defaultTextMapSetter, ROOT_CONTEXT, } from "@opentelemetry/api";
|
|
5
|
+
import { isReply, isTracedMessage, PROTOCOL_VERSION, } from "./protocol.js";
|
|
6
|
+
// tracedMessage wraps payload with the active context, synchronously, so the caller's span is the
|
|
7
|
+
// one injected even when the send itself is awaited later.
|
|
8
|
+
function tracedMessage(propagator, payload) {
|
|
9
|
+
const carrier = {};
|
|
10
|
+
propagator.inject(context.active(), carrier, defaultTextMapSetter);
|
|
11
|
+
return { libo11y: PROTOCOL_VERSION, type: "traced", carrier, payload };
|
|
12
|
+
}
|
|
13
|
+
// unwrap sends and unwraps the TracedReply. It takes the send as a thunk, so an extension API that
|
|
14
|
+
// throws synchronously (an invalidated extension context, a bad tabId) still gives a rejection.
|
|
15
|
+
async function unwrap(send) {
|
|
16
|
+
const r = await send();
|
|
17
|
+
if (!isReply(r) || r.type !== "traced-reply") {
|
|
18
|
+
throw new Error("o11y: no traced reply: no traced listener answered the message");
|
|
19
|
+
}
|
|
20
|
+
if (!r.ok)
|
|
21
|
+
throw new Error(r.error ?? "o11y: the traced listener failed");
|
|
22
|
+
return r.result;
|
|
23
|
+
}
|
|
24
|
+
function errorText(err) {
|
|
25
|
+
if (err instanceof Error)
|
|
26
|
+
return err.message;
|
|
27
|
+
if (typeof err === "object" && err !== null && "message" in err)
|
|
28
|
+
return String(err.message);
|
|
29
|
+
return String(err);
|
|
30
|
+
}
|
|
31
|
+
function ok(result) {
|
|
32
|
+
return result === undefined
|
|
33
|
+
? { libo11y: PROTOCOL_VERSION, type: "traced-reply", ok: true }
|
|
34
|
+
: { libo11y: PROTOCOL_VERSION, type: "traced-reply", ok: true, result };
|
|
35
|
+
}
|
|
36
|
+
function failed(err) {
|
|
37
|
+
return { libo11y: PROTOCOL_VERSION, type: "traced-reply", ok: false, error: errorText(err) };
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The runtime.onMessage listener behind TracedMessaging.onMessage: it extracts the carrier, runs
|
|
41
|
+
* listener under context.with(extracted), answers with a TracedReply (awaiting a promise result,
|
|
42
|
+
* returning true), and ignores any message that is not a TracedMessage.
|
|
43
|
+
*/
|
|
44
|
+
export function tracedListener(propagator, listener) {
|
|
45
|
+
return (message, sender, sendResponse) => {
|
|
46
|
+
if (!isTracedMessage(message))
|
|
47
|
+
return undefined;
|
|
48
|
+
const extracted = propagator.extract(ROOT_CONTEXT, message.carrier, defaultTextMapGetter);
|
|
49
|
+
let result;
|
|
50
|
+
try {
|
|
51
|
+
result = context.with(extracted, () => listener(message.payload, sender));
|
|
52
|
+
}
|
|
53
|
+
catch (err) {
|
|
54
|
+
sendResponse(failed(err));
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
if (typeof result?.then !== "function") {
|
|
58
|
+
sendResponse(ok(result));
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
Promise.resolve(result).then((value) => sendResponse(ok(value)), (err) => sendResponse(failed(err)));
|
|
62
|
+
return true;
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Traced messaging over chrome with propagator (the telemetry's, so the baggage egress filter
|
|
67
|
+
* applies). sendMessage injects the active context into a TracedMessage and unwraps the
|
|
68
|
+
* TracedReply. onMessage adds a tracedListener.
|
|
69
|
+
*/
|
|
70
|
+
export function createTracedMessaging(chrome, propagator) {
|
|
71
|
+
return {
|
|
72
|
+
onMessage(listener) {
|
|
73
|
+
const onRuntimeMessage = tracedListener(propagator, listener);
|
|
74
|
+
chrome.runtime.onMessage.addListener(onRuntimeMessage);
|
|
75
|
+
return () => chrome.runtime.onMessage.removeListener(onRuntimeMessage);
|
|
76
|
+
},
|
|
77
|
+
sendMessage(payload) {
|
|
78
|
+
const message = tracedMessage(propagator, payload);
|
|
79
|
+
return unwrap(() => chrome.runtime.sendMessage(message));
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/** tabs.sendMessage counterpart of TracedMessaging.sendMessage. */
|
|
84
|
+
export function sendTracedTabMessage(chrome, propagator, tabId, payload) {
|
|
85
|
+
if (chrome.tabs === undefined) {
|
|
86
|
+
return Promise.reject(new Error("o11y: chrome.tabs is unavailable in this context"));
|
|
87
|
+
}
|
|
88
|
+
const message = tracedMessage(propagator, payload);
|
|
89
|
+
const tabs = chrome.tabs;
|
|
90
|
+
return unwrap(() => tabs.sendMessage(tabId, message));
|
|
91
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Contract, frozen by the L4 scaffold. The public options and handles of @libo11y/webext.
|
|
3
|
+
*/
|
|
4
|
+
import type { BrowserExportOptions, ConsentOptions, HttpInstrumentationOptions, TelemetryOptions, WebInstrumentationOptions, WebTelemetry } from "@libo11y/web";
|
|
5
|
+
import type { ContextManager } from "@opentelemetry/api";
|
|
6
|
+
import type { MessageSenderLike } from "./chrome.ts";
|
|
7
|
+
/**
|
|
8
|
+
* Handles a traced message. It runs inside the sender's trace context, so spans it starts are
|
|
9
|
+
* children of the sender's active span. The returned value (or resolved value) is the reply.
|
|
10
|
+
*/
|
|
11
|
+
export type TracedMessageListener = (payload: unknown, sender: MessageSenderLike) => unknown;
|
|
12
|
+
/** Traced runtime messaging, on both sides. */
|
|
13
|
+
export interface TracedMessaging {
|
|
14
|
+
/**
|
|
15
|
+
* Adds a runtime.onMessage listener for traced messages; other messages are left to other
|
|
16
|
+
* listeners. Returns a function that removes it.
|
|
17
|
+
*/
|
|
18
|
+
onMessage(listener: TracedMessageListener): () => void;
|
|
19
|
+
/**
|
|
20
|
+
* runtime.sendMessage(payload) wrapped in a TracedMessage with the active context. Resolves with
|
|
21
|
+
* the listener's result; rejects with its error, or when no listener answered.
|
|
22
|
+
*/
|
|
23
|
+
sendMessage<R = unknown>(payload: unknown): Promise<R>;
|
|
24
|
+
}
|
|
25
|
+
/** Options for setupWorker. */
|
|
26
|
+
export interface WorkerSetupOptions extends TelemetryOptions, BrowserExportOptions {
|
|
27
|
+
/**
|
|
28
|
+
* The consent gate's initial state and privacy signals. The state is persisted in
|
|
29
|
+
* chrome.storage.local under "libo11y.consent", and a stored state beats initial, because the
|
|
30
|
+
* worker restarts at any time.
|
|
31
|
+
*/
|
|
32
|
+
readonly consent?: ConsentOptions;
|
|
33
|
+
/** Default createContextManager() from `@libo11y/web`. */
|
|
34
|
+
readonly contextManager?: () => ContextManager;
|
|
35
|
+
/** Client spans for the worker's own fetch calls. Default true. */
|
|
36
|
+
readonly fetch?: boolean | Pick<HttpInstrumentationOptions, "propagateTo" | "ignoreUrls">;
|
|
37
|
+
/** Accept export batches from content scripts and extension pages. Default true. */
|
|
38
|
+
readonly acceptForwarded?: boolean;
|
|
39
|
+
}
|
|
40
|
+
/** The service worker's telemetry. */
|
|
41
|
+
export interface WorkerTelemetry extends WebTelemetry, TracedMessaging {
|
|
42
|
+
/** tabs.sendMessage(tabId, payload) as a TracedMessage. Rejects where tabs is unavailable. */
|
|
43
|
+
sendTabMessage<R = unknown>(tabId: number, payload: unknown): Promise<R>;
|
|
44
|
+
}
|
|
45
|
+
/** Options for setupContentScript. */
|
|
46
|
+
export interface ContentScriptSetupOptions extends TelemetryOptions {
|
|
47
|
+
/** OTEL_* variables, as BrowserExportOptions.env. */
|
|
48
|
+
readonly env?: Readonly<Record<string, string>>;
|
|
49
|
+
/** Default createContextManager() from `@libo11y/web`. */
|
|
50
|
+
readonly contextManager?: () => ContextManager;
|
|
51
|
+
/**
|
|
52
|
+
* What to instrument in this context. fetch and xhr default true and see only the content
|
|
53
|
+
* script's own requests (content scripts run in an isolated world). documentLoad defaults to
|
|
54
|
+
* false in a content script, whose document is the page's, and true in an extension page.
|
|
55
|
+
*/
|
|
56
|
+
readonly instrumentations?: WebInstrumentationOptions;
|
|
57
|
+
/** As BrowserExportOptions.userAgent. */
|
|
58
|
+
readonly userAgent?: boolean;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* A content script's or extension page's telemetry. Its records go to the worker by runtime
|
|
62
|
+
* messaging. Its consent mirrors the worker's through chrome.storage.local; grant and revoke here
|
|
63
|
+
* change it for the whole extension.
|
|
64
|
+
*/
|
|
65
|
+
export interface ContentScriptTelemetry extends WebTelemetry, TracedMessaging {
|
|
66
|
+
}
|
package/dist/options.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WP5 (webext). The runtime messaging protocol between content scripts or extension pages and the
|
|
3
|
+
* service worker. The types are a contract frozen by the L4 scaffold; the guards are WP5's.
|
|
4
|
+
*
|
|
5
|
+
* Every libo11y message is a plain JSON object with `libo11y: 1`, so it survives Chrome's JSON
|
|
6
|
+
* serialization of runtime messages and other listeners can tell it apart.
|
|
7
|
+
*/
|
|
8
|
+
import { type OtlpSignal } from "@libo11y/web/internal";
|
|
9
|
+
/** The protocol version every message carries. A listener ignores any other value. */
|
|
10
|
+
export declare const PROTOCOL_VERSION = 1;
|
|
11
|
+
/** A content script's or page's export batch, for the worker to persist and deliver. */
|
|
12
|
+
export interface ExportMessage {
|
|
13
|
+
readonly libo11y: typeof PROTOCOL_VERSION;
|
|
14
|
+
readonly type: "export";
|
|
15
|
+
readonly signal: OtlpSignal;
|
|
16
|
+
/** The OTLP/HTTP JSON request body, exactly as the worker will post it. */
|
|
17
|
+
readonly body: string;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The worker's answer to an ExportMessage, sent once the batch is in the worker's IndexedDB queue
|
|
21
|
+
* (ok true), or refused: consent closed, malformed, or the queue refused it (ok false, with reason).
|
|
22
|
+
* A refused batch is not retried by the sender.
|
|
23
|
+
*/
|
|
24
|
+
export interface ExportReply {
|
|
25
|
+
readonly libo11y: typeof PROTOCOL_VERSION;
|
|
26
|
+
readonly type: "export-reply";
|
|
27
|
+
readonly ok: boolean;
|
|
28
|
+
readonly reason?: string;
|
|
29
|
+
}
|
|
30
|
+
/** An application message carrying the sender's active trace context. */
|
|
31
|
+
export interface TracedMessage {
|
|
32
|
+
readonly libo11y: typeof PROTOCOL_VERSION;
|
|
33
|
+
readonly type: "traced";
|
|
34
|
+
/** What the propagator injected: traceparent, and tracestate and baggage when present. */
|
|
35
|
+
readonly carrier: Readonly<Record<string, string>>;
|
|
36
|
+
/** The application's message. */
|
|
37
|
+
readonly payload: unknown;
|
|
38
|
+
}
|
|
39
|
+
/** The answer to a TracedMessage: the listener's result, or its error message. */
|
|
40
|
+
export interface TracedReply {
|
|
41
|
+
readonly libo11y: typeof PROTOCOL_VERSION;
|
|
42
|
+
readonly type: "traced-reply";
|
|
43
|
+
readonly ok: boolean;
|
|
44
|
+
readonly result?: unknown;
|
|
45
|
+
readonly error?: string;
|
|
46
|
+
}
|
|
47
|
+
/** Every libo11y message. */
|
|
48
|
+
export type Libo11yMessage = ExportMessage | ExportReply | TracedMessage | TracedReply;
|
|
49
|
+
/** True for a well-formed ExportMessage: libo11y 1, a known signal and a string body. */
|
|
50
|
+
export declare function isExportMessage(m: unknown): m is ExportMessage;
|
|
51
|
+
/** True for a well-formed TracedMessage: libo11y 1 and a carrier of string values. */
|
|
52
|
+
export declare function isTracedMessage(m: unknown): m is TracedMessage;
|
|
53
|
+
/** True for an ExportReply or TracedReply. */
|
|
54
|
+
export declare function isReply(m: unknown): m is ExportReply | TracedReply;
|
package/dist/protocol.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WP5 (webext). The runtime messaging protocol between content scripts or extension pages and the
|
|
3
|
+
* service worker. The types are a contract frozen by the L4 scaffold; the guards are WP5's.
|
|
4
|
+
*
|
|
5
|
+
* Every libo11y message is a plain JSON object with `libo11y: 1`, so it survives Chrome's JSON
|
|
6
|
+
* serialization of runtime messages and other listeners can tell it apart.
|
|
7
|
+
*/
|
|
8
|
+
import { OTLP_SIGNALS } from "@libo11y/web/internal";
|
|
9
|
+
/** The protocol version every message carries. A listener ignores any other value. */
|
|
10
|
+
export const PROTOCOL_VERSION = 1;
|
|
11
|
+
// libo11y reads m as a libo11y message of the given type: a non-array object with libo11y 1.
|
|
12
|
+
function framed(m, type) {
|
|
13
|
+
return (typeof m === "object" &&
|
|
14
|
+
m !== null &&
|
|
15
|
+
!Array.isArray(m) &&
|
|
16
|
+
m.libo11y === PROTOCOL_VERSION &&
|
|
17
|
+
m.type === type);
|
|
18
|
+
}
|
|
19
|
+
function isCarrier(c) {
|
|
20
|
+
return (typeof c === "object" &&
|
|
21
|
+
c !== null &&
|
|
22
|
+
!Array.isArray(c) &&
|
|
23
|
+
Object.values(c).every((v) => typeof v === "string"));
|
|
24
|
+
}
|
|
25
|
+
/** True for a well-formed ExportMessage: libo11y 1, a known signal and a string body. */
|
|
26
|
+
export function isExportMessage(m) {
|
|
27
|
+
return (framed(m, "export") &&
|
|
28
|
+
OTLP_SIGNALS.includes(m.signal) &&
|
|
29
|
+
typeof m.body === "string");
|
|
30
|
+
}
|
|
31
|
+
/** True for a well-formed TracedMessage: libo11y 1 and a carrier of string values. */
|
|
32
|
+
export function isTracedMessage(m) {
|
|
33
|
+
return framed(m, "traced") && isCarrier(m.carrier);
|
|
34
|
+
}
|
|
35
|
+
/** True for an ExportReply or TracedReply. */
|
|
36
|
+
export function isReply(m) {
|
|
37
|
+
if (framed(m, "export-reply")) {
|
|
38
|
+
return typeof m.ok === "boolean" && (m.reason === undefined || typeof m.reason === "string");
|
|
39
|
+
}
|
|
40
|
+
if (framed(m, "traced-reply")) {
|
|
41
|
+
return typeof m.ok === "boolean" && (m.error === undefined || typeof m.error === "string");
|
|
42
|
+
}
|
|
43
|
+
return false;
|
|
44
|
+
}
|
package/dist/version.js
ADDED