@tokamaq/sdk 0.0.0-stage → 0.1.0-dev.2
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 +21 -0
- package/README.md +1403 -2
- package/build-internals.ts +25 -0
- package/caller/agent-launch.ts +60 -0
- package/client.tsx +498 -0
- package/component-actions.ts +327 -0
- package/component-alerts.ts +136 -0
- package/component-attributes.ts +340 -0
- package/component-parts.tsx +1177 -0
- package/core-contracts/auth.ts +40 -0
- package/package.json +98 -4
- package/quit.ts +58 -0
- package/regions.tsx +94 -0
- package/screen-search.ts +211 -0
- package/send-file.ts +175 -0
- package/server-build-internals.ts +11 -0
- package/solid.ts +132 -0
- package/src/agent-command.ts +48 -0
- package/src/agent-info-cache.ts +34 -0
- package/src/agent-reports.ts +140 -0
- package/src/agent-turn.ts +289 -0
- package/src/api.ts +174 -0
- package/src/auth.ts +39 -0
- package/src/call-error.ts +37 -0
- package/src/caller-storage.ts +32 -0
- package/src/client.ts +163 -0
- package/src/database.ts +322 -0
- package/src/functions.ts +726 -0
- package/src/hooks.ts +141 -0
- package/src/host.ts +211 -0
- package/src/http-action.ts +55 -0
- package/src/index.ts +126 -0
- package/src/internal/contracts.ts +260 -0
- package/src/internal/machine-scope.ts +21 -0
- package/src/local.ts +22 -0
- package/src/plugin.ts +162 -0
- package/src/points.ts +79 -0
- package/src/protocol.ts +64 -0
- package/src/schema.ts +136 -0
- package/src/storage.ts +193 -0
- package/src/thread-context.ts +42 -0
- package/src/transport.ts +421 -0
- package/src/triggers.ts +87 -0
- package/src/unstable.ts +66 -0
- package/src/validators.ts +248 -0
- package/src/values.ts +98 -0
- package/src/visibility.ts +8 -0
- package/src/websocket-transport.ts +91 -0
- package/src/window-state-protocol.ts +7 -0
- package/src/within.ts +24 -0
- package/src/worker-limits.ts +5 -0
- package/tools/bundle.mjs +490 -0
- package/tools/client-entry.mjs +10 -0
- package/tools/contracts.mjs +254 -0
- package/tools/http-actions.mjs +42 -0
- package/tools/placement.mjs +535 -0
- package/tools/plugin-boundary.mjs +592 -0
- package/tools/plugin-compiler.mjs +125 -0
- package/tools/plugin-descriptor.ts +75 -0
- package/tools/points.mjs +340 -0
- package/tools/result-validator.mjs +83 -0
- package/tools/server-builtins.mjs +82 -0
- package/tools/server-files.mjs +34 -0
- package/tools/table-references.mjs +98 -0
- package/tools/worker.mjs +110 -0
- package/tsconfig.plugin-server.json +12 -0
- package/tsconfig.plugin-window.json +15 -0
- package/view.ts +27 -0
- package/web.d.ts +6 -0
- package/window-state-host.ts +228 -0
- package/window-state.ts +43 -0
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { contract, type Failure, type MemberHook } from "@tokamaq/sdk";
|
|
2
|
+
|
|
3
|
+
export type SignInFields = Readonly<Record<string, string>>;
|
|
4
|
+
export type SignInForm = Readonly<Record<string, "text" | "email" | "password">>;
|
|
5
|
+
export type SignInResult = { accountId: string; passwordChangeRequired?: true } | Failure<string, unknown>;
|
|
6
|
+
export type SetupOwnerResult = { accountId: string; displayName?: string } | Failure<string, unknown>;
|
|
7
|
+
|
|
8
|
+
type PasswordChangeResult = { accountId: string } | Failure<string, unknown>;
|
|
9
|
+
type NewAccount = { accountId: string; displayName: string } | Failure<string, unknown>;
|
|
10
|
+
type AccountForm = {
|
|
11
|
+
createAccountForm: SignInForm;
|
|
12
|
+
createAccount: (input: { memberId: string; fields: SignInFields }) => Promise<NewAccount>;
|
|
13
|
+
};
|
|
14
|
+
type PasswordManagement = {
|
|
15
|
+
resetPassword?: (input: { accountId: string; password: string }) => Promise<PasswordChangeResult>;
|
|
16
|
+
changePassword?: (input: {
|
|
17
|
+
accountId: string;
|
|
18
|
+
fields: SignInFields;
|
|
19
|
+
newPassword: string;
|
|
20
|
+
}) => Promise<PasswordChangeResult>;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export const method = contract<
|
|
24
|
+
{
|
|
25
|
+
id: string;
|
|
26
|
+
name: string;
|
|
27
|
+
form: SignInForm;
|
|
28
|
+
/** Which text or email field identifies the login for sign-in backoff. */
|
|
29
|
+
loginField?: string;
|
|
30
|
+
signIn: (fields: SignInFields) => Promise<SignInResult>;
|
|
31
|
+
} & (
|
|
32
|
+
| { setupOwnerForm: SignInForm; setupOwner: (fields: SignInFields) => Promise<SetupOwnerResult> }
|
|
33
|
+
| { setupOwnerForm?: never; setupOwner?: never }
|
|
34
|
+
) &
|
|
35
|
+
(AccountForm | { createAccountForm?: never; createAccount?: never }) &
|
|
36
|
+
PasswordManagement
|
|
37
|
+
>("method");
|
|
38
|
+
|
|
39
|
+
export const memberAdded = contract<MemberHook>("memberAdded");
|
|
40
|
+
export const memberRemoved = contract<MemberHook>("memberRemoved");
|
package/package.json
CHANGED
|
@@ -1,6 +1,100 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokamaq/sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0-dev.2",
|
|
4
|
+
"description": "Tokamaq server and window plugin SDK.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/pixelscortex/tokamaq.git",
|
|
9
|
+
"directory": "packages/sdk"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"build-internals.ts",
|
|
13
|
+
"caller/agent-launch.ts",
|
|
14
|
+
"client.tsx",
|
|
15
|
+
"component-actions.ts",
|
|
16
|
+
"component-alerts.ts",
|
|
17
|
+
"component-attributes.ts",
|
|
18
|
+
"component-parts.tsx",
|
|
19
|
+
"core-contracts/auth.ts",
|
|
20
|
+
"quit.ts",
|
|
21
|
+
"regions.tsx",
|
|
22
|
+
"screen-search.ts",
|
|
23
|
+
"server-build-internals.ts",
|
|
24
|
+
"send-file.ts",
|
|
25
|
+
"solid.ts",
|
|
26
|
+
"src",
|
|
27
|
+
"tools/bundle.mjs",
|
|
28
|
+
"tools/client-entry.mjs",
|
|
29
|
+
"tools/contracts.mjs",
|
|
30
|
+
"tools/http-actions.mjs",
|
|
31
|
+
"tools/placement.mjs",
|
|
32
|
+
"tools/plugin-boundary.mjs",
|
|
33
|
+
"tools/plugin-compiler.mjs",
|
|
34
|
+
"tools/plugin-descriptor.ts",
|
|
35
|
+
"tools/points.mjs",
|
|
36
|
+
"tools/result-validator.mjs",
|
|
37
|
+
"tools/server-builtins.mjs",
|
|
38
|
+
"tools/server-files.mjs",
|
|
39
|
+
"tools/table-references.mjs",
|
|
40
|
+
"tools/worker.mjs",
|
|
41
|
+
"tsconfig.plugin-server.json",
|
|
42
|
+
"tsconfig.plugin-window.json",
|
|
43
|
+
"view.ts",
|
|
44
|
+
"web.d.ts",
|
|
45
|
+
"window-state-host.ts",
|
|
46
|
+
"window-state.ts"
|
|
47
|
+
],
|
|
48
|
+
"type": "module",
|
|
49
|
+
"exports": {
|
|
50
|
+
".": "./src/index.ts",
|
|
51
|
+
"./tsconfig.server.json": "./tsconfig.plugin-server.json",
|
|
52
|
+
"./tsconfig.window.json": "./tsconfig.plugin-window.json",
|
|
53
|
+
"./solid": "./solid.ts",
|
|
54
|
+
"./web": {
|
|
55
|
+
"types": "./web.d.ts"
|
|
56
|
+
},
|
|
57
|
+
"./client": "./client.tsx",
|
|
58
|
+
"./window-state-host": "./window-state-host.ts",
|
|
59
|
+
"./unstable": "./src/unstable.ts",
|
|
60
|
+
"./agent-turn": "./src/agent-turn.ts",
|
|
61
|
+
"./agent-launch": "./caller/agent-launch.ts",
|
|
62
|
+
"./internal/contracts": "./src/internal/contracts.ts",
|
|
63
|
+
"./internal/build": "./build-internals.ts",
|
|
64
|
+
"./internal/server-build": "./server-build-internals.ts",
|
|
65
|
+
"./internal/bundle": "./tools/bundle.mjs"
|
|
66
|
+
},
|
|
67
|
+
"publishConfig": {
|
|
68
|
+
"access": "public",
|
|
69
|
+
"tag": "dev"
|
|
70
|
+
},
|
|
71
|
+
"dependencies": {
|
|
72
|
+
"typescript": "5.9.3"
|
|
73
|
+
},
|
|
74
|
+
"devDependencies": {
|
|
75
|
+
"@solidjs/vite-plugin": "3.0.0",
|
|
76
|
+
"@testing-library/dom": "10.4.2",
|
|
77
|
+
"jsdom": "31.0.1",
|
|
78
|
+
"vitest": "5.1.0"
|
|
79
|
+
},
|
|
80
|
+
"peerDependencies": {
|
|
81
|
+
"@solidjs/web": "2.0.0",
|
|
82
|
+
"@types/node": "26.6.6",
|
|
83
|
+
"solid-js": "2.0.0",
|
|
84
|
+
"vite": "8.3.6"
|
|
85
|
+
},
|
|
86
|
+
"peerDependenciesMeta": {
|
|
87
|
+
"solid-js": {
|
|
88
|
+
"optional": true
|
|
89
|
+
},
|
|
90
|
+
"@solidjs/web": {
|
|
91
|
+
"optional": true
|
|
92
|
+
},
|
|
93
|
+
"@types/node": {
|
|
94
|
+
"optional": true
|
|
95
|
+
},
|
|
96
|
+
"vite": {
|
|
97
|
+
"optional": true
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
package/quit.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Quitting the desktop app while a plugin still has work on this computer.
|
|
3
|
+
* A plugin registers a check from its window code; when the person quits,
|
|
4
|
+
* the app asks every check. If any answers with a blocker, the app asks
|
|
5
|
+
* first ("Claude is still working in 1 thread · Stop and quit · Cancel"),
|
|
6
|
+
* and Stop and quit runs each blocker's `stop` before the app closes:
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* import { onQuit } from "@tokamaq/sdk/client";
|
|
10
|
+
* onQuit(async () =>
|
|
11
|
+
* (await running()).length ? { message: "Claude is still working in 1 thread", stop: stopAll } : undefined,
|
|
12
|
+
* );
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
import { TIMED_OUT, within } from "./src/within";
|
|
16
|
+
|
|
17
|
+
export interface QuitBlocker {
|
|
18
|
+
/** One line naming what would be lost, as the dialog shows it. */
|
|
19
|
+
readonly message: string;
|
|
20
|
+
/** Ends the work cleanly; the app quits once every blocker's stop has settled. */
|
|
21
|
+
stop(): Promise<unknown>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type QuitCheck = () => QuitBlocker | undefined | Promise<QuitBlocker | undefined>;
|
|
25
|
+
|
|
26
|
+
// Kept on globalThis: the app and every plugin bundle must reach the same checks.
|
|
27
|
+
const KEY = Symbol.for("tokamaq.quitChecks");
|
|
28
|
+
|
|
29
|
+
function checks(): Set<QuitCheck> {
|
|
30
|
+
const scope = globalThis as typeof globalThis & { [KEY]?: Set<QuitCheck> };
|
|
31
|
+
return (scope[KEY] ??= new Set());
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Registers a check the app runs when the person quits; returns the function that removes it. */
|
|
35
|
+
export function onQuit(check: QuitCheck): () => void {
|
|
36
|
+
checks().add(check);
|
|
37
|
+
return () => void checks().delete(check);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* For the app: every blocker the registered checks report. A check that
|
|
42
|
+
* throws or does not answer within `ms` blocks nothing, so a broken plugin
|
|
43
|
+
* cannot stop the person from quitting.
|
|
44
|
+
*/
|
|
45
|
+
export async function quitBlockers(ms = 2_000): Promise<QuitBlocker[]> {
|
|
46
|
+
const answers = await Promise.all(
|
|
47
|
+
[...checks()].map(async (check) => {
|
|
48
|
+
const answer = await within(
|
|
49
|
+
Promise.resolve()
|
|
50
|
+
.then(check)
|
|
51
|
+
.catch(() => undefined),
|
|
52
|
+
ms,
|
|
53
|
+
);
|
|
54
|
+
return answer === TIMED_OUT ? undefined : answer;
|
|
55
|
+
}),
|
|
56
|
+
);
|
|
57
|
+
return answers.filter((answer): answer is QuitBlocker => answer !== undefined);
|
|
58
|
+
}
|
package/regions.tsx
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { createContext, createSignal, onCleanup, Show, useContext, type Accessor } from "solid-js";
|
|
2
|
+
import { Portal, type JSX } from "@solidjs/web";
|
|
3
|
+
|
|
4
|
+
export type RegionName = "sidebar" | "header" | "panel";
|
|
5
|
+
type Children = { children?: JSX.Element };
|
|
6
|
+
function createRegionState() {
|
|
7
|
+
const [outlet, setOutlet] = createSignal<HTMLDivElement>();
|
|
8
|
+
const [count, setCount] = createSignal(0, { ownedWrite: true });
|
|
9
|
+
return { outlet, setOutlet, count, setCount };
|
|
10
|
+
}
|
|
11
|
+
function createRegions() {
|
|
12
|
+
const [titles, setTitles] = createSignal<readonly Accessor<string | undefined>[]>([], { ownedWrite: true });
|
|
13
|
+
return {
|
|
14
|
+
sidebar: createRegionState(),
|
|
15
|
+
header: createRegionState(),
|
|
16
|
+
panel: createRegionState(),
|
|
17
|
+
titles,
|
|
18
|
+
setTitles,
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
const Regions = createContext<ReturnType<typeof createRegions> | null>(null);
|
|
22
|
+
|
|
23
|
+
export function RegionProvider(props: Children) {
|
|
24
|
+
const regions = createRegions();
|
|
25
|
+
return <Regions value={regions}>{props.children}</Regions>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function RegionOutlet(props: { name: RegionName; class?: string }) {
|
|
29
|
+
const regions = useContext(Regions);
|
|
30
|
+
const region = regions?.[props.name];
|
|
31
|
+
let element!: HTMLDivElement;
|
|
32
|
+
onCleanup(() => {
|
|
33
|
+
if (region?.outlet() === element) region.setOutlet(undefined);
|
|
34
|
+
});
|
|
35
|
+
return (
|
|
36
|
+
<div
|
|
37
|
+
ref={(node) => {
|
|
38
|
+
element = node;
|
|
39
|
+
region?.setOutlet(node);
|
|
40
|
+
}}
|
|
41
|
+
// oxlint-disable-next-line shadcn/no-inline-styles -- Outlets must not introduce a layout box.
|
|
42
|
+
style={{ display: "contents" }}
|
|
43
|
+
data-region={props.name}
|
|
44
|
+
class={props.class}
|
|
45
|
+
/>
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function useRegionFilled(name: RegionName): () => boolean {
|
|
50
|
+
const region = useContext(Regions)?.[name];
|
|
51
|
+
return () => (region?.count() ?? 0) > 0;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function regionComponent(name: RegionName) {
|
|
55
|
+
return (props: Children) => {
|
|
56
|
+
const region = useContext(Regions)?.[name];
|
|
57
|
+
if (!region) return null;
|
|
58
|
+
region.setCount((count) => count + 1);
|
|
59
|
+
onCleanup(() => region.setCount((count) => count - 1));
|
|
60
|
+
return (
|
|
61
|
+
<Show when={region.outlet()}>{(outlet) => <Portal mount={outlet()}>{props.children}</Portal>}</Show>
|
|
62
|
+
);
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export const Region = {
|
|
67
|
+
Sidebar: regionComponent("sidebar"),
|
|
68
|
+
Header: regionComponent("header"),
|
|
69
|
+
Panel: regionComponent("panel"),
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Names the page while the calling view is mounted: the shell shows it in the
|
|
74
|
+
* tab and the window title. Undefined falls back to the view's title.
|
|
75
|
+
*/
|
|
76
|
+
export function usePageTitle(title: Accessor<string | undefined>): void {
|
|
77
|
+
const regions = useContext(Regions);
|
|
78
|
+
if (!regions) return;
|
|
79
|
+
regions.setTitles((list) => [...list, title]);
|
|
80
|
+
onCleanup(() => regions.setTitles((list) => list.filter((item) => item !== title)));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The title the most recently mounted view gave its page, for the shell. */
|
|
84
|
+
export function usePageTitleValue(): Accessor<string | undefined> {
|
|
85
|
+
const regions = useContext(Regions);
|
|
86
|
+
return () => {
|
|
87
|
+
const list = regions?.titles() ?? [];
|
|
88
|
+
for (let index = list.length - 1; index >= 0; index--) {
|
|
89
|
+
const value = list[index]!()?.trim();
|
|
90
|
+
if (value) return value;
|
|
91
|
+
}
|
|
92
|
+
return undefined;
|
|
93
|
+
};
|
|
94
|
+
}
|
package/screen-search.ts
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
export const searchAttributes = ["type", "href", "role"] as const;
|
|
2
|
+
type SearchAttribute = (typeof searchAttributes)[number];
|
|
3
|
+
|
|
4
|
+
export type AttributeFilters = Partial<Record<SearchAttribute, string>> & {
|
|
5
|
+
aria?: Readonly<Record<string, string>>;
|
|
6
|
+
};
|
|
7
|
+
export type ScreenSearch = AttributeFilters & { name: string; in?: string; nth?: number };
|
|
8
|
+
export type ScreenElement = { target: string; fingerprint?: string };
|
|
9
|
+
export type ScreenTarget = ScreenElement & { search?: ScreenSearch };
|
|
10
|
+
type ScreenKind = "element" | "render function";
|
|
11
|
+
type Candidate = ScreenElement & {
|
|
12
|
+
name: string;
|
|
13
|
+
ancestors: readonly string[];
|
|
14
|
+
attributes?: Readonly<Record<string, string>>;
|
|
15
|
+
computed?: readonly string[];
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export function isSearchAttribute(name: string): name is SearchAttribute {
|
|
19
|
+
return searchAttributes.some((key) => key === name);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function isAriaAttribute(name: string) {
|
|
23
|
+
return name.startsWith("aria-") && name.length > 5;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function flattenAttributes(filters: AttributeFilters) {
|
|
27
|
+
const attributes: [string, string][] = [];
|
|
28
|
+
for (const name of searchAttributes) {
|
|
29
|
+
const value = filters[name];
|
|
30
|
+
if (value !== undefined) attributes.push([name, value]);
|
|
31
|
+
}
|
|
32
|
+
for (const [name, value] of Object.entries(filters.aria ?? {})) attributes.push([`aria-${name}`, value]);
|
|
33
|
+
return attributes;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function attributeFilters(options: Readonly<Record<string, string | number>>) {
|
|
37
|
+
const filters: AttributeFilters = {};
|
|
38
|
+
const aria: [string, string][] = [];
|
|
39
|
+
for (const [name, value] of Object.entries(options)) {
|
|
40
|
+
if (typeof value !== "string") continue;
|
|
41
|
+
if (isSearchAttribute(name)) filters[name] = value;
|
|
42
|
+
else if (isAriaAttribute(name)) aria.push([name.slice(5), value]);
|
|
43
|
+
}
|
|
44
|
+
if (aria.length) filters.aria = Object.fromEntries(aria);
|
|
45
|
+
return filters;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Ordered pairs preserve source order even for names like "123". Leaves hold
|
|
49
|
+
// just a fingerprint (or null); branches use "" for their own fingerprint.
|
|
50
|
+
// With attributes, that fingerprint becomes [fingerprint, name, value, …].
|
|
51
|
+
// A leading ":" at the root marks trees with render function addresses.
|
|
52
|
+
// Inside, branches with no "" or ":" entry are render functions. A ":" entry
|
|
53
|
+
// marks a scope that only encloses other functions and cannot be attached to.
|
|
54
|
+
export type ScreenTree = readonly (string | null | ScreenTree)[];
|
|
55
|
+
|
|
56
|
+
function segmentName(segment: string) {
|
|
57
|
+
// Consume escapes before looking for a positional suffix. For example, the
|
|
58
|
+
// closing dollar in "$24$2" belongs to the encoded name "$2".
|
|
59
|
+
return segment.replace(
|
|
60
|
+
/\$([\da-f]+)\$|\$\d+$|^\$(?=(?:target|fingerprint|__proto__|constructor|prototype)(?:\$\d+)?$)/g,
|
|
61
|
+
(_, hex: string | undefined) => (hex ? String.fromCharCode(parseInt(hex, 16)) : ""),
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function screenElementName(target: string) {
|
|
66
|
+
const [owner, ...path] = target.split(".");
|
|
67
|
+
return path.length ? `${owner} ${path.map(segmentName).join(" › ")}` : target;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function screenElements(plugin: string, tree: ScreenTree, kind: ScreenKind = "element") {
|
|
71
|
+
const elements: Candidate[] = [];
|
|
72
|
+
const functions = kind === "render function";
|
|
73
|
+
if (functions && tree[0] !== ":") return elements; // Older bundles have no instance hook.
|
|
74
|
+
function visit(branch: ScreenTree, target: string, ancestors: readonly string[]) {
|
|
75
|
+
if (functions && branch[0] !== "" && branch[0] !== ":")
|
|
76
|
+
elements.push({ target, name: ancestors.at(-1)!, ancestors: ancestors.slice(0, -1) });
|
|
77
|
+
for (let i = 0; i < branch.length; i += 2) {
|
|
78
|
+
const segment = branch[i] as string;
|
|
79
|
+
const value = branch[i + 1]!;
|
|
80
|
+
if (segment === ":") continue;
|
|
81
|
+
if (segment === "") {
|
|
82
|
+
if (functions) continue;
|
|
83
|
+
const packed = typeof value === "object" && value !== null ? value : undefined;
|
|
84
|
+
let attributes: Record<string, string> | undefined;
|
|
85
|
+
if (packed) {
|
|
86
|
+
attributes = {};
|
|
87
|
+
for (let j = 1; j < packed.length; j += 2)
|
|
88
|
+
attributes[packed[j] as string] = packed[j + 1] as string;
|
|
89
|
+
}
|
|
90
|
+
const fingerprint = packed ? packed[0] : value;
|
|
91
|
+
elements.push({
|
|
92
|
+
target,
|
|
93
|
+
name: ancestors.at(-1)!,
|
|
94
|
+
ancestors: ancestors.slice(0, -1),
|
|
95
|
+
fingerprint: typeof fingerprint === "string" ? fingerprint : undefined,
|
|
96
|
+
attributes,
|
|
97
|
+
});
|
|
98
|
+
} else {
|
|
99
|
+
const name = segmentName(segment);
|
|
100
|
+
const path = `${target}.${segment}`;
|
|
101
|
+
if (typeof value === "string" || value === null) {
|
|
102
|
+
if (!functions) elements.push({ target: path, name, ancestors, fingerprint: value ?? undefined });
|
|
103
|
+
} else visit(value, path, [...ancestors, name]);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
visit(tree, plugin, []);
|
|
108
|
+
return elements;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function screenTarget(options: Readonly<Record<string, string | number>>): ScreenTarget {
|
|
112
|
+
const { target, fingerprint, name, in: within, nth } = options;
|
|
113
|
+
return {
|
|
114
|
+
target: String(target),
|
|
115
|
+
fingerprint: typeof fingerprint === "string" ? fingerprint : undefined,
|
|
116
|
+
search:
|
|
117
|
+
typeof name === "string"
|
|
118
|
+
? {
|
|
119
|
+
name,
|
|
120
|
+
...attributeFilters(options),
|
|
121
|
+
in: typeof within === "string" ? within : undefined,
|
|
122
|
+
nth: typeof nth === "number" ? nth : undefined,
|
|
123
|
+
}
|
|
124
|
+
: undefined,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function resolveScreenSearch(
|
|
129
|
+
elements: readonly Candidate[],
|
|
130
|
+
search?: ScreenSearch,
|
|
131
|
+
previous?: ScreenElement,
|
|
132
|
+
kind: ScreenKind = "element",
|
|
133
|
+
): { element: ScreenElement; reason?: never } | { element?: never; reason: string } {
|
|
134
|
+
if (!search) {
|
|
135
|
+
const samePath = elements.find((element) => element.target === previous?.target);
|
|
136
|
+
if (!samePath) return { reason: `targets missing screen part ${previous?.target}` };
|
|
137
|
+
if (previous?.fingerprint && previous.fingerprint !== samePath.fingerprint)
|
|
138
|
+
return { reason: `targets a different ${kind} at ${previous.target}` };
|
|
139
|
+
return { element: samePath };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const { name, in: within, nth } = search;
|
|
143
|
+
const named = elements.filter((element) => element.name === name);
|
|
144
|
+
const attributes = flattenAttributes(search);
|
|
145
|
+
const scoped = named.filter(
|
|
146
|
+
(element) =>
|
|
147
|
+
(within === undefined || element.ancestors.includes(within)) &&
|
|
148
|
+
attributes.every(([key, value]) => element.attributes?.[key] === value),
|
|
149
|
+
);
|
|
150
|
+
const matches = nth === undefined ? scoped : scoped.slice(nth - 1, nth);
|
|
151
|
+
// A name says which element is meant, so a search without `nth` follows it
|
|
152
|
+
// wherever the owner moves it. Only a position can come to mean another
|
|
153
|
+
// element: an `nth` search stays on the element it found, or is skipped.
|
|
154
|
+
const pinned = !!previous && nth !== undefined;
|
|
155
|
+
const retained =
|
|
156
|
+
previous &&
|
|
157
|
+
matches.find(
|
|
158
|
+
(element) =>
|
|
159
|
+
element.target === previous.target &&
|
|
160
|
+
(!pinned || !previous.fingerprint || previous.fingerprint === element.fingerprint),
|
|
161
|
+
);
|
|
162
|
+
if (retained) return { element: retained };
|
|
163
|
+
if (!pinned && matches.length === 1) return { element: matches[0]! };
|
|
164
|
+
|
|
165
|
+
const issue =
|
|
166
|
+
matches.length === 0
|
|
167
|
+
? `matches no ${kind}s`
|
|
168
|
+
: pinned
|
|
169
|
+
? `targets a different ${kind}`
|
|
170
|
+
: `matches several ${kind}s`;
|
|
171
|
+
return { reason: searchProblem(search, issue, scoped.length ? scoped : named) };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function describeScreenSearch(search: ScreenSearch) {
|
|
175
|
+
const aria = Object.entries(search.aria ?? {})
|
|
176
|
+
.map(([key, value]) => `${JSON.stringify(key)}: ${JSON.stringify(value)}`)
|
|
177
|
+
.join(", ");
|
|
178
|
+
const filters = [
|
|
179
|
+
search.in === undefined ? undefined : `in: ${JSON.stringify(search.in)}`,
|
|
180
|
+
...searchAttributes.flatMap((key) =>
|
|
181
|
+
search[key] === undefined ? [] : [`${key}: ${JSON.stringify(search[key])}`],
|
|
182
|
+
),
|
|
183
|
+
aria ? `aria: { ${aria} }` : undefined,
|
|
184
|
+
search.nth === undefined ? undefined : `nth: ${search.nth}`,
|
|
185
|
+
].filter(Boolean);
|
|
186
|
+
return `find(${JSON.stringify(search.name)}${filters.length ? `, { ${filters.join(", ")} }` : ""})`;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function unnamedTargetWarning(plugin: string, search: ScreenSearch, target: string) {
|
|
190
|
+
return `Plugin "${plugin}": ${describeScreenSearch(search)} targets unnamed element ${target}; add data-part to name this element`;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function searchProblem(search: ScreenSearch, issue: string, options: readonly Candidate[]) {
|
|
194
|
+
const filters = flattenAttributes(search);
|
|
195
|
+
const labels = options.map(({ ancestors, name, attributes, computed }) => {
|
|
196
|
+
const path = [...ancestors, name].join(" › ");
|
|
197
|
+
if (!filters.length) return path;
|
|
198
|
+
const details = [
|
|
199
|
+
...Object.entries(attributes ?? {}).map(([key, value]) => `${key}=${JSON.stringify(value)}`),
|
|
200
|
+
...(computed ?? []).map((key) => `${key}={…} (a filter cannot match a computed value)`),
|
|
201
|
+
];
|
|
202
|
+
return details.length ? `${path} [${details.join(", ")}]` : `${path} [no static filter attributes]`;
|
|
203
|
+
});
|
|
204
|
+
const candidates =
|
|
205
|
+
labels
|
|
206
|
+
.map((label, index) =>
|
|
207
|
+
labels.indexOf(label) === labels.lastIndexOf(label) ? label : `${label} (match ${index + 1})`,
|
|
208
|
+
)
|
|
209
|
+
.join(", ") || "none";
|
|
210
|
+
return `${describeScreenSearch(search)} ${issue}; candidates: ${candidates}. Narrow the search with in or nth`;
|
|
211
|
+
}
|
package/send-file.ts
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
const defaultPartSize = 8 * 1024 * 1024;
|
|
2
|
+
const maxAttempts = 5;
|
|
3
|
+
|
|
4
|
+
export interface SendFileOptions {
|
|
5
|
+
onProgress?: (sent: number, total: number) => void;
|
|
6
|
+
signal?: AbortSignal;
|
|
7
|
+
/** Advanced: maximum bytes per request. Defaults to 8 MiB. */
|
|
8
|
+
partSize?: number;
|
|
9
|
+
/** Advanced: initial retry delay in milliseconds, doubled on each retry. */
|
|
10
|
+
retryDelayMs?: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export class UploadHttpError extends Error {
|
|
14
|
+
constructor(
|
|
15
|
+
readonly status: number,
|
|
16
|
+
message: string,
|
|
17
|
+
) {
|
|
18
|
+
super(message ? `Upload HTTP ${status}: ${message}` : `Upload HTTP ${status}`);
|
|
19
|
+
this.name = "UploadHttpError";
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
let connection: { origin: string } | undefined;
|
|
24
|
+
|
|
25
|
+
/** The window host supplies the same HTTP origin it uses for plugin assets. */
|
|
26
|
+
export function __bindUploadOrigin(http: string): () => void {
|
|
27
|
+
const binding = { origin: new URL(http).origin };
|
|
28
|
+
connection = binding;
|
|
29
|
+
return () => {
|
|
30
|
+
if (connection === binding) connection = undefined;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function sendFile(
|
|
35
|
+
url: string,
|
|
36
|
+
blob: Blob,
|
|
37
|
+
{ onProgress, signal, partSize = defaultPartSize, retryDelayMs = 250 }: SendFileOptions = {},
|
|
38
|
+
): Promise<{ id: string }> {
|
|
39
|
+
signal?.throwIfAborted();
|
|
40
|
+
if (!Number.isSafeInteger(partSize) || partSize <= 0) throw new RangeError("Invalid upload part size");
|
|
41
|
+
const target = new URL(url, connection?.origin);
|
|
42
|
+
const firstHeaders = uploadHeaders(blob);
|
|
43
|
+
|
|
44
|
+
let offset = 0;
|
|
45
|
+
let started = false;
|
|
46
|
+
let end = Math.min(partSize, blob.size);
|
|
47
|
+
let attempts = 0;
|
|
48
|
+
let needsOffset = false;
|
|
49
|
+
let handledConflict = false;
|
|
50
|
+
|
|
51
|
+
function confirm(next: number) {
|
|
52
|
+
if (next !== offset) {
|
|
53
|
+
offset = next;
|
|
54
|
+
onProgress?.(offset, blob.size);
|
|
55
|
+
}
|
|
56
|
+
if (offset >= end && offset < blob.size) {
|
|
57
|
+
end = Math.min(offset + partSize, blob.size);
|
|
58
|
+
attempts = 0;
|
|
59
|
+
handledConflict = false;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
for (;;) {
|
|
64
|
+
signal?.throwIfAborted();
|
|
65
|
+
const method: "HEAD" | "PATCH" | "POST" = needsOffset ? "HEAD" : started ? "PATCH" : "POST";
|
|
66
|
+
const response = await uploadRequest(target, {
|
|
67
|
+
method,
|
|
68
|
+
signal,
|
|
69
|
+
...(method === "HEAD"
|
|
70
|
+
? { cache: "no-store" }
|
|
71
|
+
: {
|
|
72
|
+
headers: method === "POST" ? firstHeaders : { "Upload-Offset": String(offset) },
|
|
73
|
+
body: blob.slice(offset, end),
|
|
74
|
+
}),
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
if ("error" in response || response.status >= 500) {
|
|
78
|
+
if (++attempts >= maxAttempts) {
|
|
79
|
+
throw "error" in response ? response.error : await httpError(response, signal);
|
|
80
|
+
}
|
|
81
|
+
if (!("error" in response)) await response.body?.cancel().catch(() => {});
|
|
82
|
+
await wait(retryDelayMs * 2 ** (attempts - 1), signal);
|
|
83
|
+
needsOffset = true;
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (response.status === 409 && method !== "HEAD" && !handledConflict && ++attempts < maxAttempts) {
|
|
88
|
+
handledConflict = true;
|
|
89
|
+
needsOffset = true;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (!response.ok) throw await httpError(response, signal);
|
|
93
|
+
|
|
94
|
+
if (response.status === 200 && method !== "HEAD") {
|
|
95
|
+
const result = await uploadResult(response);
|
|
96
|
+
signal?.throwIfAborted();
|
|
97
|
+
if (!blob.size || offset !== blob.size) onProgress?.(blob.size, blob.size);
|
|
98
|
+
return result;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const next = uploadOffset(response, method === "HEAD" ? offset : offset + 1, blob.size);
|
|
102
|
+
// A HEAD on an unopened upload has offset 0 and no length. A started
|
|
103
|
+
// upload may also have offset 0 if the first connection dropped early.
|
|
104
|
+
started = method !== "HEAD" || next > 0 || response.headers.has("Upload-Length");
|
|
105
|
+
needsOffset = false;
|
|
106
|
+
confirm(next);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function uploadHeaders(blob: Blob): Record<string, string> {
|
|
111
|
+
// Declare the length even for one part, so an interrupted POST is resumable.
|
|
112
|
+
const headers: Record<string, string> = { "Upload-Length": String(blob.size) };
|
|
113
|
+
if (blob.type) headers["Content-Type"] = blob.type;
|
|
114
|
+
if (typeof File !== "undefined" && blob instanceof File) {
|
|
115
|
+
// Keep common names readable. The server stores the fallback header as sent.
|
|
116
|
+
headers["X-File-Name"] =
|
|
117
|
+
/^[ -~]+$/.test(blob.name) && blob.name === blob.name.trim()
|
|
118
|
+
? blob.name
|
|
119
|
+
: encodeURIComponent(blob.name);
|
|
120
|
+
}
|
|
121
|
+
return headers;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function uploadRequest(target: URL, init: RequestInit): Promise<Response | { error: unknown }> {
|
|
125
|
+
try {
|
|
126
|
+
return await fetch(target, init);
|
|
127
|
+
} catch (error) {
|
|
128
|
+
init.signal?.throwIfAborted();
|
|
129
|
+
return { error };
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function uploadOffset(response: Response, min: number, max: number): number {
|
|
134
|
+
const header = response.headers.get("Upload-Offset");
|
|
135
|
+
const offset = Number(header);
|
|
136
|
+
if (response.status !== 204 || !header || !/^\d+$/.test(header) || offset < min || offset > max) {
|
|
137
|
+
throw new Error("Invalid upload offset");
|
|
138
|
+
}
|
|
139
|
+
return offset;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function uploadResult(response: Response): Promise<{ id: string }> {
|
|
143
|
+
const result: unknown = await response.json();
|
|
144
|
+
if (
|
|
145
|
+
typeof result !== "object" ||
|
|
146
|
+
!result ||
|
|
147
|
+
!("id" in result) ||
|
|
148
|
+
typeof result.id !== "string" ||
|
|
149
|
+
!result.id
|
|
150
|
+
) {
|
|
151
|
+
throw new Error("Upload response did not contain a file ID");
|
|
152
|
+
}
|
|
153
|
+
return { id: result.id };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function httpError(response: Response, signal?: AbortSignal): Promise<UploadHttpError> {
|
|
157
|
+
const body = await response.text().catch(() => "");
|
|
158
|
+
signal?.throwIfAborted();
|
|
159
|
+
return new UploadHttpError(response.status, body.trim() || response.statusText);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function wait(ms: number, signal?: AbortSignal): Promise<void> {
|
|
163
|
+
signal?.throwIfAborted();
|
|
164
|
+
return new Promise((resolve, reject) => {
|
|
165
|
+
const timer = setTimeout(() => {
|
|
166
|
+
signal?.removeEventListener("abort", abort);
|
|
167
|
+
resolve();
|
|
168
|
+
}, ms);
|
|
169
|
+
function abort() {
|
|
170
|
+
clearTimeout(timer);
|
|
171
|
+
reject(signal?.reason);
|
|
172
|
+
}
|
|
173
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
174
|
+
});
|
|
175
|
+
}
|