@open-artifact/server-sdk 0.0.0-stage → 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/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +5 -2
- package/bin/frame-host.d.ts +2 -0
- package/bin/frame-host.js +29 -0
- package/package.json +71 -4
- package/src/daemon.d.ts +65 -0
- package/src/daemon.js +157 -0
- package/src/frame/client/comments.css +1 -0
- package/src/frame/client/comments.js +57 -0
- package/src/frame/client/runtime.js +995 -0
- package/src/frame/client/shell.css +45 -0
- package/src/frame/client/shell.html +29 -0
- package/src/frame/client/shell.js +990 -0
- package/src/frame/comments.d.ts +87 -0
- package/src/frame/comments.js +228 -0
- package/src/frame/db.d.ts +149 -0
- package/src/frame/db.js +573 -0
- package/src/frame/declaration.d.ts +24 -0
- package/src/frame/declaration.js +65 -0
- package/src/frame/files.d.ts +107 -0
- package/src/frame/files.js +348 -0
- package/src/frame/index.d.ts +138 -0
- package/src/frame/index.js +1075 -0
- package/src/frame/wire.d.ts +184 -0
- package/src/frame/wire.js +21 -0
- package/src/index.d.ts +15 -0
- package/src/index.js +15 -0
- package/src/lan.d.ts +74 -0
- package/src/lan.js +201 -0
- package/src/serve.d.ts +362 -0
- package/src/serve.js +779 -0
- package/src/ws.d.ts +46 -0
- package/src/ws.js +182 -0
|
@@ -0,0 +1,995 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
(() => {
|
|
3
|
+
// packages/server-sdk/src/frame/client/runtime.ts
|
|
4
|
+
(() => {
|
|
5
|
+
"use strict";
|
|
6
|
+
const w = window;
|
|
7
|
+
if (w.openArtifact && w.openArtifact.__openArtifactFrame) return;
|
|
8
|
+
const boot = w.__OPEN_ARTIFACT_FRAME || {};
|
|
9
|
+
const SHELL = boot.shellOrigin || "";
|
|
10
|
+
const parentWin = window.parent;
|
|
11
|
+
const framed = !!SHELL && !!parentWin && parentWin !== window;
|
|
12
|
+
const INIT_TIMEOUT_MS = 1e4;
|
|
13
|
+
const WANT_TIMEOUT_MS = 1e4;
|
|
14
|
+
const ACKED_MS = 9e5;
|
|
15
|
+
const BUDGET_MAX_MS = 6e5;
|
|
16
|
+
const REWIRED_MESSAGE = "may not have run: the artifact was updated before this call was answered";
|
|
17
|
+
const grants = Array.isArray(boot.grants) ? boot.grants.slice() : [];
|
|
18
|
+
const stubs = Array.isArray(boot.stubs) ? boot.stubs.slice() : [];
|
|
19
|
+
const TIMEOUTS = {
|
|
20
|
+
downloads: [15e4, "unavailable", 0],
|
|
21
|
+
assets: [13e4, "upstream_error", ACKED_MS],
|
|
22
|
+
user: [2e4, null, 0],
|
|
23
|
+
artifact: [13e4, "upstream_error", 0],
|
|
24
|
+
comments: [13e4, "upstream_error", ACKED_MS],
|
|
25
|
+
permissions: [13e4, "upstream_error", ACKED_MS],
|
|
26
|
+
room: [13e4, "upstream_error", 0],
|
|
27
|
+
db: [13e4, "unavailable", 0]
|
|
28
|
+
};
|
|
29
|
+
const PREFIX = { downloads: "d", assets: "e", permissions: "p", user: "u", artifact: "s", room: "r", comments: "k", db: "b" };
|
|
30
|
+
const ACTIVATED = { "permissions.request": true, "room.sendToAgentSession": true };
|
|
31
|
+
let seq = 0;
|
|
32
|
+
const salt = new Uint32Array(1);
|
|
33
|
+
const pending = /* @__PURE__ */ new Map();
|
|
34
|
+
let init = null;
|
|
35
|
+
let initDone = false;
|
|
36
|
+
let initWaiters = [];
|
|
37
|
+
let brokerGen;
|
|
38
|
+
const configs = /* @__PURE__ */ Object.create(null);
|
|
39
|
+
function post(msg, activation = false) {
|
|
40
|
+
if (!framed) return;
|
|
41
|
+
try {
|
|
42
|
+
if (activation) parentWin.postMessage(msg, { targetOrigin: SHELL, includeUserActivation: true });
|
|
43
|
+
else parentWin.postMessage(msg, SHELL);
|
|
44
|
+
} catch {
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
function frameError(code, message, extra, name) {
|
|
48
|
+
const err = new Error(typeof message === "string" && message ? message : String(code || "error"));
|
|
49
|
+
err.name = name || "FrameError";
|
|
50
|
+
err.code = typeof code === "string" && code ? code : "upstream_error";
|
|
51
|
+
if (extra && typeof extra === "object") {
|
|
52
|
+
for (const k of Object.keys(extra)) if (k !== "message" && k !== "name" && k !== "stack") err[k] = extra[k];
|
|
53
|
+
}
|
|
54
|
+
return err;
|
|
55
|
+
}
|
|
56
|
+
function whenInit() {
|
|
57
|
+
if (initDone) return Promise.resolve(init);
|
|
58
|
+
return new Promise((resolve) => initWaiters.push(resolve));
|
|
59
|
+
}
|
|
60
|
+
function finishInit(value) {
|
|
61
|
+
if (initDone) return;
|
|
62
|
+
initDone = true;
|
|
63
|
+
init = value;
|
|
64
|
+
if (value) {
|
|
65
|
+
if (typeof value.brokerGen === "number") brokerGen = value.brokerGen;
|
|
66
|
+
const caps = value.capabilities || {};
|
|
67
|
+
for (const cap of Object.keys(caps)) configs[cap] = caps[cap] && caps[cap].config || {};
|
|
68
|
+
}
|
|
69
|
+
const list = initWaiters;
|
|
70
|
+
initWaiters = [];
|
|
71
|
+
for (const fn of list) fn(value);
|
|
72
|
+
}
|
|
73
|
+
function timeoutOf(cap, method) {
|
|
74
|
+
const t = TIMEOUTS[cap] || [13e4, "upstream_error", 0];
|
|
75
|
+
const budget = init && init.capBudgets && init.capBudgets[cap] ? init.capBudgets[cap][method] : void 0;
|
|
76
|
+
if (typeof budget === "number" && budget > 0) return [Math.min(budget, BUDGET_MAX_MS) + 2e3, t[1]];
|
|
77
|
+
return [t[0], t[1]];
|
|
78
|
+
}
|
|
79
|
+
function arm(id, p, ms, code) {
|
|
80
|
+
if (p.timer) clearTimeout(p.timer);
|
|
81
|
+
p.timer = setTimeout(() => {
|
|
82
|
+
if (!pending.delete(id)) return;
|
|
83
|
+
if (code === null) p.resolve(null);
|
|
84
|
+
else p.reject({ code, message: `${p.cap}.${p.method} did not answer in time.` });
|
|
85
|
+
}, ms);
|
|
86
|
+
}
|
|
87
|
+
function call(cap, method, arg, errorName, transfer) {
|
|
88
|
+
if (!framed) return Promise.reject(frameError("unavailable", "This page is not inside its frame shell.", null, errorName));
|
|
89
|
+
return new Promise((resolve, reject) => {
|
|
90
|
+
crypto.getRandomValues(salt);
|
|
91
|
+
const id = `${PREFIX[cap] || "x"}${salt[0].toString(36)}.${++seq}`;
|
|
92
|
+
const p = {
|
|
93
|
+
cap,
|
|
94
|
+
method,
|
|
95
|
+
resolve: (v) => {
|
|
96
|
+
if (p.timer) clearTimeout(p.timer);
|
|
97
|
+
resolve(v);
|
|
98
|
+
},
|
|
99
|
+
reject: (e) => {
|
|
100
|
+
if (p.timer) clearTimeout(p.timer);
|
|
101
|
+
if (boot.debug) post({ __open_artifact_console: true, level: "warn", text: `${cap}.${method} → ${e && e.code || "error"}: ${e && e.message || ""}` });
|
|
102
|
+
reject(frameError(e && e.code, e && e.message, e, errorName));
|
|
103
|
+
},
|
|
104
|
+
timer: null
|
|
105
|
+
};
|
|
106
|
+
pending.set(id, p);
|
|
107
|
+
const [ms, code] = timeoutOf(cap, method);
|
|
108
|
+
arm(id, p, ms, code);
|
|
109
|
+
const msg = { __frame_cap: true, cap, id, method, args: [arg] };
|
|
110
|
+
if (brokerGen !== void 0) msg.brokerGen = brokerGen;
|
|
111
|
+
if (cap === "assets") msg.holds = true;
|
|
112
|
+
const activation = cap === "comments" || ACTIVATED[`${cap}.${method}`] === true;
|
|
113
|
+
try {
|
|
114
|
+
if (transfer && transfer.length) parentWin.postMessage(msg, { targetOrigin: SHELL, transfer });
|
|
115
|
+
else if (activation) parentWin.postMessage(msg, { targetOrigin: SHELL, includeUserActivation: true });
|
|
116
|
+
else parentWin.postMessage(msg, SHELL);
|
|
117
|
+
} catch (e) {
|
|
118
|
+
pending.delete(id);
|
|
119
|
+
p.reject({ code: "invalid_argument", message: String(e?.message || e) });
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
const dbSubs = /* @__PURE__ */ new Map();
|
|
124
|
+
const roomHandlers = /* @__PURE__ */ new Map();
|
|
125
|
+
const peerHandlers = /* @__PURE__ */ new Set();
|
|
126
|
+
const connHandlers = /* @__PURE__ */ new Set();
|
|
127
|
+
const wants = /* @__PURE__ */ new Map();
|
|
128
|
+
let anchors = null;
|
|
129
|
+
let commentsMode = false;
|
|
130
|
+
window.addEventListener("message", (ev) => {
|
|
131
|
+
if (ev.source !== parentWin || ev.origin !== SHELL) return;
|
|
132
|
+
const d = ev.data;
|
|
133
|
+
if (!d || typeof d !== "object") return;
|
|
134
|
+
if (d.__frame_init && typeof d.__frame_init === "object") return finishInit(d.__frame_init);
|
|
135
|
+
if (d.__frame_cap_r === true) {
|
|
136
|
+
const p = pending.get(d.id);
|
|
137
|
+
if (!p) return;
|
|
138
|
+
pending.delete(d.id);
|
|
139
|
+
if (d.error != null) p.reject(d.error);
|
|
140
|
+
else p.resolve(d.result);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
if (d.__frame_cap_ack === true) {
|
|
144
|
+
const p = pending.get(d.id);
|
|
145
|
+
const t = p && TIMEOUTS[p.cap];
|
|
146
|
+
if (p && t && t[2]) arm(d.id, p, t[2], t[1]);
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
if (d.__frame_cap_rewired === true) return onRewired(d);
|
|
150
|
+
if (d.__frame_cap_grant === true) {
|
|
151
|
+
const fn = wants.get(d.cap);
|
|
152
|
+
if (fn) fn(d);
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
if (d.__frame_db_ev === true) {
|
|
156
|
+
const sub = dbSubs.get(d.sub);
|
|
157
|
+
if (sub) sub.deliver(d);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (d.__frame_room_ev === true) return onRoomEvent(d);
|
|
161
|
+
if (d.__open_artifact_comments === true) onCommentsEvent(d);
|
|
162
|
+
});
|
|
163
|
+
function onRewired(d) {
|
|
164
|
+
const changed = d.brokerGen !== void 0 && brokerGen !== void 0 && d.brokerGen !== brokerGen;
|
|
165
|
+
if (typeof d.brokerGen === "number") brokerGen = d.brokerGen;
|
|
166
|
+
const caps = Array.isArray(d.caps) ? d.caps : null;
|
|
167
|
+
const gone = (cap) => !!caps && caps.indexOf(cap) < 0 && !(cap === "artifact" && caps.indexOf("self") >= 0);
|
|
168
|
+
for (const [id, p] of [...pending]) {
|
|
169
|
+
if (gone(p.cap) && p.cap === "db") {
|
|
170
|
+
pending.delete(id);
|
|
171
|
+
p.reject({ code: "revoked", message: "The document store is no longer available to this artifact." });
|
|
172
|
+
} else if (changed) {
|
|
173
|
+
pending.delete(id);
|
|
174
|
+
if (p.cap === "user") p.resolve(null);
|
|
175
|
+
else p.reject({ code: p.cap === "db" || p.cap === "downloads" ? "unavailable" : "upstream_error", message: REWIRED_MESSAGE });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
if (gone("db")) for (const s of dbSubs.values()) s.revoke();
|
|
179
|
+
else if (changed) for (const s of dbSubs.values()) s.resubscribe();
|
|
180
|
+
if (gone("room")) {
|
|
181
|
+
connected = false;
|
|
182
|
+
for (const fn of connHandlers) safely(fn, false);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
function connect() {
|
|
186
|
+
if (!framed) return finishInit(null);
|
|
187
|
+
let tries = 0;
|
|
188
|
+
const tick = () => {
|
|
189
|
+
if (initDone) return;
|
|
190
|
+
post({ __frame_connect: true, contract: boot.contract, key: boot.key });
|
|
191
|
+
if (++tries * 400 < INIT_TIMEOUT_MS) setTimeout(tick, 400);
|
|
192
|
+
else finishInit(null);
|
|
193
|
+
};
|
|
194
|
+
tick();
|
|
195
|
+
}
|
|
196
|
+
function safely(fn, ...args) {
|
|
197
|
+
try {
|
|
198
|
+
fn(...args);
|
|
199
|
+
} catch (e) {
|
|
200
|
+
setTimeout(() => {
|
|
201
|
+
throw e;
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
const SEG = /^[A-Za-z0-9_\-.~:@+]+$/;
|
|
206
|
+
const enc = new TextEncoder();
|
|
207
|
+
function segsOf(path, kind) {
|
|
208
|
+
if (typeof path !== "string") throw new TypeError("A db path is a string.");
|
|
209
|
+
const t = path.replace(/^\/+|\/+$/g, "");
|
|
210
|
+
if (!t) throw new TypeError("An empty db path.");
|
|
211
|
+
if (enc.encode(t).length > 1e3) throw new TypeError("A db path is at most 1000 bytes.");
|
|
212
|
+
const segs = t.split("/");
|
|
213
|
+
if (segs.length > 16) throw new TypeError("A db path has at most 16 segments.");
|
|
214
|
+
for (const s of segs) {
|
|
215
|
+
if (!SEG.test(s) || s === "." || s === ".." || enc.encode(s).length > 200) throw new TypeError(`Bad db path segment ${JSON.stringify(s)}.`);
|
|
216
|
+
}
|
|
217
|
+
if (kind === "doc" && segs.length % 2 !== 0) throw new TypeError(`${t} names a collection, not a document.`);
|
|
218
|
+
if (kind === "collection" && segs.length % 2 !== 1) throw new TypeError(`${t} names a document, not a collection.`);
|
|
219
|
+
return segs;
|
|
220
|
+
}
|
|
221
|
+
const clone = (v) => v === void 0 ? void 0 : JSON.parse(JSON.stringify(v));
|
|
222
|
+
function fieldOf(data, field) {
|
|
223
|
+
let v = data;
|
|
224
|
+
for (const k of String(field).split(".")) v = v && typeof v === "object" ? v[k] : void 0;
|
|
225
|
+
return v;
|
|
226
|
+
}
|
|
227
|
+
const META = Object.freeze({ fromCache: false, hasPendingWrites: false });
|
|
228
|
+
function docSnap(ref, data) {
|
|
229
|
+
return {
|
|
230
|
+
id: ref.id,
|
|
231
|
+
ref,
|
|
232
|
+
exists: data !== void 0,
|
|
233
|
+
metadata: META,
|
|
234
|
+
data: () => clone(data),
|
|
235
|
+
get: (field) => clone(fieldOf(data, field))
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
const dbCall = (method, arg) => call("db", method, arg, "DbError");
|
|
239
|
+
function observer(next, error) {
|
|
240
|
+
if (next && typeof next === "object") return { next: (next.next || (() => {
|
|
241
|
+
})).bind(next), error: (next.error || (() => {
|
|
242
|
+
})).bind(next) };
|
|
243
|
+
return { next: next || (() => {
|
|
244
|
+
}), error: error || (() => {
|
|
245
|
+
}) };
|
|
246
|
+
}
|
|
247
|
+
function subscribe(kind, path, spec, onData, onError) {
|
|
248
|
+
if (dbSubs.size >= 64) throw frameError("resource_exhausted", "At most 64 db subscriptions.", null, "DbError");
|
|
249
|
+
const id = `sub${++seq}`;
|
|
250
|
+
let live = true;
|
|
251
|
+
const start = () => {
|
|
252
|
+
dbCall("subscribe", { sub: id, kind, path, spec }).catch((e) => {
|
|
253
|
+
if (live) onError(e);
|
|
254
|
+
});
|
|
255
|
+
};
|
|
256
|
+
dbSubs.set(id, {
|
|
257
|
+
deliver: (d) => {
|
|
258
|
+
if (!live) return;
|
|
259
|
+
if (d.error) onError(frameError(d.error.code, d.error.message, null, "DbError"));
|
|
260
|
+
else onData(d);
|
|
261
|
+
},
|
|
262
|
+
resubscribe: start,
|
|
263
|
+
revoke: () => {
|
|
264
|
+
if (!live) return;
|
|
265
|
+
live = false;
|
|
266
|
+
dbSubs.delete(id);
|
|
267
|
+
onError(frameError("revoked", "The document store is no longer available to this artifact.", null, "DbError"));
|
|
268
|
+
}
|
|
269
|
+
});
|
|
270
|
+
start();
|
|
271
|
+
return () => {
|
|
272
|
+
if (!live) return;
|
|
273
|
+
live = false;
|
|
274
|
+
dbSubs.delete(id);
|
|
275
|
+
dbCall("unsubscribe", { sub: id }).catch(() => {
|
|
276
|
+
});
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
let holder = null;
|
|
280
|
+
const holderId = () => holder ||= `tab-${Math.random().toString(36).slice(2, 10)}`;
|
|
281
|
+
function docRef(path) {
|
|
282
|
+
const segs = segsOf(path, "doc");
|
|
283
|
+
const full = segs.join("/");
|
|
284
|
+
const ref = {
|
|
285
|
+
id: segs[segs.length - 1],
|
|
286
|
+
path: full,
|
|
287
|
+
get parent() {
|
|
288
|
+
return collectionRef(segs.slice(0, -1).join("/"));
|
|
289
|
+
},
|
|
290
|
+
collection: (sub) => collectionRef(`${full}/${sub}`),
|
|
291
|
+
get: () => dbCall("get", { path: full }).then((r) => docSnap(ref, r && r.exists ? r.data : void 0)),
|
|
292
|
+
set: (data) => dbCall("set", { path: full, data: clone(data) }).then(() => {
|
|
293
|
+
}),
|
|
294
|
+
update: (data) => dbCall("update", { path: full, data: clone(data) }).then(() => {
|
|
295
|
+
}),
|
|
296
|
+
delete: () => dbCall("delete", { path: full }).then(() => {
|
|
297
|
+
}),
|
|
298
|
+
acquire: (opts) => {
|
|
299
|
+
const o = opts || {};
|
|
300
|
+
return dbCall("acquire", { path: full, options: { holder: o.holder || holderId(), ttlMs: o.ttlMs === void 0 ? 3e4 : o.ttlMs, data: o.data } });
|
|
301
|
+
},
|
|
302
|
+
release: (h) => dbCall("release", { path: full, holder: h || holderId() }),
|
|
303
|
+
onSnapshot: (next, error) => {
|
|
304
|
+
const o = observer(next, error);
|
|
305
|
+
return subscribe("doc", full, null, (d) => o.next(docSnap(ref, d.exists ? d.data : void 0)), o.error);
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
return ref;
|
|
309
|
+
}
|
|
310
|
+
function querySnapshot(path, docs, prev) {
|
|
311
|
+
const snaps = docs.map((d) => docSnap(docRef(`${path}/${d.id}`), d.data));
|
|
312
|
+
const changes = [];
|
|
313
|
+
const nextIndex = /* @__PURE__ */ new Map();
|
|
314
|
+
docs.forEach((d, i) => nextIndex.set(d.id, i));
|
|
315
|
+
if (prev) {
|
|
316
|
+
prev.order.forEach((id, i) => {
|
|
317
|
+
if (!nextIndex.has(id)) changes.push({ type: "removed", doc: docSnap(docRef(`${path}/${id}`), prev.data.get(id)), oldIndex: i, newIndex: -1 });
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
docs.forEach((d, i) => {
|
|
321
|
+
const before = prev ? prev.text.get(d.id) : void 0;
|
|
322
|
+
if (before === void 0) changes.push({ type: "added", doc: snaps[i], oldIndex: -1, newIndex: i });
|
|
323
|
+
else if (before !== JSON.stringify(d.data)) changes.push({ type: "modified", doc: snaps[i], oldIndex: prev.order.indexOf(d.id), newIndex: i });
|
|
324
|
+
});
|
|
325
|
+
return {
|
|
326
|
+
docs: snaps,
|
|
327
|
+
size: snaps.length,
|
|
328
|
+
empty: snaps.length === 0,
|
|
329
|
+
metadata: META,
|
|
330
|
+
forEach: (fn, thisArg) => snaps.forEach(fn, thisArg),
|
|
331
|
+
docChanges: () => changes.slice()
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
function stateOf(docs) {
|
|
335
|
+
const s = { order: [], text: /* @__PURE__ */ new Map(), data: /* @__PURE__ */ new Map() };
|
|
336
|
+
for (const d of docs) {
|
|
337
|
+
s.order.push(d.id);
|
|
338
|
+
s.text.set(d.id, JSON.stringify(d.data));
|
|
339
|
+
s.data.set(d.id, d.data);
|
|
340
|
+
}
|
|
341
|
+
return s;
|
|
342
|
+
}
|
|
343
|
+
const OPS = ["==", "!=", "<", "<=", ">", ">=", "in", "not-in", "array-contains"];
|
|
344
|
+
function query(path, spec) {
|
|
345
|
+
return {
|
|
346
|
+
where: (field, op, value) => {
|
|
347
|
+
if (OPS.indexOf(op) < 0) throw new TypeError(`where(): unknown operator ${op}`);
|
|
348
|
+
return query(path, { ...spec, where: (spec.where || []).concat([{ field: String(field), op, value: clone(value) }]) });
|
|
349
|
+
},
|
|
350
|
+
orderBy: (field, dir) => {
|
|
351
|
+
if (spec.orderBy) throw new TypeError("One orderBy() per query.");
|
|
352
|
+
return query(path, { ...spec, orderBy: { field: String(field), dir: dir === "desc" ? "desc" : "asc" } });
|
|
353
|
+
},
|
|
354
|
+
limit: (n) => {
|
|
355
|
+
if (!Number.isInteger(n) || n < 1 || n > 1e3) throw new TypeError("limit() takes 1 to 1000.");
|
|
356
|
+
return query(path, { ...spec, limit: n });
|
|
357
|
+
},
|
|
358
|
+
get: () => dbCall("query", { path, spec }).then((r) => querySnapshot(path, r && r.docs || [], null)),
|
|
359
|
+
onSnapshot: (next, error) => {
|
|
360
|
+
const o = observer(next, error);
|
|
361
|
+
let prev = null;
|
|
362
|
+
return subscribe(
|
|
363
|
+
"query",
|
|
364
|
+
path,
|
|
365
|
+
spec,
|
|
366
|
+
(d) => {
|
|
367
|
+
const docs = d.docs || [];
|
|
368
|
+
const snap = querySnapshot(path, docs, prev);
|
|
369
|
+
const first = prev === null;
|
|
370
|
+
prev = stateOf(docs);
|
|
371
|
+
if (first || snap.docChanges().length) o.next(snap);
|
|
372
|
+
},
|
|
373
|
+
o.error
|
|
374
|
+
);
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
function collectionRef(path) {
|
|
379
|
+
const segs = segsOf(path, "collection");
|
|
380
|
+
const full = segs.join("/");
|
|
381
|
+
const q = query(full, {});
|
|
382
|
+
q.id = segs[segs.length - 1];
|
|
383
|
+
q.path = full;
|
|
384
|
+
Object.defineProperty(q, "parent", { get: () => segs.length > 1 ? docRef(segs.slice(0, -1).join("/")) : null });
|
|
385
|
+
q.doc = (id) => docRef(`${full}/${id === void 0 ? Math.random().toString(36).slice(2, 12) + Date.now().toString(36) : id}`);
|
|
386
|
+
q.add = (data) => dbCall("add", { path: full, data: clone(data) }).then((r) => docRef(r.path));
|
|
387
|
+
return q;
|
|
388
|
+
}
|
|
389
|
+
const db = {
|
|
390
|
+
collection: (path) => collectionRef(path),
|
|
391
|
+
doc: (path) => docRef(path)
|
|
392
|
+
};
|
|
393
|
+
function bytesToB64(bytes) {
|
|
394
|
+
let out = "";
|
|
395
|
+
for (let i = 0; i < bytes.length; i += 32768) out += String.fromCharCode.apply(null, Array.from(bytes.subarray(i, i + 32768)));
|
|
396
|
+
return btoa(out);
|
|
397
|
+
}
|
|
398
|
+
async function encodeContent(value) {
|
|
399
|
+
if (typeof value === "string") return { text: value };
|
|
400
|
+
if (value instanceof Blob) return { b64: bytesToB64(new Uint8Array(await value.arrayBuffer())), ...value.type ? { contentType: value.type } : {} };
|
|
401
|
+
if (value instanceof ArrayBuffer) return { b64: bytesToB64(new Uint8Array(value)) };
|
|
402
|
+
if (ArrayBuffer.isView(value)) return { b64: bytesToB64(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) };
|
|
403
|
+
throw frameError("invalid_content", "A file is a string, Blob or bytes.");
|
|
404
|
+
}
|
|
405
|
+
const isBytes = (v) => v instanceof Blob || v instanceof ArrayBuffer || ArrayBuffer.isView(v);
|
|
406
|
+
async function publish(files, opts) {
|
|
407
|
+
if (typeof files === "string") return call("artifact", "publish", { html: files });
|
|
408
|
+
if (!files || typeof files !== "object") throw frameError("invalid_content", "publish() takes a map of files.");
|
|
409
|
+
const guards = opts && opts.ifMatch && typeof opts.ifMatch === "object" ? opts.ifMatch : null;
|
|
410
|
+
const paths = Object.keys(files);
|
|
411
|
+
if (paths.length < 1 || paths.length > 256) throw frameError("too_large", "publish() takes 1 to 256 paths.");
|
|
412
|
+
const out = {};
|
|
413
|
+
for (const p of paths) {
|
|
414
|
+
const v = files[p];
|
|
415
|
+
const guard = guards && Object.prototype.hasOwnProperty.call(guards, p) ? { ifMatch: guards[p] } : {};
|
|
416
|
+
if (v === null) out[p] = { delete: true, ...guard };
|
|
417
|
+
else if (v && typeof v === "object" && !isBytes(v)) {
|
|
418
|
+
const g = "ifMatch" in v ? { ifMatch: v.ifMatch } : guard;
|
|
419
|
+
if (v.delete === true) out[p] = { delete: true, ...g };
|
|
420
|
+
else out[p] = { ...await encodeContent(v.content), ...v.contentType ? { contentType: v.contentType } : {}, ...g };
|
|
421
|
+
} else out[p] = { ...await encodeContent(v), ...guard };
|
|
422
|
+
}
|
|
423
|
+
return call("artifact", "publish", { files: out });
|
|
424
|
+
}
|
|
425
|
+
const self = {
|
|
426
|
+
get id() {
|
|
427
|
+
return configs.artifact && configs.artifact.id || boot.id;
|
|
428
|
+
},
|
|
429
|
+
publish,
|
|
430
|
+
sync: () => call("artifact", "sync", {}),
|
|
431
|
+
metadata: (refs) => call("artifact", "metadata", { refs: Array.isArray(refs) ? refs : [refs] }),
|
|
432
|
+
search: (q, o) => call("artifact", "search", { q: String(q || ""), ...o || {} }),
|
|
433
|
+
edit: () => Promise.reject(frameError("capability_disabled", "edit() is for live documents; publish the files instead."))
|
|
434
|
+
};
|
|
435
|
+
const assets = {
|
|
436
|
+
upload: (blob, opts) => {
|
|
437
|
+
if (!(blob instanceof Blob)) return Promise.reject(frameError("invalid_request", "upload() takes a Blob."));
|
|
438
|
+
return call("assets", "upload", { blob, type: opts && opts.type || blob.type || "" });
|
|
439
|
+
},
|
|
440
|
+
list: () => call("assets", "list", {}),
|
|
441
|
+
delete: (ref) => call("assets", "delete", { ref: typeof ref === "object" && ref ? ref.id || ref.url : ref })
|
|
442
|
+
};
|
|
443
|
+
const downloads = {
|
|
444
|
+
save: (opts) => {
|
|
445
|
+
const o = opts || {};
|
|
446
|
+
const filename = String(o.filename || "download").replace(/[\\/:*?"<>|\u0000-\u001f]+/g, "_").slice(0, 200) || "download";
|
|
447
|
+
const data = o.data;
|
|
448
|
+
const blob = data instanceof Blob ? data : new Blob([typeof data === "string" || data instanceof ArrayBuffer || ArrayBuffer.isView(data) ? data : JSON.stringify(data)]);
|
|
449
|
+
try {
|
|
450
|
+
const url = URL.createObjectURL(blob);
|
|
451
|
+
const a = document.createElement("a");
|
|
452
|
+
a.href = url;
|
|
453
|
+
a.download = filename;
|
|
454
|
+
a.rel = "noopener";
|
|
455
|
+
a.style.display = "none";
|
|
456
|
+
(document.body || document.documentElement).appendChild(a);
|
|
457
|
+
a.click();
|
|
458
|
+
a.remove();
|
|
459
|
+
setTimeout(() => URL.revokeObjectURL(url), 6e4);
|
|
460
|
+
if (typeof o.request === "string") post({ __open_artifact_export_done: true, request: o.request });
|
|
461
|
+
return Promise.resolve({ status: "saved" });
|
|
462
|
+
} catch (e) {
|
|
463
|
+
return Promise.reject(frameError("unavailable", String(e?.message || e)));
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
};
|
|
467
|
+
function permissionState(name) {
|
|
468
|
+
if (grants.indexOf(name === "self" ? "artifact" : name) >= 0) return Promise.resolve("granted");
|
|
469
|
+
const perms = navigator.permissions;
|
|
470
|
+
if (perms && typeof perms.query === "function") {
|
|
471
|
+
return perms.query({ name }).then(
|
|
472
|
+
(s) => s.state,
|
|
473
|
+
() => "unavailable"
|
|
474
|
+
);
|
|
475
|
+
}
|
|
476
|
+
return Promise.resolve("unavailable");
|
|
477
|
+
}
|
|
478
|
+
async function permissionMap(list) {
|
|
479
|
+
const out = {};
|
|
480
|
+
await Promise.all(list.map(async (n) => out[String(n)] = await permissionState(String(n))));
|
|
481
|
+
return out;
|
|
482
|
+
}
|
|
483
|
+
const permissions = {
|
|
484
|
+
state: (name) => name !== void 0 ? permissionState(String(name)) : permissionMap(grants),
|
|
485
|
+
request: (names) => permissionMap(names === void 0 ? grants : Array.isArray(names) ? names : [names]),
|
|
486
|
+
manage: () => Promise.resolve()
|
|
487
|
+
};
|
|
488
|
+
const FALLBACK_COLOR = "#c7c9d1";
|
|
489
|
+
const userConfig = async () => {
|
|
490
|
+
await whenInit();
|
|
491
|
+
return configs.user || {};
|
|
492
|
+
};
|
|
493
|
+
let profileCache = null;
|
|
494
|
+
const profile = () => profileCache ||= userConfig().then(
|
|
495
|
+
(c) => c.profile === true ? call("user", "profile", {}).catch(() => {
|
|
496
|
+
profileCache = null;
|
|
497
|
+
return {};
|
|
498
|
+
}) : {}
|
|
499
|
+
);
|
|
500
|
+
const colorOf = (c) => typeof c.color === "string" && /^#[0-9a-f]{6}$/.test(c.color) ? c.color : FALLBACK_COLOR;
|
|
501
|
+
const user = {
|
|
502
|
+
id: () => userConfig().then((c) => typeof c.id === "string" ? c.id : null),
|
|
503
|
+
isOwner: () => userConfig().then((c) => c.owner === true),
|
|
504
|
+
canEdit: () => userConfig().then((c) => c.canEdit === true),
|
|
505
|
+
// Here: with no `can` list, the owner can do anything; otherwise permissions are checked.
|
|
506
|
+
can: (permission) => userConfig().then((c) => Array.isArray(c.can) ? typeof permission === "string" && c.can.indexOf(permission) >= 0 : c.owner === true ? typeof permission === "string" && permission.length > 0 : null),
|
|
507
|
+
me: () => Promise.all([userConfig(), profile(), user.email()]).then(
|
|
508
|
+
([c, p, email]) => ({ id: c.id ?? null, name: p.name ?? "", avatarUrl: p.avatarUrl ?? null, color: colorOf(c), email, isOwner: c.owner === true, canEdit: c.canEdit === true }),
|
|
509
|
+
() => ({ id: null, name: "", avatarUrl: null, color: FALLBACK_COLOR, email: null, isOwner: false, canEdit: false })
|
|
510
|
+
),
|
|
511
|
+
name: () => profile().then((p) => p.name ?? "", () => ""),
|
|
512
|
+
avatarUrl: () => profile().then((p) => p.avatarUrl ?? null, () => null),
|
|
513
|
+
email: () => userConfig().then((c) => c.email === true ? call("user", "email", {}) : null).catch(() => null),
|
|
514
|
+
profiles: (ids) => call("user", "profiles", { ids: Array.isArray(ids) ? ids : [ids] }).catch(() => ({})),
|
|
515
|
+
access: (ids) => call("user", "access", { ids: Array.isArray(ids) ? ids : [ids] }).catch(() => ({})),
|
|
516
|
+
search: (q) => call("user", "search", { q: String(q || "") }).catch(() => [])
|
|
517
|
+
};
|
|
518
|
+
let peersNow = [];
|
|
519
|
+
let connected = false;
|
|
520
|
+
const senderOf = (d) => {
|
|
521
|
+
const mine = !!init && d.from === init.client;
|
|
522
|
+
return { peer: d.from, by: d.by, isMe: mine, sameTab: mine, kind: "user", guest: false };
|
|
523
|
+
};
|
|
524
|
+
function onRoomEvent(d) {
|
|
525
|
+
if (d.kind === "msg") {
|
|
526
|
+
const set = roomHandlers.get(d.topic);
|
|
527
|
+
if (set) for (const fn of set) safely(fn, clone(d.data), senderOf(d));
|
|
528
|
+
} else if (d.kind === "peers") {
|
|
529
|
+
peersNow = (d.peers || []).map((p) => ({ ...p, isMe: !!init && p.peer === init.client }));
|
|
530
|
+
for (const fn of peerHandlers) safely(fn, peersNow.slice());
|
|
531
|
+
} else if (d.kind === "connection") {
|
|
532
|
+
connected = !!d.connected;
|
|
533
|
+
for (const fn of connHandlers) safely(fn, connected);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
function makeRoom(prefix) {
|
|
537
|
+
const t = (topic) => prefix + String(topic);
|
|
538
|
+
return {
|
|
539
|
+
emit: (topic, data) => call("room", "emit", { topic: t(topic), data: clone(data) }),
|
|
540
|
+
on: (topic, handler) => {
|
|
541
|
+
const key = t(topic);
|
|
542
|
+
if (!roomHandlers.has(key)) roomHandlers.set(key, /* @__PURE__ */ new Set());
|
|
543
|
+
roomHandlers.get(key).add(handler);
|
|
544
|
+
return () => roomHandlers.get(key)?.delete(handler);
|
|
545
|
+
},
|
|
546
|
+
presence: (patch) => call("room", "presence", { patch: clone(patch || {}) }),
|
|
547
|
+
peers: () => peersNow.slice(),
|
|
548
|
+
onPeers: (fn) => {
|
|
549
|
+
peerHandlers.add(fn);
|
|
550
|
+
return () => peerHandlers.delete(fn);
|
|
551
|
+
},
|
|
552
|
+
connected: () => connected,
|
|
553
|
+
onConnection: (fn) => {
|
|
554
|
+
connHandlers.add(fn);
|
|
555
|
+
return () => connHandlers.delete(fn);
|
|
556
|
+
},
|
|
557
|
+
sendToAgentSession: (data, opts) => {
|
|
558
|
+
const o = opts || {};
|
|
559
|
+
const report = typeof o.onStatus === "function" ? o.onStatus : () => {
|
|
560
|
+
};
|
|
561
|
+
report("sending");
|
|
562
|
+
return call("room", "sendToAgentSession", { data: clone(data), deliver: o.deliver === "stage" ? "stage" : "send" }).then(
|
|
563
|
+
(r) => {
|
|
564
|
+
report("sent");
|
|
565
|
+
return r;
|
|
566
|
+
},
|
|
567
|
+
(e) => {
|
|
568
|
+
report("failed");
|
|
569
|
+
throw e;
|
|
570
|
+
}
|
|
571
|
+
);
|
|
572
|
+
},
|
|
573
|
+
canSendToAgentSession: () => call("room", "canSendToAgentSession", {}),
|
|
574
|
+
join: (name) => makeRoom(`${prefix}${String(name)}/`)
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
const room = makeRoom("");
|
|
578
|
+
function cssPath(start) {
|
|
579
|
+
const parts = [];
|
|
580
|
+
let el = start;
|
|
581
|
+
while (el && el.nodeType === 1 && el !== document.documentElement && parts.length < 12) {
|
|
582
|
+
if (el.id && /^[A-Za-z][\w-]*$/.test(el.id)) {
|
|
583
|
+
parts.unshift(`#${el.id}`);
|
|
584
|
+
break;
|
|
585
|
+
}
|
|
586
|
+
let i = 1;
|
|
587
|
+
let sib = el.previousElementSibling;
|
|
588
|
+
for (; sib; sib = sib.previousElementSibling) if (sib.tagName === el.tagName) i++;
|
|
589
|
+
parts.unshift(`${el.tagName.toLowerCase()}:nth-of-type(${i})`);
|
|
590
|
+
el = el.parentElement;
|
|
591
|
+
}
|
|
592
|
+
return parts.join(" > ");
|
|
593
|
+
}
|
|
594
|
+
function anchorFor(el, ev) {
|
|
595
|
+
if (!el || !el.getBoundingClientRect) return { path: "", x: 0.5, y: 0.5 };
|
|
596
|
+
const r = el.getBoundingClientRect();
|
|
597
|
+
const x = ev && r.width ? (ev.clientX - r.left) / r.width : 0.5;
|
|
598
|
+
const y = ev && r.height ? (ev.clientY - r.top) / r.height : 0.5;
|
|
599
|
+
return { path: cssPath(el), x: Math.min(1, Math.max(0, x)), y: Math.min(1, Math.max(0, y)) };
|
|
600
|
+
}
|
|
601
|
+
function labelFor(el) {
|
|
602
|
+
const text = String(el && (el.getAttribute("aria-label") || el.textContent) || "").replace(/\s+/g, " ").trim();
|
|
603
|
+
return text ? text.slice(0, 80) : el ? el.tagName.toLowerCase() : "the page";
|
|
604
|
+
}
|
|
605
|
+
function viewportPoint(at) {
|
|
606
|
+
if (!at) return null;
|
|
607
|
+
if (typeof Element !== "undefined" && at instanceof Element) {
|
|
608
|
+
const r = at.getBoundingClientRect();
|
|
609
|
+
return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
|
|
610
|
+
}
|
|
611
|
+
return { x: (Number(at.x) || 0) - window.scrollX, y: (Number(at.y) || 0) - window.scrollY };
|
|
612
|
+
}
|
|
613
|
+
let placedDoc = null;
|
|
614
|
+
let shellThreads = [];
|
|
615
|
+
let fallbackDraft = null;
|
|
616
|
+
let placeFrame = 0;
|
|
617
|
+
let placeQueued = false;
|
|
618
|
+
let placeObserver = null;
|
|
619
|
+
function pinsShown() {
|
|
620
|
+
if (anchors) return !!placedDoc && (commentsMode || anchors.callbacks.pinsOutsideMode === true && shellThreads.length > 0);
|
|
621
|
+
return fallbackOn;
|
|
622
|
+
}
|
|
623
|
+
function fallbackPoint(anchor) {
|
|
624
|
+
if (!anchor || typeof anchor !== "object") return null;
|
|
625
|
+
let el = null;
|
|
626
|
+
try {
|
|
627
|
+
el = anchor.path ? document.querySelector(String(anchor.path)) : document.documentElement;
|
|
628
|
+
} catch {
|
|
629
|
+
el = null;
|
|
630
|
+
}
|
|
631
|
+
if (!el) return null;
|
|
632
|
+
const r = el.getBoundingClientRect();
|
|
633
|
+
if (!r.width && !r.height) return null;
|
|
634
|
+
const fx = Number.isFinite(anchor.x) ? anchor.x : 0.5;
|
|
635
|
+
const fy = Number.isFinite(anchor.y) ? anchor.y : 0.5;
|
|
636
|
+
return { x: r.left + r.width * fx, y: r.top + r.height * fy };
|
|
637
|
+
}
|
|
638
|
+
function sendPlaced() {
|
|
639
|
+
placeQueued = false;
|
|
640
|
+
placeFrame = 0;
|
|
641
|
+
if (!pinsShown()) return;
|
|
642
|
+
const map = {};
|
|
643
|
+
if (anchors) {
|
|
644
|
+
for (const k of Object.keys(placedDoc || {})) map[k] = placedDoc[k] ? viewportPoint(placedDoc[k]) : null;
|
|
645
|
+
} else {
|
|
646
|
+
for (const t of shellThreads) map[t.id] = fallbackPoint(t.anchor);
|
|
647
|
+
if (fallbackDraft) map.composer = fallbackPoint(fallbackDraft);
|
|
648
|
+
}
|
|
649
|
+
post({ __open_artifact_comments_placed: true, map });
|
|
650
|
+
}
|
|
651
|
+
function queuePlaced(frame = false) {
|
|
652
|
+
if (frame) {
|
|
653
|
+
if (!placeFrame) placeFrame = requestAnimationFrame(sendPlaced);
|
|
654
|
+
return;
|
|
655
|
+
}
|
|
656
|
+
if (placeQueued) return;
|
|
657
|
+
placeQueued = true;
|
|
658
|
+
queueMicrotask(sendPlaced);
|
|
659
|
+
}
|
|
660
|
+
const onPlaceMove = () => {
|
|
661
|
+
if (pinsShown()) queuePlaced(true);
|
|
662
|
+
};
|
|
663
|
+
window.addEventListener("scroll", onPlaceMove, { capture: true, passive: true });
|
|
664
|
+
window.addEventListener("resize", onPlaceMove);
|
|
665
|
+
function watchLayout(on) {
|
|
666
|
+
if (on && !placeObserver && typeof MutationObserver === "function" && document.body) {
|
|
667
|
+
placeObserver = new MutationObserver(onPlaceMove);
|
|
668
|
+
placeObserver.observe(document.body, { subtree: true, childList: true, attributes: true, characterData: true });
|
|
669
|
+
} else if (!on && placeObserver) {
|
|
670
|
+
placeObserver.disconnect();
|
|
671
|
+
placeObserver = null;
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
const sendListeners = /* @__PURE__ */ new Set();
|
|
675
|
+
let fallbackOn = false;
|
|
676
|
+
const COMMENT_CURSOR = 'url("data:image/svg+xml,%3Csvg%20xmlns=%27http://www.w3.org/2000/svg%27%20width=%2728%27%20height=%2728%27%20viewBox=%270%200%2028%2028%27%3E%3Cpath%20d=%27M%202%2026%20L%202%2014%20A%2012%2012%200%201%201%2014%2026%20Z%27%20fill=%27%23000%27%20stroke=%27%23fff%27%20stroke-width=%272%27/%3E%3C/svg%3E") 2 26, crosshair';
|
|
677
|
+
let cursorStyle = null;
|
|
678
|
+
let hoverBox = null;
|
|
679
|
+
let hoverFrame = 0;
|
|
680
|
+
let hoverEvent = null;
|
|
681
|
+
function fallbackTarget(ev) {
|
|
682
|
+
const target = ev.target;
|
|
683
|
+
return target && target.nodeType === 1 ? target : target && target.parentElement || null;
|
|
684
|
+
}
|
|
685
|
+
function paintHover() {
|
|
686
|
+
hoverFrame = 0;
|
|
687
|
+
const ev = hoverEvent;
|
|
688
|
+
const el = ev ? fallbackTarget(ev) : null;
|
|
689
|
+
if (!el || el === document.documentElement || el === document.body || !el.getBoundingClientRect) {
|
|
690
|
+
if (hoverBox) hoverBox.style.display = "none";
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
if (!hoverBox) {
|
|
694
|
+
hoverBox = document.createElement("div");
|
|
695
|
+
hoverBox.setAttribute("aria-hidden", "true");
|
|
696
|
+
Object.assign(hoverBox.style, {
|
|
697
|
+
position: "fixed",
|
|
698
|
+
zIndex: "2147483647",
|
|
699
|
+
pointerEvents: "none",
|
|
700
|
+
boxSizing: "border-box",
|
|
701
|
+
border: "2px solid rgba(245, 158, 11, 0.8)",
|
|
702
|
+
borderRadius: "2px"
|
|
703
|
+
});
|
|
704
|
+
document.documentElement.append(hoverBox);
|
|
705
|
+
}
|
|
706
|
+
const r = el.getBoundingClientRect();
|
|
707
|
+
Object.assign(hoverBox.style, { display: "block", left: `${r.left}px`, top: `${r.top}px`, width: `${r.width}px`, height: `${r.height}px` });
|
|
708
|
+
}
|
|
709
|
+
function fallbackMove(ev) {
|
|
710
|
+
hoverEvent = ev;
|
|
711
|
+
if (!hoverFrame) hoverFrame = requestAnimationFrame(paintHover);
|
|
712
|
+
}
|
|
713
|
+
function fallbackLeave() {
|
|
714
|
+
hoverEvent = null;
|
|
715
|
+
if (hoverBox) hoverBox.style.display = "none";
|
|
716
|
+
}
|
|
717
|
+
function fallbackClick(ev) {
|
|
718
|
+
if (!commentsMode || anchors) return;
|
|
719
|
+
ev.preventDefault();
|
|
720
|
+
ev.stopPropagation();
|
|
721
|
+
const el = fallbackTarget(ev);
|
|
722
|
+
fallbackLeave();
|
|
723
|
+
const anchor = anchorFor(el, ev);
|
|
724
|
+
call("comments", "compose", { anchor, at: { x: ev.clientX, y: ev.clientY }, label: labelFor(el), click: true }).then((r) => {
|
|
725
|
+
fallbackDraft = r && r.opened ? anchor : null;
|
|
726
|
+
queuePlaced();
|
|
727
|
+
}).catch(() => {
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
function setFallback(on) {
|
|
731
|
+
if (on === fallbackOn) return;
|
|
732
|
+
fallbackOn = on;
|
|
733
|
+
if (on) {
|
|
734
|
+
document.addEventListener("click", fallbackClick, true);
|
|
735
|
+
document.addEventListener("mousemove", fallbackMove, true);
|
|
736
|
+
document.addEventListener("mouseleave", fallbackLeave);
|
|
737
|
+
document.addEventListener("scroll", fallbackLeave, true);
|
|
738
|
+
document.documentElement.style.cursor = COMMENT_CURSOR;
|
|
739
|
+
cursorStyle = document.createElement("style");
|
|
740
|
+
cursorStyle.textContent = `*, *::before, *::after { cursor: ${COMMENT_CURSOR} !important; }`;
|
|
741
|
+
document.head.append(cursorStyle);
|
|
742
|
+
watchLayout(true);
|
|
743
|
+
queuePlaced();
|
|
744
|
+
} else {
|
|
745
|
+
document.removeEventListener("click", fallbackClick, true);
|
|
746
|
+
document.removeEventListener("mousemove", fallbackMove, true);
|
|
747
|
+
document.removeEventListener("mouseleave", fallbackLeave);
|
|
748
|
+
document.removeEventListener("scroll", fallbackLeave, true);
|
|
749
|
+
document.documentElement.style.cursor = "";
|
|
750
|
+
cursorStyle?.remove();
|
|
751
|
+
cursorStyle = null;
|
|
752
|
+
fallbackLeave();
|
|
753
|
+
watchLayout(false);
|
|
754
|
+
fallbackDraft = null;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
function onCommentsEvent(d) {
|
|
758
|
+
const cb = anchors && anchors.callbacks;
|
|
759
|
+
if (d.op === "mode") {
|
|
760
|
+
commentsMode = !!d.on;
|
|
761
|
+
if (cb && typeof cb.mode === "function") safely(() => cb.mode(commentsMode));
|
|
762
|
+
else if (!anchors) setFallback(commentsMode);
|
|
763
|
+
if (commentsMode) queuePlaced();
|
|
764
|
+
} else if (d.op === "threads") {
|
|
765
|
+
shellThreads = (Array.isArray(d.threads) ? d.threads : []).map((t) => ({ id: String(t.id), anchor: t.anchor, resolved: !!t.resolved, active: !!t.active }));
|
|
766
|
+
if (cb && typeof cb.threads === "function") safely(() => cb.threads(shellThreads.map((t) => ({ ...t }))));
|
|
767
|
+
queuePlaced();
|
|
768
|
+
} else if (d.op === "reveal") {
|
|
769
|
+
if (cb && typeof cb.reveal === "function") safely(() => cb.reveal(d.id));
|
|
770
|
+
else if (!anchors) revealFallback(d.id);
|
|
771
|
+
} else if (d.op === "composing") {
|
|
772
|
+
if (d.state === false) fallbackDraft = null;
|
|
773
|
+
if (cb && typeof cb.composing === "function") safely(() => cb.composing(d.state === void 0 ? null : d.state));
|
|
774
|
+
} else if (d.op === "move") {
|
|
775
|
+
void answerMove(cb, d);
|
|
776
|
+
} else if (d.op === "send") {
|
|
777
|
+
if (sendListeners.size) post({ __open_artifact_comments_sent: true, ticket: d.ticket, pending: true });
|
|
778
|
+
let chain = Promise.resolve({ handled: false });
|
|
779
|
+
for (const fn of sendListeners) chain = chain.then((r) => r && r.handled ? r : Promise.resolve(fn(d.payload)).catch(() => ({ handled: false })));
|
|
780
|
+
chain.then((r) => post({ __open_artifact_comments_sent: true, ticket: d.ticket, handled: !!(r && r.handled), reply: r && typeof r.reply === "string" ? r.reply : void 0 }));
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
function revealFallback(id) {
|
|
784
|
+
const t = shellThreads.find((x) => x.id === id);
|
|
785
|
+
if (!t || !t.anchor || typeof t.anchor !== "object") return;
|
|
786
|
+
try {
|
|
787
|
+
const el = t.anchor.path ? document.querySelector(String(t.anchor.path)) : null;
|
|
788
|
+
el?.scrollIntoView({ block: "center", inline: "nearest" });
|
|
789
|
+
} catch {
|
|
790
|
+
}
|
|
791
|
+
queuePlaced(true);
|
|
792
|
+
}
|
|
793
|
+
async function answerMove(cb, d) {
|
|
794
|
+
const refuse = () => post({ __open_artifact_comments_moved: true, n: d.n, refused: true });
|
|
795
|
+
if (!cb || typeof cb.move !== "function" || !Number.isFinite(d.x) || !Number.isFinite(d.y)) return refuse();
|
|
796
|
+
try {
|
|
797
|
+
const answer = await Promise.race([
|
|
798
|
+
Promise.resolve(cb.move(String(d.id), { x: d.x + window.scrollX, y: d.y + window.scrollY })),
|
|
799
|
+
new Promise((resolve) => setTimeout(() => resolve(null), 2e3))
|
|
800
|
+
]);
|
|
801
|
+
if (!answer || typeof answer !== "object" || typeof answer.anchor !== "string") return refuse();
|
|
802
|
+
post({
|
|
803
|
+
__open_artifact_comments_moved: true,
|
|
804
|
+
n: d.n,
|
|
805
|
+
anchor: answer.anchor,
|
|
806
|
+
...typeof answer.label === "string" ? { label: answer.label } : {},
|
|
807
|
+
...typeof answer.detail === "string" ? { detail: answer.detail } : {}
|
|
808
|
+
});
|
|
809
|
+
} catch {
|
|
810
|
+
refuse();
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
document.addEventListener("keydown", (ev) => {
|
|
814
|
+
if (ev.key === "Escape" && commentsMode && !ev.defaultPrevented) post({ __frame_escape: true });
|
|
815
|
+
});
|
|
816
|
+
const comments = {
|
|
817
|
+
openComposer: (opts) => {
|
|
818
|
+
const el = opts && opts.element || null;
|
|
819
|
+
const r = el && el.getBoundingClientRect ? el.getBoundingClientRect() : null;
|
|
820
|
+
return call("comments", "compose", {
|
|
821
|
+
anchor: el ? anchorFor(el) : { path: "", x: 0.5, y: 0.5 },
|
|
822
|
+
at: r ? { x: r.left + r.width / 2, y: r.top + r.height / 2 } : null,
|
|
823
|
+
label: el ? labelFor(el) : "the page"
|
|
824
|
+
});
|
|
825
|
+
},
|
|
826
|
+
anchorFor: (el) => anchorFor(el),
|
|
827
|
+
create: (o) => call("comments", "create", { anchor: clone(o && o.anchor), text: o && o.text, label: o && o.label }).then((r) => ({ threadId: r.threadId, commentId: r.commentId })),
|
|
828
|
+
reply: (a, b) => {
|
|
829
|
+
const o = typeof a === "object" && a ? a : { threadId: a, text: b };
|
|
830
|
+
return call("comments", "reply", { threadId: o.threadId, text: o.text }).then((r) => ({ threadId: r.threadId, commentId: r.commentId }));
|
|
831
|
+
},
|
|
832
|
+
resolve: (threadId, resolved) => call("comments", "resolve", { threadId, resolved: resolved !== false }).then(() => {
|
|
833
|
+
}),
|
|
834
|
+
delete: (threadId, commentId) => call("comments", "delete", { threadId, commentId }).then(() => {
|
|
835
|
+
}),
|
|
836
|
+
list: () => call("comments", "list", {}).then((r) => r.threads),
|
|
837
|
+
sendToAgent: (o) => call("comments", "sendToAgent", clone(o || {})),
|
|
838
|
+
canSendToAgent: () => call("comments", "canSendToAgent", {}),
|
|
839
|
+
onSendToAgent: (fn) => {
|
|
840
|
+
sendListeners.add(fn);
|
|
841
|
+
return () => sendListeners.delete(fn);
|
|
842
|
+
},
|
|
843
|
+
customAnchors: (callbacks) => {
|
|
844
|
+
const mine = { callbacks: callbacks || {} };
|
|
845
|
+
anchors = mine;
|
|
846
|
+
placedDoc = null;
|
|
847
|
+
setFallback(false);
|
|
848
|
+
const ctl = {
|
|
849
|
+
// While registered, compose is the viewer's click (the shell turns comment mode on, or closes what is open).
|
|
850
|
+
compose: (anchor, at, opts) => {
|
|
851
|
+
const o = opts || {};
|
|
852
|
+
return call("comments", "compose", { anchor: clone(anchor), at: viewportPoint(at), label: o.label, detail: o.detail, area: !!o.area, click: true });
|
|
853
|
+
},
|
|
854
|
+
open: (id, at) => call("comments", "open", { id, at: viewportPoint(at) }),
|
|
855
|
+
// Kept in document points: reported now, and again on every scroll and resize.
|
|
856
|
+
placed: (map) => {
|
|
857
|
+
if (anchors !== mine) return;
|
|
858
|
+
const doc = {};
|
|
859
|
+
for (const k of Object.keys(map || {})) {
|
|
860
|
+
const v = map[k];
|
|
861
|
+
doc[k] = v && typeof v === "object" ? typeof Element !== "undefined" && v instanceof Element ? v : { x: Number(v.x), y: Number(v.y) } : null;
|
|
862
|
+
}
|
|
863
|
+
placedDoc = doc;
|
|
864
|
+
queuePlaced();
|
|
865
|
+
},
|
|
866
|
+
domAnchor: (el, ev) => anchorFor(el, ev),
|
|
867
|
+
exitMode: () => void call("comments", "mode", { on: false }).catch(() => {
|
|
868
|
+
}),
|
|
869
|
+
release: () => {
|
|
870
|
+
if (anchors === mine) {
|
|
871
|
+
anchors = null;
|
|
872
|
+
placedDoc = null;
|
|
873
|
+
setFallback(commentsMode);
|
|
874
|
+
}
|
|
875
|
+
call("comments", "custom", { on: false }).catch(() => {
|
|
876
|
+
});
|
|
877
|
+
},
|
|
878
|
+
areas: void 0
|
|
879
|
+
};
|
|
880
|
+
return call("comments", "custom", { on: true, pins: callbacks && callbacks.pinsOutsideMode === true, move: !!callbacks && typeof callbacks.move === "function" }).then(() => ctl);
|
|
881
|
+
}
|
|
882
|
+
};
|
|
883
|
+
function stub(name) {
|
|
884
|
+
return new Proxy(
|
|
885
|
+
{},
|
|
886
|
+
{
|
|
887
|
+
get: (_t, prop) => {
|
|
888
|
+
if (typeof prop === "symbol" || prop === "then" || prop === "toJSON") return void 0;
|
|
889
|
+
if (prop === "available") return true;
|
|
890
|
+
return () => call(name, String(prop), {});
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
);
|
|
894
|
+
}
|
|
895
|
+
const hot = Object.freeze({ data: void 0, from: null, gen: 0, signal: void 0, snapshot() {
|
|
896
|
+
}, ready() {
|
|
897
|
+
}, accept() {
|
|
898
|
+
}, restart() {
|
|
899
|
+
} });
|
|
900
|
+
const namespaces = { db, artifact: self, assets, downloads, user, permissions, room, comments };
|
|
901
|
+
const mounted = /* @__PURE__ */ Object.create(null);
|
|
902
|
+
function namespaceOf(key) {
|
|
903
|
+
if (stubs.indexOf(key) >= 0) return mounted[key] ||= stub(key);
|
|
904
|
+
if (!namespaces[key]) return null;
|
|
905
|
+
if (!mounted[key]) {
|
|
906
|
+
const ns = /* @__PURE__ */ Object.create(null);
|
|
907
|
+
const src = namespaces[key];
|
|
908
|
+
for (const k of Object.keys(src)) Object.defineProperty(ns, k, Object.getOwnPropertyDescriptor(src, k));
|
|
909
|
+
delete ns.then;
|
|
910
|
+
mounted[key] = Object.freeze(ns);
|
|
911
|
+
}
|
|
912
|
+
return mounted[key];
|
|
913
|
+
}
|
|
914
|
+
const pageVer = (/^\/_f\/([^/]{1,128})\//.exec(location.pathname) || [])[1] || "0";
|
|
915
|
+
function want(cap) {
|
|
916
|
+
return new Promise((resolve) => {
|
|
917
|
+
const done = (value) => {
|
|
918
|
+
clearTimeout(timer);
|
|
919
|
+
wants.delete(cap);
|
|
920
|
+
resolve(value);
|
|
921
|
+
};
|
|
922
|
+
const timer = setTimeout(() => done(null), WANT_TIMEOUT_MS);
|
|
923
|
+
wants.set(cap, (g) => {
|
|
924
|
+
if (typeof g.brokerGen === "number") brokerGen = g.brokerGen;
|
|
925
|
+
if (!g.grant || cap === "network") return done(null);
|
|
926
|
+
configs[cap] = g.grant && g.grant.config || {};
|
|
927
|
+
done(namespaceOf(cap));
|
|
928
|
+
});
|
|
929
|
+
post({ __frame_cap_want: true, cap: cap === "artifact" ? "self" : cap, ver: pageVer });
|
|
930
|
+
});
|
|
931
|
+
}
|
|
932
|
+
const slots = /* @__PURE__ */ new Map();
|
|
933
|
+
const KNOWN = /^[a-z][a-z0-9]{0,23}$/;
|
|
934
|
+
function use(name) {
|
|
935
|
+
if (typeof name !== "string") return Promise.resolve(null);
|
|
936
|
+
if (name === "hot") return Promise.resolve(hot);
|
|
937
|
+
const key = name === "self" ? "artifact" : name;
|
|
938
|
+
if (!KNOWN.test(key) || !namespaces[key] && stubs.indexOf(key) < 0) return Promise.resolve(null);
|
|
939
|
+
let slot = slots.get(key);
|
|
940
|
+
if (!slot) {
|
|
941
|
+
slot = whenInit().then((got) => {
|
|
942
|
+
if (!got) return null;
|
|
943
|
+
if (stubs.indexOf(key) >= 0) return namespaceOf(key);
|
|
944
|
+
if (got.capabilities && got.capabilities[key]) return namespaceOf(key);
|
|
945
|
+
if (got.capWants === true && Array.isArray(got.usable) && got.usable.indexOf(key) >= 0) return want(key);
|
|
946
|
+
return null;
|
|
947
|
+
});
|
|
948
|
+
if (boot.debug) slot.then((ns) => ns || post({ __open_artifact_console: true, level: "warn", text: `use(${name}) → null` }));
|
|
949
|
+
slots.set(key, slot);
|
|
950
|
+
}
|
|
951
|
+
return slot;
|
|
952
|
+
}
|
|
953
|
+
const openArtifact = { __openArtifactFrame: true, contract: boot.contract, use };
|
|
954
|
+
for (const g of grants) {
|
|
955
|
+
const ns = namespaceOf(g);
|
|
956
|
+
if (ns) openArtifact[g] = ns;
|
|
957
|
+
}
|
|
958
|
+
if (grants.indexOf("artifact") >= 0) openArtifact.self = namespaceOf("artifact");
|
|
959
|
+
openArtifact.hot = hot;
|
|
960
|
+
for (const s of stubs) openArtifact[s] = namespaceOf(s);
|
|
961
|
+
Object.defineProperty(window, "openArtifact", { value: Object.freeze(openArtifact), configurable: false, writable: false, enumerable: false });
|
|
962
|
+
if (boot.debug && framed) {
|
|
963
|
+
const relay = (level, args) => {
|
|
964
|
+
const text = Array.prototype.map.call(args, (a) => {
|
|
965
|
+
if (a instanceof Error) return a.stack || a.message;
|
|
966
|
+
if (typeof a === "string") return a;
|
|
967
|
+
try {
|
|
968
|
+
return JSON.stringify(a);
|
|
969
|
+
} catch {
|
|
970
|
+
return String(a);
|
|
971
|
+
}
|
|
972
|
+
}).join(" ").slice(0, 4e3);
|
|
973
|
+
post({ __open_artifact_console: true, level, text });
|
|
974
|
+
};
|
|
975
|
+
for (const level of ["error", "warn"]) {
|
|
976
|
+
const orig = console[level];
|
|
977
|
+
console[level] = (...args) => {
|
|
978
|
+
relay(level, args);
|
|
979
|
+
orig.apply(console, args);
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
window.addEventListener("error", (ev) => relay("error", [ev.error || ev.message]));
|
|
983
|
+
window.addEventListener("unhandledrejection", (ev) => relay("error", ["unhandled rejection:", ev.reason]));
|
|
984
|
+
}
|
|
985
|
+
window.addEventListener("pagehide", () => {
|
|
986
|
+
for (const id of [...dbSubs.keys()]) dbCall("unsubscribe", { sub: id }).catch(() => {
|
|
987
|
+
});
|
|
988
|
+
dbSubs.clear();
|
|
989
|
+
});
|
|
990
|
+
connect();
|
|
991
|
+
const signalReady = () => post({ __frame_ready: true, gate: "init" });
|
|
992
|
+
if (document.readyState === "complete") setTimeout(signalReady, 0);
|
|
993
|
+
else window.addEventListener("load", signalReady, { once: true });
|
|
994
|
+
})();
|
|
995
|
+
})();
|