wildcrane-artifact-sdk 0.0.0-stage → 0.1.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/README.md +79 -2
- package/bin/artifact-sdk.mjs +56 -0
- package/bin/pack.mjs +70 -0
- package/dist/index.d.ts +39 -0
- package/dist/index.js +73 -0
- package/package.json +29 -4
- package/src/index.ts +112 -0
package/README.md
CHANGED
|
@@ -1,3 +1,80 @@
|
|
|
1
|
-
#
|
|
1
|
+
# wildcrane-artifact-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Write your own preview for your own artifact type — a subtitle editor, a slide viewer — and
|
|
4
|
+
publish it to your WildCrane account. When an agent submits an artifact of that type, the review
|
|
5
|
+
page draws it with your component.
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
review.wildcrane.ai ──postMessage──▶ <hash>.wildcraneusercontent.com (your bundle)
|
|
9
|
+
holds the sign-in, sandboxed iframe, no network,
|
|
10
|
+
validates and saves sees only the artifact it is handed
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
- **Yours alone**: a component draws artifacts only on tasks your account started.
|
|
14
|
+
- **No network**: `connect-src 'none'`, so not even `fetch` of your own files; bundle every script, style, font and image, and import data instead of fetching it.
|
|
15
|
+
- **Saving**: only the account's owners get `readOnly: false`. A save becomes the artifact's
|
|
16
|
+
next version and puts the checkpoint back up for review. Approving stays on the review page.
|
|
17
|
+
- **Pinned**: an artifact version keeps the component version that was newest when it was
|
|
18
|
+
written; publishing later changes nothing already submitted.
|
|
19
|
+
|
|
20
|
+
## A component
|
|
21
|
+
|
|
22
|
+
A folder of static files with `index.html` at its top, at most 10 MB, any framework, and
|
|
23
|
+
`wildcrane.component.json`:
|
|
24
|
+
|
|
25
|
+
```json
|
|
26
|
+
{
|
|
27
|
+
"name": "subtitles",
|
|
28
|
+
"version": "1.0.0",
|
|
29
|
+
"title": { "en": "Subtitle editor", "zh": "字幕编辑器" },
|
|
30
|
+
"types": ["@your-handle/subtitles"],
|
|
31
|
+
"schema": { "type": "array" }
|
|
32
|
+
}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
- **`name`**: unique in your account; not a built-in type (`html`, `image`, `video`,
|
|
36
|
+
`markdown`, `storyboard`, `compare`).
|
|
37
|
+
- **`version`**: semver, published once.
|
|
38
|
+
- **`types`**: the artifact types it draws, each `@<your GitHub handle>/<name>`, lowercase.
|
|
39
|
+
- **`schema`**: optional JSON Schema every save must match. The review page checks `type`,
|
|
40
|
+
`enum`, `const`, `properties`, `required`, `additionalProperties`, `items`, `minItems`,
|
|
41
|
+
`maxItems`, `minLength`, `maxLength`, `pattern`, `minimum` and `maximum`. A save is at most 256 KB.
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
npm install wildcrane-artifact-sdk
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
```js
|
|
48
|
+
import { connect } from "wildcrane-artifact-sdk";
|
|
49
|
+
|
|
50
|
+
const bridge = await connect();
|
|
51
|
+
// bridge.artifact: { type, name, version, content } or { …, file: { data: ArrayBuffer, contentType } }
|
|
52
|
+
// bridge.readOnly, bridge.locale ("zh" | "en"), bridge.theme ("light" | "dark")
|
|
53
|
+
await bridge.save(next); // rejects with the reason, in bridge.locale
|
|
54
|
+
bridge.onChange((ctx) => redraw(ctx));
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The frame follows your document's height (`connect({ autoResize: false })` and
|
|
58
|
+
`bridge.resize(px)` to do it yourself), up to twice the window's height.
|
|
59
|
+
|
|
60
|
+
## Publish
|
|
61
|
+
|
|
62
|
+
```sh
|
|
63
|
+
WILDCRANE_API_KEY=wck_… npx wildcrane-artifact-sdk publish dist
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Every file in the folder but dot files goes into the bundle. With Vite, put the manifest in
|
|
67
|
+
`public/` and publish `dist`. Then submit an artifact of your type:
|
|
68
|
+
`POST /v1/tasks/{id}/artifacts { "type": "@your-handle/subtitles", "checkpoint": "…" }`.
|
|
69
|
+
`GET /v1/components` lists what you published; `DELETE
|
|
70
|
+
/v1/components/{name}/versions/{version}` removes a version, and artifacts pinned to it show that
|
|
71
|
+
their preview cannot be drawn.
|
|
72
|
+
|
|
73
|
+
## The example
|
|
74
|
+
|
|
75
|
+
`examples/subtitles` edits a JSON list of `{ start, end, text }`. Set your handle in its
|
|
76
|
+
manifest, then `npm run example`.
|
|
77
|
+
|
|
78
|
+
## Develop
|
|
79
|
+
|
|
80
|
+
`npm install`, then `npm run lint`.
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// npx wildcrane-artifact-sdk publish [dir]
|
|
3
|
+
//
|
|
4
|
+
// Reads `wildcrane.component.json` in dir, packs every other file into a gzipped tar and
|
|
5
|
+
// publishes it as that version, with WILDCRANE_API_KEY.
|
|
6
|
+
|
|
7
|
+
import { readFileSync } from 'node:fs'
|
|
8
|
+
import { join, resolve } from 'node:path'
|
|
9
|
+
import { gzipSync } from 'node:zlib'
|
|
10
|
+
|
|
11
|
+
import { MANIFEST, filesOf, tarOf } from './pack.mjs'
|
|
12
|
+
|
|
13
|
+
const API = (process.env.WILDCRANE_API_URL || 'https://api.ai4kanban.dev').replace(/\/+$/, '')
|
|
14
|
+
|
|
15
|
+
/** @param {string} path @param {{ method: string, headers: Record<string, string>, body: BodyInit }} init */
|
|
16
|
+
async function api(path, init) {
|
|
17
|
+
const r = await fetch(`${API}${path}`, {
|
|
18
|
+
...init,
|
|
19
|
+
headers: { authorization: `Bearer ${process.env.WILDCRANE_API_KEY}`, ...init.headers },
|
|
20
|
+
})
|
|
21
|
+
const body = await r.json().catch(() => null)
|
|
22
|
+
if (!r.ok) throw new Error(body?.error?.message ?? `${r.status} ${r.statusText}`)
|
|
23
|
+
return body
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param {string} dir */
|
|
27
|
+
async function publish(dir) {
|
|
28
|
+
if (!process.env.WILDCRANE_API_KEY) throw new Error('Set WILDCRANE_API_KEY to an API key of your account.')
|
|
29
|
+
let manifest
|
|
30
|
+
try {
|
|
31
|
+
manifest = JSON.parse(readFileSync(join(dir, MANIFEST), 'utf8'))
|
|
32
|
+
} catch (e) {
|
|
33
|
+
throw new Error(`Cannot read ${join(dir, MANIFEST)}: ${e instanceof Error ? e.message : e}`)
|
|
34
|
+
}
|
|
35
|
+
const paths = filesOf(dir)
|
|
36
|
+
if (!paths.includes('index.html')) throw new Error(`${dir} has no index.html.`)
|
|
37
|
+
const bundle = gzipSync(tarOf(paths.map((p) => [p, readFileSync(join(dir, p))])))
|
|
38
|
+
const { name, version, ...rest } = manifest
|
|
39
|
+
const made = await api('/v1/components', {
|
|
40
|
+
method: 'POST',
|
|
41
|
+
headers: { 'content-type': 'application/json' },
|
|
42
|
+
body: JSON.stringify({ name, version, manifest: rest }),
|
|
43
|
+
})
|
|
44
|
+
await api(made.upload.url, { method: 'PUT', headers: { 'content-type': 'application/gzip' }, body: bundle })
|
|
45
|
+
console.log(`Published ${name}@${version} (${paths.length} files) — draws ${made.types.join(', ')}.`)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const [command, dir = '.'] = process.argv.slice(2)
|
|
49
|
+
if (command !== 'publish') {
|
|
50
|
+
console.log('Usage: npx wildcrane-artifact-sdk publish [dir]')
|
|
51
|
+
process.exit(command ? 1 : 0)
|
|
52
|
+
}
|
|
53
|
+
publish(resolve(dir)).catch((e) => {
|
|
54
|
+
console.error(`publish: ${e.message}`)
|
|
55
|
+
process.exit(1)
|
|
56
|
+
})
|
package/bin/pack.mjs
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// The bundle `publish` sends: a ustar archive of the component's folder.
|
|
2
|
+
|
|
3
|
+
import { readdirSync, statSync } from 'node:fs'
|
|
4
|
+
import { join, relative, sep } from 'node:path'
|
|
5
|
+
|
|
6
|
+
export const MANIFEST = 'wildcrane.component.json'
|
|
7
|
+
|
|
8
|
+
/** Every file under dir but the manifest, dot files and node_modules, by its `/` path. */
|
|
9
|
+
/** @param {string} dir @returns {string[]} */
|
|
10
|
+
export function filesOf(dir) {
|
|
11
|
+
/** @type {string[]} */
|
|
12
|
+
const out = []
|
|
13
|
+
/** @param {string} at */
|
|
14
|
+
const walk = (at) => {
|
|
15
|
+
for (const name of readdirSync(at).sort()) {
|
|
16
|
+
if (name.startsWith('.') || name === 'node_modules') continue
|
|
17
|
+
const path = join(at, name)
|
|
18
|
+
if (statSync(path).isDirectory()) walk(path)
|
|
19
|
+
else out.push(relative(dir, path).split(sep).join('/'))
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
walk(dir)
|
|
23
|
+
return out.filter((p) => p !== MANIFEST)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A ustar archive; a path past 100 bytes travels in a pax header. */
|
|
27
|
+
/** @param {[string, Uint8Array][]} files */
|
|
28
|
+
export function tarOf(files) {
|
|
29
|
+
/** @type {Uint8Array[]} */
|
|
30
|
+
const blocks = []
|
|
31
|
+
const enc = new TextEncoder()
|
|
32
|
+
/** @param {string} name @param {number} size @param {string} kind */
|
|
33
|
+
const header = (name, size, kind) => {
|
|
34
|
+
const h = new Uint8Array(512)
|
|
35
|
+
/** @param {string} text @param {number} at */
|
|
36
|
+
const put = (text, at) => h.set(enc.encode(text), at)
|
|
37
|
+
put(name.slice(0, 100), 0)
|
|
38
|
+
put('0000644\0', 100)
|
|
39
|
+
put('0000000\0', 108)
|
|
40
|
+
put('0000000\0', 116)
|
|
41
|
+
put(size.toString(8).padStart(11, '0') + '\0', 124)
|
|
42
|
+
put('00000000000\0', 136)
|
|
43
|
+
put(' ', 148)
|
|
44
|
+
put(kind, 156)
|
|
45
|
+
put('ustar\x0000', 257)
|
|
46
|
+
const sum = h.reduce((n, b) => n + b, 0)
|
|
47
|
+
put(sum.toString(8).padStart(6, '0') + '\0 ', 148)
|
|
48
|
+
return h
|
|
49
|
+
}
|
|
50
|
+
/** @param {string} name @param {Uint8Array} body */
|
|
51
|
+
const entry = (name, body, kind = '0') =>
|
|
52
|
+
blocks.push(header(name, body.length, kind), body, new Uint8Array((512 - (body.length % 512)) % 512))
|
|
53
|
+
for (const [name, body] of files) {
|
|
54
|
+
if (enc.encode(name).length > 100) {
|
|
55
|
+
const record = ` path=${name}\n`
|
|
56
|
+
let n = enc.encode(record).length
|
|
57
|
+
n += String(n + String(n).length).length
|
|
58
|
+
entry('PaxHeader', enc.encode(`${n}${record}`), 'x')
|
|
59
|
+
}
|
|
60
|
+
entry(name, body)
|
|
61
|
+
}
|
|
62
|
+
blocks.push(new Uint8Array(1024))
|
|
63
|
+
const out = new Uint8Array(blocks.reduce((n, b) => n + b.length, 0))
|
|
64
|
+
let at = 0
|
|
65
|
+
for (const b of blocks) {
|
|
66
|
+
out.set(b, at)
|
|
67
|
+
at += b.length
|
|
68
|
+
}
|
|
69
|
+
return out
|
|
70
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export type Locale = "zh" | "en";
|
|
2
|
+
export type Theme = "light" | "dark";
|
|
3
|
+
/** The artifact version under review: inline JSON, or a file's bytes. */
|
|
4
|
+
export interface Artifact {
|
|
5
|
+
type: string;
|
|
6
|
+
name: string;
|
|
7
|
+
version: number;
|
|
8
|
+
content?: unknown;
|
|
9
|
+
file?: {
|
|
10
|
+
data: ArrayBuffer;
|
|
11
|
+
contentType: string;
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
export interface Context {
|
|
15
|
+
artifact: Artifact;
|
|
16
|
+
/** True for anyone who may not save: send changes back with a comment instead. */
|
|
17
|
+
readOnly: boolean;
|
|
18
|
+
locale: Locale;
|
|
19
|
+
theme: Theme;
|
|
20
|
+
}
|
|
21
|
+
export interface Connection extends Context {
|
|
22
|
+
/** Save `content` as the artifact's next version. Rejects with the reason, in `locale`. */
|
|
23
|
+
save(content: unknown): Promise<{
|
|
24
|
+
version: number;
|
|
25
|
+
}>;
|
|
26
|
+
/** Ask for this height, in CSS pixels. Done for you unless `autoResize` is false. */
|
|
27
|
+
resize(height: number): void;
|
|
28
|
+
/** Called when the page changes the theme, the language or the artifact. */
|
|
29
|
+
onChange(listener: (context: Context) => void): () => void;
|
|
30
|
+
}
|
|
31
|
+
export interface ConnectOptions {
|
|
32
|
+
/** Follow the document's height. Default true. */
|
|
33
|
+
autoResize?: boolean;
|
|
34
|
+
/** How long to wait for the review page, in ms. Default 10000. */
|
|
35
|
+
timeout?: number;
|
|
36
|
+
}
|
|
37
|
+
export declare class SaveError extends Error {
|
|
38
|
+
}
|
|
39
|
+
export declare function connect(options?: ConnectOptions): Promise<Connection>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// The component's half of the Bridge: JSON-RPC 2.0 over postMessage, with message names
|
|
2
|
+
// taken from MCP Apps (`ui/initialize`, `ui/notifications/size-changed`,
|
|
3
|
+
// `ui/notifications/host-context-changed`) plus `wildcrane/save`. The review page is the only
|
|
4
|
+
// frame allowed to embed a component, so the parent is the only peer listened to.
|
|
5
|
+
export class SaveError extends Error {
|
|
6
|
+
}
|
|
7
|
+
export function connect(options = {}) {
|
|
8
|
+
const parent = window.parent;
|
|
9
|
+
if (parent === window)
|
|
10
|
+
return Promise.reject(new Error("Not inside the WildCrane review page."));
|
|
11
|
+
let origin = "*";
|
|
12
|
+
let next = 1;
|
|
13
|
+
const waiting = new Map();
|
|
14
|
+
const listeners = new Set();
|
|
15
|
+
let context;
|
|
16
|
+
const post = (message) => parent.postMessage({ jsonrpc: "2.0", ...message }, origin);
|
|
17
|
+
const request = (method, params) => new Promise((resolve, reject) => {
|
|
18
|
+
const id = next++;
|
|
19
|
+
waiting.set(id, { resolve, reject });
|
|
20
|
+
post({ id, method, params });
|
|
21
|
+
});
|
|
22
|
+
window.addEventListener("message", (event) => {
|
|
23
|
+
if (event.source !== parent)
|
|
24
|
+
return;
|
|
25
|
+
const m = event.data;
|
|
26
|
+
if (!m || m.jsonrpc !== "2.0")
|
|
27
|
+
return;
|
|
28
|
+
if (m.id !== undefined && waiting.has(m.id)) {
|
|
29
|
+
if (origin === "*")
|
|
30
|
+
origin = event.origin;
|
|
31
|
+
const w = waiting.get(m.id);
|
|
32
|
+
waiting.delete(m.id);
|
|
33
|
+
if (m.error)
|
|
34
|
+
w.reject(new SaveError(m.error.message));
|
|
35
|
+
else
|
|
36
|
+
w.resolve(m.result);
|
|
37
|
+
}
|
|
38
|
+
else if (m.method === "ui/notifications/host-context-changed" && origin === event.origin) {
|
|
39
|
+
context = { ...context, ...m.params };
|
|
40
|
+
for (const l of listeners)
|
|
41
|
+
l(context);
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
const resize = (height) => post({ method: "ui/notifications/size-changed", params: { height: Math.ceil(height) } });
|
|
45
|
+
const ready = request("ui/initialize", { protocolVersion: 1 }).then((initial) => {
|
|
46
|
+
context = initial;
|
|
47
|
+
if (options.autoResize !== false) {
|
|
48
|
+
// The content's own height: `scrollHeight` never drops below the frame's.
|
|
49
|
+
const measure = () => resize(document.documentElement.getBoundingClientRect().height);
|
|
50
|
+
const watch = new ResizeObserver(measure);
|
|
51
|
+
watch.observe(document.documentElement);
|
|
52
|
+
watch.observe(document.body);
|
|
53
|
+
measure();
|
|
54
|
+
}
|
|
55
|
+
const connection = {
|
|
56
|
+
get artifact() { return context.artifact; },
|
|
57
|
+
get readOnly() { return context.readOnly; },
|
|
58
|
+
get locale() { return context.locale; },
|
|
59
|
+
get theme() { return context.theme; },
|
|
60
|
+
save: (content) => context.readOnly
|
|
61
|
+
? Promise.reject(new SaveError(context.locale === "zh" ? "你没有保存权限。" : "You can't save changes here."))
|
|
62
|
+
: request("wildcrane/save", { content }),
|
|
63
|
+
resize,
|
|
64
|
+
onChange: (listener) => {
|
|
65
|
+
listeners.add(listener);
|
|
66
|
+
return () => listeners.delete(listener);
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
return connection;
|
|
70
|
+
});
|
|
71
|
+
const timeout = new Promise((_, reject) => setTimeout(() => reject(new Error("The review page did not answer.")), options.timeout ?? 10_000));
|
|
72
|
+
return Promise.race([ready, timeout]);
|
|
73
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,31 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "wildcrane-artifact-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Write your own WildCrane review preview for your own artifact types, and publish it.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"homepage": "https://wildcrane.ai/",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/ai4kanban/ai4kanban.git",
|
|
10
|
+
"directory": "artifact-sdk"
|
|
11
|
+
},
|
|
12
|
+
"type": "module",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" }
|
|
15
|
+
},
|
|
16
|
+
"bin": { "artifact-sdk": "bin/artifact-sdk.mjs" },
|
|
17
|
+
"files": ["dist", "bin", "src", "README.md"],
|
|
18
|
+
"engines": { "node": ">=20" },
|
|
19
|
+
"publishConfig": { "access": "public", "provenance": true },
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "tsc -p .",
|
|
22
|
+
"typecheck": "tsc -p . --noEmit && tsc -p tsconfig.bin.json && tsc -p tsconfig.example.json",
|
|
23
|
+
"lint": "npm run typecheck",
|
|
24
|
+
"example": "npm run build && cp dist/index.js examples/subtitles/sdk.js && node bin/artifact-sdk.mjs publish examples/subtitles",
|
|
25
|
+
"prepack": "npm run build"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@types/node": "^24.0.0",
|
|
29
|
+
"typescript": "^5.9.3"
|
|
30
|
+
}
|
|
31
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// The component's half of the Bridge: JSON-RPC 2.0 over postMessage, with message names
|
|
2
|
+
// taken from MCP Apps (`ui/initialize`, `ui/notifications/size-changed`,
|
|
3
|
+
// `ui/notifications/host-context-changed`) plus `wildcrane/save`. The review page is the only
|
|
4
|
+
// frame allowed to embed a component, so the parent is the only peer listened to.
|
|
5
|
+
|
|
6
|
+
export type Locale = "zh" | "en";
|
|
7
|
+
export type Theme = "light" | "dark";
|
|
8
|
+
|
|
9
|
+
/** The artifact version under review: inline JSON, or a file's bytes. */
|
|
10
|
+
export interface Artifact {
|
|
11
|
+
type: string;
|
|
12
|
+
name: string;
|
|
13
|
+
version: number;
|
|
14
|
+
content?: unknown;
|
|
15
|
+
file?: { data: ArrayBuffer; contentType: string };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface Context {
|
|
19
|
+
artifact: Artifact;
|
|
20
|
+
/** True for anyone who may not save: send changes back with a comment instead. */
|
|
21
|
+
readOnly: boolean;
|
|
22
|
+
locale: Locale;
|
|
23
|
+
theme: Theme;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface Connection extends Context {
|
|
27
|
+
/** Save `content` as the artifact's next version. Rejects with the reason, in `locale`. */
|
|
28
|
+
save(content: unknown): Promise<{ version: number }>;
|
|
29
|
+
/** Ask for this height, in CSS pixels. Done for you unless `autoResize` is false. */
|
|
30
|
+
resize(height: number): void;
|
|
31
|
+
/** Called when the page changes the theme, the language or the artifact. */
|
|
32
|
+
onChange(listener: (context: Context) => void): () => void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface ConnectOptions {
|
|
36
|
+
/** Follow the document's height. Default true. */
|
|
37
|
+
autoResize?: boolean;
|
|
38
|
+
/** How long to wait for the review page, in ms. Default 10000. */
|
|
39
|
+
timeout?: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
type Message = { jsonrpc: "2.0"; id?: number; method?: string; params?: any; result?: any; error?: { message: string } };
|
|
43
|
+
|
|
44
|
+
export class SaveError extends Error {}
|
|
45
|
+
|
|
46
|
+
export function connect(options: ConnectOptions = {}): Promise<Connection> {
|
|
47
|
+
const parent = window.parent;
|
|
48
|
+
if (parent === window) return Promise.reject(new Error("Not inside the WildCrane review page."));
|
|
49
|
+
let origin = "*";
|
|
50
|
+
let next = 1;
|
|
51
|
+
const waiting = new Map<number, { resolve: (v: any) => void; reject: (e: Error) => void }>();
|
|
52
|
+
const listeners = new Set<(c: Context) => void>();
|
|
53
|
+
let context: Context;
|
|
54
|
+
|
|
55
|
+
const post = (message: Omit<Message, "jsonrpc">) => parent.postMessage({ jsonrpc: "2.0", ...message }, origin);
|
|
56
|
+
const request = (method: string, params?: unknown) =>
|
|
57
|
+
new Promise<any>((resolve, reject) => {
|
|
58
|
+
const id = next++;
|
|
59
|
+
waiting.set(id, { resolve, reject });
|
|
60
|
+
post({ id, method, params });
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
window.addEventListener("message", (event) => {
|
|
64
|
+
if (event.source !== parent) return;
|
|
65
|
+
const m = event.data as Message;
|
|
66
|
+
if (!m || m.jsonrpc !== "2.0") return;
|
|
67
|
+
if (m.id !== undefined && waiting.has(m.id)) {
|
|
68
|
+
if (origin === "*") origin = event.origin;
|
|
69
|
+
const w = waiting.get(m.id)!;
|
|
70
|
+
waiting.delete(m.id);
|
|
71
|
+
if (m.error) w.reject(new SaveError(m.error.message));
|
|
72
|
+
else w.resolve(m.result);
|
|
73
|
+
} else if (m.method === "ui/notifications/host-context-changed" && origin === event.origin) {
|
|
74
|
+
context = { ...context, ...m.params };
|
|
75
|
+
for (const l of listeners) l(context);
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
const resize = (height: number) => post({ method: "ui/notifications/size-changed", params: { height: Math.ceil(height) } });
|
|
80
|
+
|
|
81
|
+
const ready = request("ui/initialize", { protocolVersion: 1 }).then((initial: Context): Connection => {
|
|
82
|
+
context = initial;
|
|
83
|
+
if (options.autoResize !== false) {
|
|
84
|
+
// The content's own height: `scrollHeight` never drops below the frame's.
|
|
85
|
+
const measure = () => resize(document.documentElement.getBoundingClientRect().height);
|
|
86
|
+
const watch = new ResizeObserver(measure);
|
|
87
|
+
watch.observe(document.documentElement);
|
|
88
|
+
watch.observe(document.body);
|
|
89
|
+
measure();
|
|
90
|
+
}
|
|
91
|
+
const connection: Connection = {
|
|
92
|
+
get artifact() { return context.artifact; },
|
|
93
|
+
get readOnly() { return context.readOnly; },
|
|
94
|
+
get locale() { return context.locale; },
|
|
95
|
+
get theme() { return context.theme; },
|
|
96
|
+
save: (content) =>
|
|
97
|
+
context.readOnly
|
|
98
|
+
? Promise.reject(new SaveError(context.locale === "zh" ? "你没有保存权限。" : "You can't save changes here."))
|
|
99
|
+
: request("wildcrane/save", { content }),
|
|
100
|
+
resize,
|
|
101
|
+
onChange: (listener) => {
|
|
102
|
+
listeners.add(listener);
|
|
103
|
+
return () => listeners.delete(listener);
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
return connection;
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
const timeout = new Promise<never>((_, reject) =>
|
|
110
|
+
setTimeout(() => reject(new Error("The review page did not answer.")), options.timeout ?? 10_000));
|
|
111
|
+
return Promise.race([ready, timeout]);
|
|
112
|
+
}
|