@minecraftbot-com/plugin 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +188 -177
- package/README.md +47 -46
- package/dist/api.d.ts +4 -1
- package/dist/cli/api.d.ts +23 -0
- package/dist/cli/api.js +8 -0
- package/dist/cli/build.d.ts +1 -0
- package/dist/cli/build.js +9 -2
- package/dist/cli/check.d.ts +7 -0
- package/dist/cli/check.js +2 -1
- package/dist/cli/deploy.d.ts +13 -0
- package/dist/cli/deploy.js +51 -0
- package/dist/cli/main.js +7 -0
- package/dist/hosted/fetch.d.ts +53 -0
- package/dist/hosted/fetch.js +216 -0
- package/dist/hosted/index.d.ts +3 -0
- package/dist/hosted/index.js +81 -0
- package/dist/runtime/runtime.d.ts +1 -1
- package/dist/runtime/runtime.js +1 -1
- package/package.json +6 -1
- package/src/api.ts +4 -1
- package/src/cli/api.ts +105 -79
- package/src/cli/build.ts +9 -2
- package/src/cli/check.ts +104 -103
- package/src/cli/deploy.ts +60 -0
- package/src/cli/main.ts +7 -0
- package/src/hosted/fetch.ts +224 -0
- package/src/hosted/index.ts +121 -0
- package/src/runtime/runtime.ts +281 -281
- package/templates/basic/AGENTS.md +32 -31
- package/templates/basic/README.md +14 -13
- package/templates/basic/package.json +1 -0
package/src/cli/build.ts
CHANGED
|
@@ -43,13 +43,20 @@ export function devBuildOptions(project: Project, outfile: string): esbuild.Buil
|
|
|
43
43
|
/**
|
|
44
44
|
* The bundle a hosted runner runs: everything included, minified, and the SDK compiled from its TypeScript
|
|
45
45
|
* source (the `minebot-source` condition) so enum members become plain strings and the enum objects drop out.
|
|
46
|
+
* It is one script (QuickJS evaluates it as a global script) that hands the plugin to `serveHosted`.
|
|
46
47
|
*/
|
|
47
48
|
export function hostedBuildOptions(project: Project, outfile: string): esbuild.BuildOptions {
|
|
49
|
+
const entry = JSON.stringify(project.entry.replace(/\\/g, "/"));
|
|
48
50
|
return {
|
|
49
|
-
|
|
51
|
+
stdin: {
|
|
52
|
+
contents: `import plugin from ${entry};\nimport { serveHosted } from "@minecraftbot-com/plugin/hosted";\nserveHosted(plugin);\n`,
|
|
53
|
+
resolveDir: project.root,
|
|
54
|
+
sourcefile: "minebot-hosted-entry.js",
|
|
55
|
+
loader: "js",
|
|
56
|
+
},
|
|
50
57
|
outfile,
|
|
51
58
|
bundle: true,
|
|
52
|
-
format: "
|
|
59
|
+
format: "iife",
|
|
53
60
|
platform: "neutral",
|
|
54
61
|
target: "es2022",
|
|
55
62
|
minify: true,
|
package/src/cli/check.ts
CHANGED
|
@@ -1,103 +1,104 @@
|
|
|
1
|
-
import { mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
-
import { join } from "node:path";
|
|
3
|
-
import * as esbuild from "esbuild";
|
|
4
|
-
import { PERMISSION_LABELS } from "../generated/permission-labels.js";
|
|
5
|
-
import { networkHost } from "../permissions.js";
|
|
6
|
-
import { buildManifest } from "../runtime/runtime.js";
|
|
7
|
-
import type { Manifest } from "../protocol.js";
|
|
8
|
-
import { devBuildOptions, findProject, formatErrors, hostedBuildOptions, loadPlugin } from "./build.js";
|
|
9
|
-
import { bold, dim, fail, green, info, warn, yellow } from "./output.js";
|
|
10
|
-
|
|
11
|
-
/** Above this a hosted plugin probably won't fit its memory after start (about 1.5 MB, mostly bundled code). */
|
|
12
|
-
const BUNDLE_WARNING_BYTES = 256 * 1024;
|
|
13
|
-
|
|
14
|
-
interface Built {
|
|
15
|
-
manifest: Manifest;
|
|
16
|
-
bundle: string;
|
|
17
|
-
bytes: number;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
const
|
|
50
|
-
const
|
|
51
|
-
const
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
if (
|
|
56
|
-
if (
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
if (
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
const
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
info(
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
info(`
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
for (const
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
const
|
|
98
|
-
const
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
}
|
|
1
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import * as esbuild from "esbuild";
|
|
4
|
+
import { PERMISSION_LABELS } from "../generated/permission-labels.js";
|
|
5
|
+
import { networkHost } from "../permissions.js";
|
|
6
|
+
import { buildManifest } from "../runtime/runtime.js";
|
|
7
|
+
import type { Manifest } from "../protocol.js";
|
|
8
|
+
import { devBuildOptions, findProject, formatErrors, hostedBuildOptions, loadPlugin } from "./build.js";
|
|
9
|
+
import { bold, dim, fail, green, info, warn, yellow } from "./output.js";
|
|
10
|
+
|
|
11
|
+
/** Above this a hosted plugin probably won't fit its memory after start (about 1.5 MB, mostly bundled code). */
|
|
12
|
+
const BUNDLE_WARNING_BYTES = 256 * 1024;
|
|
13
|
+
|
|
14
|
+
export interface Built {
|
|
15
|
+
manifest: Manifest;
|
|
16
|
+
bundle: string;
|
|
17
|
+
bytes: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Builds the manifest (by running the plugin in Node) and the hosted bundle into outDir. */
|
|
21
|
+
export async function buildAll(outDir: string): Promise<Built> {
|
|
22
|
+
const project = findProject();
|
|
23
|
+
mkdirSync(outDir, { recursive: true });
|
|
24
|
+
|
|
25
|
+
// The manifest comes from running the plugin's module in Node; that build stays out of the output folder.
|
|
26
|
+
mkdirSync(join(project.root, ".minebot"), { recursive: true });
|
|
27
|
+
const devFile = join(project.root, ".minebot", "probe.mjs");
|
|
28
|
+
try {
|
|
29
|
+
await esbuild.build(devBuildOptions(project, devFile));
|
|
30
|
+
} catch (e) {
|
|
31
|
+
fail(`Build failed:\n${formatErrors((e as esbuild.BuildFailure).errors ?? [])}`);
|
|
32
|
+
}
|
|
33
|
+
const plugin = await loadPlugin(devFile);
|
|
34
|
+
const manifest = buildManifest(plugin, project.version);
|
|
35
|
+
|
|
36
|
+
const bundle = join(outDir, "plugin.js");
|
|
37
|
+
let result: esbuild.BuildResult;
|
|
38
|
+
try {
|
|
39
|
+
result = await esbuild.build(hostedBuildOptions(project, bundle));
|
|
40
|
+
} catch (e) {
|
|
41
|
+
fail(`Hosted build failed:\n${formatErrors((e as esbuild.BuildFailure).errors ?? [])}`);
|
|
42
|
+
}
|
|
43
|
+
const bytes = Object.values(result.metafile!.outputs).reduce((n, o) => n + o.bytes, 0);
|
|
44
|
+
return { manifest, bundle, bytes };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Problems with a manifest: each is a sentence a person (or an AI) can act on. */
|
|
48
|
+
export function review(manifest: Manifest, bytes: number): { problems: string[]; notes: string[] } {
|
|
49
|
+
const problems: string[] = [];
|
|
50
|
+
const notes: string[] = [];
|
|
51
|
+
const permissions = new Set(manifest.permissions);
|
|
52
|
+
const hosts = manifest.permissions.map(networkHost).filter((h): h is string => h !== null);
|
|
53
|
+
const urlSettings = Object.entries(manifest.settings).filter(([, s]) => s.type === "url");
|
|
54
|
+
|
|
55
|
+
if (manifest.name.length > 64) problems.push("The name is longer than 64 characters.");
|
|
56
|
+
if (hosts.some(h => h === "*" || h.startsWith("*.") && h.split(".").length < 3)) problems.push("A network permission covers too much; name the hosts you call.");
|
|
57
|
+
if (permissions.has("ChatRead") && (hosts.length > 0 || urlSettings.length > 0)) {
|
|
58
|
+
notes.push(`Users will be told this plugin "can read chat and send it to ${[...hosts, ...urlSettings.map(([k]) => `the URL in "${k}"`)].join(", ")}".`);
|
|
59
|
+
}
|
|
60
|
+
if (permissions.has("ProfileBots")) notes.push("ProfileBots lets the plugin connect and disconnect every bot of the profile; users see that at install.");
|
|
61
|
+
if (manifest.exclusive.length === 0 && (permissions.has("Move") || permissions.has("Interact"))) {
|
|
62
|
+
notes.push("The plugin moves or digs but declares no exclusive control units; another plugin may drive the same bot at once. Add exclusive: [ControlUnit.Movement, ...].");
|
|
63
|
+
}
|
|
64
|
+
if (bytes > BUNDLE_WARNING_BYTES) {
|
|
65
|
+
problems.push(`The hosted bundle is ${(bytes / 1024).toFixed(0)} KB; hosted plugins have about 1.5 MB after start, and bundled libraries are the usual cause. Import only what you use.`);
|
|
66
|
+
}
|
|
67
|
+
return { problems, notes };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** `minebot check`: builds the plugin as it would be uploaded and reports what users will be asked to allow. */
|
|
71
|
+
export async function check(): Promise<void> {
|
|
72
|
+
const project = findProject();
|
|
73
|
+
const { manifest, bytes } = await buildAll(join(project.root, ".minebot", "check"));
|
|
74
|
+
|
|
75
|
+
info(`${bold(manifest.name)} ${dim(manifest.version)}`);
|
|
76
|
+
info("\nUsers will be asked to allow:");
|
|
77
|
+
if (manifest.permissions.length === 0) info(dim(" nothing (logs, settings, storage and timers are always allowed)"));
|
|
78
|
+
for (const p of manifest.permissions) {
|
|
79
|
+
const host = networkHost(p);
|
|
80
|
+
info(` • ${host ? `Can send and receive data from ${host}` : PERMISSION_LABELS[p as keyof typeof PERMISSION_LABELS] ?? p}`);
|
|
81
|
+
}
|
|
82
|
+
const settings = Object.entries(manifest.settings);
|
|
83
|
+
if (settings.length) info(`\nSettings: ${settings.map(([k, s]) => `${k} (${s.type}${s.secret ? ", secret" : ""})`).join(", ")}`);
|
|
84
|
+
const storage = Object.entries(manifest.storage);
|
|
85
|
+
if (storage.length) info(`Storage: ${storage.map(([k, s]) => `${k} (${s.kind}, ${s.scope})`).join(", ")}`);
|
|
86
|
+
info(`Hosted bundle: ${(bytes / 1024).toFixed(1)} KB`);
|
|
87
|
+
|
|
88
|
+
const { problems, notes } = review(manifest, bytes);
|
|
89
|
+
for (const n of notes) info(`\n${yellow("note:")} ${n}`);
|
|
90
|
+
for (const p of problems) warn(p);
|
|
91
|
+
if (problems.length) process.exit(1);
|
|
92
|
+
info(`\n${green("ok")}`);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** `minebot build`: writes dist/plugin.js (the hosted bundle) and dist/manifest.json, for upload. */
|
|
96
|
+
export async function build(): Promise<void> {
|
|
97
|
+
const project = findProject();
|
|
98
|
+
const outDir = join(project.root, "dist");
|
|
99
|
+
const { manifest, bytes } = await buildAll(outDir);
|
|
100
|
+
writeFileSync(join(outDir, "manifest.json"), JSON.stringify(manifest, null, 2));
|
|
101
|
+
const { problems } = review(manifest, bytes);
|
|
102
|
+
for (const p of problems) warn(p);
|
|
103
|
+
info(`Wrote dist/plugin.js (${(bytes / 1024).toFixed(1)} KB) and dist/manifest.json`);
|
|
104
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { SDK_VERSION } from "../runtime/runtime.js";
|
|
4
|
+
import { deployBundle } from "./api.js";
|
|
5
|
+
import { findProject } from "./build.js";
|
|
6
|
+
import { buildAll, review } from "./check.js";
|
|
7
|
+
import { bold, cyan, dim, fail, green, info, warn } from "./output.js";
|
|
8
|
+
|
|
9
|
+
export interface DeployArgs {
|
|
10
|
+
/** Run it on this profile (name or id) from now on. */
|
|
11
|
+
profile?: string;
|
|
12
|
+
/** Only these bots (names or ids) on that profile; default every bot. */
|
|
13
|
+
bots: string[];
|
|
14
|
+
/** Setting values for that profile. */
|
|
15
|
+
settingsFile?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* `minebot deploy`: builds the hosted bundle and uploads it as the plugin's new version, so it runs on MineBot's
|
|
20
|
+
* servers instead of your machine. Profiles it runs on move to the new version; `--profile` adds one.
|
|
21
|
+
*/
|
|
22
|
+
export async function deploy(args: DeployArgs): Promise<void> {
|
|
23
|
+
const project = findProject();
|
|
24
|
+
const { manifest, bundle, bytes } = await buildAll(join(project.root, ".minebot", "deploy"));
|
|
25
|
+
const { problems } = review(manifest, bytes);
|
|
26
|
+
if (problems.length) {
|
|
27
|
+
for (const p of problems) warn(p);
|
|
28
|
+
fail("Fix these before deploying.", "`minebot check` shows the same list.");
|
|
29
|
+
}
|
|
30
|
+
if ((args.bots.length || args.settingsFile) && !args.profile) fail("--bot and --settings need --profile.");
|
|
31
|
+
|
|
32
|
+
let settings: Record<string, unknown> | undefined;
|
|
33
|
+
if (args.settingsFile) {
|
|
34
|
+
try {
|
|
35
|
+
settings = JSON.parse(readFileSync(args.settingsFile, "utf8")) as Record<string, unknown>;
|
|
36
|
+
} catch (e) {
|
|
37
|
+
fail(`Couldn't read ${args.settingsFile}: ${(e as Error).message}`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
info(`Deploying ${bold(manifest.name)} ${dim(manifest.version)} (${(bytes / 1024).toFixed(1)} KB)…`);
|
|
42
|
+
const result = await deployBundle({
|
|
43
|
+
manifest,
|
|
44
|
+
bundle: readFileSync(bundle, "utf8"),
|
|
45
|
+
sdk: SDK_VERSION,
|
|
46
|
+
profile: args.profile,
|
|
47
|
+
settings,
|
|
48
|
+
bots: args.bots.length ? args.bots : undefined,
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
info(result.newVersion ? green(`Deployed ${result.name} ${result.version}.`) : `${result.name} ${result.version} is already deployed; nothing to upload.`);
|
|
52
|
+
const enabled = result.installations.filter(i => i.enabled);
|
|
53
|
+
if (enabled.length === 0) {
|
|
54
|
+
info(`\nIt doesn't run anywhere yet: ${cyan("minebot deploy --profile <name>")}, or Plugins → Custom Plugins on the dashboard.`);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
info("\nRuns on MineBot's servers whenever these profiles run:");
|
|
58
|
+
for (const i of enabled) info(` • ${bold(i.profileName)}`);
|
|
59
|
+
info(dim(`\nIts console and status are on the dashboard: ${result.dashboard}`));
|
|
60
|
+
}
|
package/src/cli/main.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { pollDevice, startDevice } from "./api.js";
|
|
|
3
3
|
import { build, check } from "./check.js";
|
|
4
4
|
import { apiUrl, deleteCredentials, readCredentials, saveCredentials } from "./config.js";
|
|
5
5
|
import { create } from "./create.js";
|
|
6
|
+
import { deploy } from "./deploy.js";
|
|
6
7
|
import { dev } from "./dev.js";
|
|
7
8
|
import { bold, cyan, dim, fail, green, info } from "./output.js";
|
|
8
9
|
import { test } from "./test.js";
|
|
@@ -23,6 +24,10 @@ const HELP = `minebot ${SDK_VERSION}: write and run MineBot plugins
|
|
|
23
24
|
minebot test run test/*.test.ts against a fake bot
|
|
24
25
|
minebot check what users will be asked to allow, bundle size, problems
|
|
25
26
|
minebot build write dist/plugin.js and dist/manifest.json
|
|
27
|
+
minebot deploy [options] upload the plugin so it runs on MineBot's servers, not your machine
|
|
28
|
+
--profile <name|id> run it on this profile from now on (it already runs where it did)
|
|
29
|
+
--bot <name> on this bot only (repeat for more; default: every bot)
|
|
30
|
+
--settings <file.json> setting values for that profile
|
|
26
31
|
|
|
27
32
|
Environment: MINEBOT_API_URL overrides the API (default ${apiUrl()}).`;
|
|
28
33
|
|
|
@@ -95,6 +100,8 @@ async function main(argv: string[]): Promise<void> {
|
|
|
95
100
|
return check();
|
|
96
101
|
case "build":
|
|
97
102
|
return build();
|
|
103
|
+
case "deploy":
|
|
104
|
+
return deploy({ profile: option(args, "--profile"), bots: options(args, "--bot"), settingsFile: option(args, "--settings") });
|
|
98
105
|
case undefined:
|
|
99
106
|
case "help":
|
|
100
107
|
case "--help":
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
// fetch() for hosted plugins: the standard API on top of the runner's __host_fetch. The runner checks and makes
|
|
2
|
+
// every request (allowed hosts and URL settings, HTTPS, public addresses, sizes, rates) and logs it in the plugin
|
|
3
|
+
// console; this side only shapes the request and gives back a Response. QuickJS has no fetch, Headers or
|
|
4
|
+
// Response of its own, so minimal ones are defined here.
|
|
5
|
+
import { PluginError } from "../errors.js";
|
|
6
|
+
|
|
7
|
+
declare function __host_fetch(id: number, request: string): void;
|
|
8
|
+
|
|
9
|
+
interface WireResponse {
|
|
10
|
+
status: number;
|
|
11
|
+
statusText: string;
|
|
12
|
+
url: string;
|
|
13
|
+
redirected: boolean;
|
|
14
|
+
headers: [string, string][];
|
|
15
|
+
body: string;
|
|
16
|
+
bodyBase64: boolean;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
type Outcome = { ok: true; response: WireResponse } | { ok: false; code: string; message: string };
|
|
20
|
+
|
|
21
|
+
type HeadersInit = Record<string, string> | [string, string][] | HostedHeaders;
|
|
22
|
+
|
|
23
|
+
/** Case-insensitive header names, as in browsers and Node. */
|
|
24
|
+
export class HostedHeaders {
|
|
25
|
+
private readonly map = new Map<string, string[]>();
|
|
26
|
+
|
|
27
|
+
constructor(init?: HeadersInit) {
|
|
28
|
+
if (!init) return;
|
|
29
|
+
if (init instanceof HostedHeaders) init.forEach((value, name) => this.append(name, value));
|
|
30
|
+
else if (Array.isArray(init)) for (const [name, value] of init) this.append(name, value);
|
|
31
|
+
else for (const name of Object.keys(init)) this.append(name, init[name]);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
append(name: string, value: string): void {
|
|
35
|
+
const key = String(name).toLowerCase();
|
|
36
|
+
const list = this.map.get(key);
|
|
37
|
+
if (list) list.push(String(value));
|
|
38
|
+
else this.map.set(key, [String(value)]);
|
|
39
|
+
}
|
|
40
|
+
set(name: string, value: string): void {
|
|
41
|
+
this.map.set(String(name).toLowerCase(), [String(value)]);
|
|
42
|
+
}
|
|
43
|
+
get(name: string): string | null {
|
|
44
|
+
return this.map.get(String(name).toLowerCase())?.join(", ") ?? null;
|
|
45
|
+
}
|
|
46
|
+
has(name: string): boolean {
|
|
47
|
+
return this.map.has(String(name).toLowerCase());
|
|
48
|
+
}
|
|
49
|
+
delete(name: string): void {
|
|
50
|
+
this.map.delete(String(name).toLowerCase());
|
|
51
|
+
}
|
|
52
|
+
forEach(callback: (value: string, name: string) => void): void {
|
|
53
|
+
for (const [name, values] of this.map) callback(values.join(", "), name);
|
|
54
|
+
}
|
|
55
|
+
*entries(): IterableIterator<[string, string]> {
|
|
56
|
+
for (const [name, values] of this.map) yield [name, values.join(", ")];
|
|
57
|
+
}
|
|
58
|
+
keys(): IterableIterator<string> {
|
|
59
|
+
return this.map.keys();
|
|
60
|
+
}
|
|
61
|
+
*values(): IterableIterator<string> {
|
|
62
|
+
for (const values of this.map.values()) yield values.join(", ");
|
|
63
|
+
}
|
|
64
|
+
[Symbol.iterator](): IterableIterator<[string, string]> {
|
|
65
|
+
return this.entries();
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The parts of a Response plugins use: status, headers and the body as text, JSON or bytes (once). */
|
|
70
|
+
export class HostedResponse {
|
|
71
|
+
readonly status: number;
|
|
72
|
+
readonly statusText: string;
|
|
73
|
+
readonly ok: boolean;
|
|
74
|
+
readonly url: string;
|
|
75
|
+
readonly redirected: boolean;
|
|
76
|
+
readonly headers: HostedHeaders;
|
|
77
|
+
readonly type = "basic";
|
|
78
|
+
private used = false;
|
|
79
|
+
|
|
80
|
+
constructor(private readonly wire: WireResponse) {
|
|
81
|
+
this.status = wire.status;
|
|
82
|
+
this.statusText = wire.statusText;
|
|
83
|
+
this.ok = wire.status >= 200 && wire.status < 300;
|
|
84
|
+
this.url = wire.url;
|
|
85
|
+
this.redirected = wire.redirected;
|
|
86
|
+
this.headers = new HostedHeaders(wire.headers);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
get bodyUsed(): boolean {
|
|
90
|
+
return this.used;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
private take(): WireResponse {
|
|
94
|
+
if (this.used) throw new TypeError("The response body was already read");
|
|
95
|
+
this.used = true;
|
|
96
|
+
return this.wire;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async text(): Promise<string> {
|
|
100
|
+
const w = this.take();
|
|
101
|
+
return w.bodyBase64 ? utf8Decode(base64Decode(w.body)) : w.body;
|
|
102
|
+
}
|
|
103
|
+
async json(): Promise<unknown> {
|
|
104
|
+
return JSON.parse(await this.text());
|
|
105
|
+
}
|
|
106
|
+
async bytes(): Promise<Uint8Array> {
|
|
107
|
+
const w = this.take();
|
|
108
|
+
return w.bodyBase64 ? base64Decode(w.body) : utf8Encode(w.body);
|
|
109
|
+
}
|
|
110
|
+
async arrayBuffer(): Promise<ArrayBuffer> {
|
|
111
|
+
const b = await this.bytes();
|
|
112
|
+
return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer;
|
|
113
|
+
}
|
|
114
|
+
clone(): HostedResponse {
|
|
115
|
+
if (this.used) throw new TypeError("The response body was already read");
|
|
116
|
+
return new HostedResponse(this.wire);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
interface FetchInit {
|
|
121
|
+
method?: string;
|
|
122
|
+
headers?: HeadersInit;
|
|
123
|
+
body?: string | Uint8Array | ArrayBuffer | null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Installs fetch, Headers and Response; returns what the runner calls with each outcome. */
|
|
127
|
+
export function installFetch(g: Record<string, unknown>): (id: number, outcome: string) => void {
|
|
128
|
+
const pending = new Map<number, { resolve(r: HostedResponse): void; reject(e: Error): void }>();
|
|
129
|
+
let next = 1;
|
|
130
|
+
|
|
131
|
+
g.Headers ??= HostedHeaders;
|
|
132
|
+
g.Response ??= HostedResponse;
|
|
133
|
+
g.fetch = (input: string | { href?: string; url?: string; method?: string; headers?: HeadersInit }, init: FetchInit = {}): Promise<HostedResponse> => {
|
|
134
|
+
const url = typeof input === "string" ? input : (input?.href ?? input?.url ?? String(input));
|
|
135
|
+
const method = (init.method ?? (typeof input === "object" ? input?.method : undefined) ?? "GET").toUpperCase();
|
|
136
|
+
const headers: [string, string][] = [...new HostedHeaders(init.headers ?? (typeof input === "object" ? input?.headers : undefined))];
|
|
137
|
+
let body: string | null = null;
|
|
138
|
+
let bodyBase64 = false;
|
|
139
|
+
if (init.body !== undefined && init.body !== null) {
|
|
140
|
+
if (typeof init.body === "string") body = init.body;
|
|
141
|
+
else if (init.body instanceof Uint8Array) [body, bodyBase64] = [base64Encode(init.body), true];
|
|
142
|
+
else if (init.body instanceof ArrayBuffer) [body, bodyBase64] = [base64Encode(new Uint8Array(init.body)), true];
|
|
143
|
+
else return Promise.reject(new TypeError("fetch: the body must be a string (e.g. JSON.stringify(...)) or bytes"));
|
|
144
|
+
}
|
|
145
|
+
const id = next++;
|
|
146
|
+
return new Promise((resolve, reject) => {
|
|
147
|
+
pending.set(id, { resolve, reject });
|
|
148
|
+
__host_fetch(id, JSON.stringify({ url, method, headers, body, bodyBase64 }));
|
|
149
|
+
});
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
return (id, text) => {
|
|
153
|
+
const p = pending.get(id);
|
|
154
|
+
if (!p) return;
|
|
155
|
+
pending.delete(id);
|
|
156
|
+
const outcome = JSON.parse(text) as Outcome;
|
|
157
|
+
if (outcome.ok) p.resolve(new HostedResponse(outcome.response));
|
|
158
|
+
else if (outcome.code === "NetworkDenied") p.reject(new PluginError("NetworkDenied", outcome.message));
|
|
159
|
+
else p.reject(new TypeError(outcome.message));
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// ---- bytes, without TextEncoder or atob (QuickJS has neither) ----
|
|
164
|
+
|
|
165
|
+
const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
166
|
+
|
|
167
|
+
export function base64Encode(bytes: Uint8Array): string {
|
|
168
|
+
let out = "";
|
|
169
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
170
|
+
const n = (bytes[i] << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0);
|
|
171
|
+
out += B64[(n >> 18) & 63] + B64[(n >> 12) & 63] + (i + 1 < bytes.length ? B64[(n >> 6) & 63] : "=") + (i + 2 < bytes.length ? B64[n & 63] : "=");
|
|
172
|
+
}
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export function base64Decode(text: string): Uint8Array {
|
|
177
|
+
const clean = text.replace(/[^A-Za-z0-9+/]/g, "");
|
|
178
|
+
const out = new Uint8Array(Math.floor((clean.length * 3) / 4));
|
|
179
|
+
let o = 0;
|
|
180
|
+
for (let i = 0; i < clean.length; i += 4) {
|
|
181
|
+
const n = (B64.indexOf(clean[i]) << 18) | (B64.indexOf(clean[i + 1]) << 12) | ((B64.indexOf(clean[i + 2] ?? "A") & 63) << 6) | (B64.indexOf(clean[i + 3] ?? "A") & 63);
|
|
182
|
+
out[o++] = (n >> 16) & 255;
|
|
183
|
+
if (i + 2 < clean.length) out[o++] = (n >> 8) & 255;
|
|
184
|
+
if (i + 3 < clean.length) out[o++] = n & 255;
|
|
185
|
+
}
|
|
186
|
+
return out.subarray(0, o);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function utf8Encode(text: string): Uint8Array {
|
|
190
|
+
const out: number[] = [];
|
|
191
|
+
for (const ch of text) {
|
|
192
|
+
const c = ch.codePointAt(0)!;
|
|
193
|
+
if (c < 0x80) out.push(c);
|
|
194
|
+
else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 63));
|
|
195
|
+
else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
|
|
196
|
+
else out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
|
|
197
|
+
}
|
|
198
|
+
return new Uint8Array(out);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** UTF-8 to text; malformed sequences become U+FFFD. */
|
|
202
|
+
export function utf8Decode(bytes: Uint8Array): string {
|
|
203
|
+
let out = "";
|
|
204
|
+
let i = 0;
|
|
205
|
+
while (i < bytes.length) {
|
|
206
|
+
const b = bytes[i];
|
|
207
|
+
const need = b < 0x80 ? 0 : (b & 0xe0) === 0xc0 ? 1 : (b & 0xf0) === 0xe0 ? 2 : (b & 0xf8) === 0xf0 ? 3 : -1;
|
|
208
|
+
let c = need <= 0 ? b : b & (0xff >> (need + 2));
|
|
209
|
+
let ok = need >= 0 && i + need < bytes.length;
|
|
210
|
+
for (let k = 1; ok && k <= need; k++) {
|
|
211
|
+
const n = bytes[i + k];
|
|
212
|
+
if ((n & 0xc0) !== 0x80) ok = false;
|
|
213
|
+
else c = (c << 6) | (n & 63);
|
|
214
|
+
}
|
|
215
|
+
if (!ok || c > 0x10ffff) {
|
|
216
|
+
out += "\uFFFD";
|
|
217
|
+
i++;
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
out += String.fromCodePoint(c);
|
|
221
|
+
i += need + 1;
|
|
222
|
+
}
|
|
223
|
+
return out;
|
|
224
|
+
}
|