@kition/kit-host 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/dist/LICENSE ADDED
@@ -0,0 +1,177 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
package/dist/index.js ADDED
@@ -0,0 +1,530 @@
1
+ import { KitRpcError as b, FILE_HANDLE_PREFIX as W, HOST_ACTION_CAPABILITY_PREFIX as te, HOST_SERVICES as ne, serviceAllowed as ie, HOST_SERVICE_CAPABILITY_PREFIX as se, KIT_UI_PROTOCOL as z, linkPathFrom as oe, isReady as re, KitPeer as ae, isGeneratePurpose as ce, parseOpenParams as le, isOpenableUrl as de, isFetchableUrl as fe, FETCH_IMAGE_TYPES as ue, parseLinksPickParams as he, parseSchemaReport as pe, parsePresence as j, parseServiceParams as me, parseCommentAnchor as we } from "@kition/kit-ui-protocol";
2
+ import { ACTION_ERROR_REASONS as Le, FETCH_IMAGE_ERROR_REASONS as Pe, FETCH_IMAGE_TYPES as Ce, GENERATE_ERROR_REASONS as Ne, GENERATE_PURPOSES as $e, HOST_SERVICES as Te, KIT_UI_PROTOCOL as ze, KitRpcError as Ue, LEASE_HELD_REASON as xe, OPEN_ERROR_REASONS as Fe, OPEN_URL_SCHEMES as He, SERVICE_ERROR_REASONS as Me, fetchImageErrorReason as Ge, fileErrorReason as Ke, hostRequestErrorReason as We, isFetchableUrl as je, isGeneratePurpose as Be, isOpenableUrl as De, linkPathFrom as Ve, openErrorReason as Ye, parseCommentAnchor as Xe, parseKitView as Je, parseLinkRef as Ze, parseLinksPickParams as Qe, parseOpenParams as et, parseServiceParams as tt, serviceAllowed as nt } from "@kition/kit-ui-protocol";
3
+ function m(t, r) {
4
+ return new b(-32e3, r, { reason: t });
5
+ }
6
+ const N = (t) => new b(-32602, t), H = (t) => Object.prototype.toString.call(t) === "[object ArrayBuffer]";
7
+ function C(t) {
8
+ const r = t.lastIndexOf(".");
9
+ return r > 0 ? t.slice(r + 1).toLowerCase() : "";
10
+ }
11
+ const ge = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
12
+ function M(t) {
13
+ let i = (t.split(/[\\/]/).pop() ?? "").replace(/[\u0000-\u001f\u007f<>:"|?*]/g, "").trim().replace(/^\.+/, "").replace(/[. ]+$/, "");
14
+ const s = i.indexOf("."), c = s < 0 ? i : i.slice(0, s);
15
+ if (ge.test(c) && (i = `${c}_${i.slice(c.length)}`), i.length > 255) {
16
+ const u = C(i);
17
+ i = u ? `${i.slice(0, 254 - u.length)}.${u}` : i.slice(0, 255);
18
+ }
19
+ return i || "Untitled";
20
+ }
21
+ async function ye(t, r) {
22
+ const i = t.lastIndexOf("."), [s, c] = i > 0 ? [t.slice(0, i), t.slice(i)] : [t, ""];
23
+ for (let u = 1; u < 1e4; u += 1) {
24
+ const g = u === 1 ? t : `${s} ${u}${c}`;
25
+ if (!await r(g)) return g;
26
+ }
27
+ throw m("io-error", "no unused name is left for this file");
28
+ }
29
+ function G() {
30
+ const t = new Uint8Array(16);
31
+ return crypto.getRandomValues(t), W + Array.from(t, (r) => r.toString(16).padStart(2, "0")).join("");
32
+ }
33
+ const ke = (t) => t.split(/[\\/]/).filter(Boolean).pop() ?? t, ve = () => globalThis.navigator?.userActivation?.isActive ?? !0, F = (t) => (t ?? []).map((r) => r.replace(/^\./, "").toLowerCase());
34
+ function be(t, r, i) {
35
+ let s = [];
36
+ return {
37
+ append: async (c) => void s.push(c),
38
+ commit: async () => {
39
+ const c = new Uint8Array(s.reduce((k, q) => k + q.byteLength, 0));
40
+ let u = 0;
41
+ for (const k of s)
42
+ c.set(k, u), u += k.byteLength;
43
+ const g = await t.commit(r(), c, i());
44
+ return s = [], g;
45
+ },
46
+ abort: async () => {
47
+ s = [];
48
+ }
49
+ };
50
+ }
51
+ const Ee = ["files/pick", "files/create", "files/stat", "files/read", "files/list", "files/write", "files/release", "files/print"];
52
+ function Re(t) {
53
+ const { storage: r } = t, i = G().slice(W.length), s = { read: F(t.manifest?.read), create: F(t.manifest?.create), folders: t.manifest?.folders === !0, print: t.manifest?.print === !0 }, c = r.name ?? ke, u = t.gesture ?? ve, g = /* @__PURE__ */ new Map();
54
+ let k = !1, q = 0;
55
+ const $ = ["files", ...t.pick ? ["files-pick"] : [], ...t.print ? ["print"] : []], w = (e) => ({
56
+ handle: e.handle,
57
+ name: e.name,
58
+ kind: e.kind,
59
+ ...e.size !== void 0 ? { size: e.size } : {},
60
+ ...e.mime !== void 0 ? { mime: e.mime } : {},
61
+ version: e.version,
62
+ rights: [...e.rights]
63
+ }), E = (e, n, a, f, d = {}) => {
64
+ const h = {
65
+ handle: G(),
66
+ session: i,
67
+ kit: t.kit,
68
+ principal: t.principal,
69
+ flow: f,
70
+ rights: a,
71
+ kind: n?.kind ?? "file",
72
+ name: d.name ?? c(e),
73
+ ref: e,
74
+ folder: d.folder ?? null,
75
+ accept: d.accept ?? [],
76
+ mime: d.mime ?? n?.mime,
77
+ version: n?.version ?? null,
78
+ size: n?.size,
79
+ committed: !1,
80
+ staging: null,
81
+ staged: 0,
82
+ written: 0,
83
+ expected: null
84
+ };
85
+ g.set(h.handle, h);
86
+ const { handle: S, session: x, kit: J, principal: Z, kind: Q, name: ee } = h;
87
+ return t.log?.({ handle: S, session: x, kit: J, principal: Z, flow: f, rights: [...a], kind: Q, name: ee }), h;
88
+ }, v = (e, n, a) => {
89
+ if (k) throw m("file-not-granted", "the session has ended");
90
+ const f = typeof e == "string" ? g.get(e) : void 0;
91
+ if (!f) throw m("file-not-granted", "this handle was not granted to this session");
92
+ if (n && !f.rights.includes(n)) throw m("file-not-granted", `this handle has no ${n} right`);
93
+ if (a && f.kind !== a) throw m("file-not-granted", `this handle is not a ${a}`);
94
+ return f;
95
+ }, l = async (e) => {
96
+ try {
97
+ return await e();
98
+ } catch (n) {
99
+ throw n instanceof b ? n : m("io-error", "the host could not reach the file");
100
+ }
101
+ }, O = async (e) => {
102
+ g.delete(e.handle);
103
+ const n = e.staging;
104
+ e.staging = null, n && await n.abort().catch(() => {
105
+ });
106
+ }, I = (e) => {
107
+ if (!u()) throw m("no-gesture", `${e} needs a person's gesture in the kit`);
108
+ }, L = async (e, n) => {
109
+ const a = new Set([...g.values()].filter((d) => d.rights.includes("create") && d.kind === "file" && !d.committed).map((d) => d.ref)), f = await ye(n, async (d) => {
110
+ const h = r.child(e, d);
111
+ return a.has(h) || await r.stat(h) !== null;
112
+ });
113
+ return { name: f, ref: r.child(e, f) };
114
+ }, P = (e, n = s.read) => {
115
+ const a = C(e);
116
+ if (!s.read.includes(a) || !n.includes(a)) throw m("not-allowed", `the kit may not read .${a || "(none)"} files`);
117
+ }, y = (e) => {
118
+ const n = C(e);
119
+ if (!s.create.includes(n)) throw m("not-allowed", `the kit may not create .${n || "(none)"} files`);
120
+ }, _ = (e, n) => {
121
+ const a = F(e);
122
+ if (a.some((f) => !n.includes(f))) throw m("not-allowed", "the kit asked for a file type its manifest does not declare");
123
+ return a.length ? a : n;
124
+ }, o = async (e) => {
125
+ if (!t.pick) throw m("unsupported", "this host has no picker");
126
+ if (e?.mode !== "open" && e?.mode !== "folder" && e?.mode !== "save") throw N("mode is open, folder, or save");
127
+ if (I("files/pick"), e.mode === "folder" && !s.folders) throw m("not-allowed", "the kit may not ask for folders");
128
+ const n = _(e.accept, e.mode === "save" ? s.create : s.read);
129
+ e.mode === "save" && e.suggestedName != null && y(M(e.suggestedName));
130
+ const a = await l(() => t.pick(e)), f = [];
131
+ for (const d of e.mode === "open" && !e.multiple ? a.slice(0, 1) : a) {
132
+ const h = await l(() => r.stat(d));
133
+ if (e.mode === "folder") {
134
+ if (h?.kind !== "folder") continue;
135
+ const S = s.create.length ? ["read", "create"] : ["read"];
136
+ f.push(w(E(d, h, S, "pick", { accept: n })));
137
+ } else if (e.mode === "open") {
138
+ if (h?.kind !== "file" || !n.includes(C(c(d)))) continue;
139
+ f.push(w(E(d, h, ["read"], "pick")));
140
+ } else {
141
+ if (!n.includes(C(c(d)))) throw m("not-allowed", "the kit may not create this file type");
142
+ if (h?.kind === "folder") continue;
143
+ if (h && t.readOnly) throw m("not-allowed", "a read-only session replaces no file");
144
+ f.push(w(E(d, h, h ? ["write"] : ["create"], "pick")));
145
+ break;
146
+ }
147
+ }
148
+ return { files: f };
149
+ }, p = async (e) => {
150
+ if (typeof e?.suggestedName != "string") throw N("suggestedName is a string");
151
+ const n = e.folder === void 0 ? null : v(e.folder, "create", "folder"), a = M(e.suggestedName);
152
+ y(a);
153
+ const { name: f, ref: d } = await l(() => L(n?.ref ?? null, a));
154
+ return w(E(d, null, ["create"], "create", { name: f, folder: n?.ref ?? null, mime: typeof e.mime == "string" ? e.mime : void 0 }));
155
+ }, R = async ({ handle: e, offset: n, length: a }) => {
156
+ const f = v(e, "read", "file"), d = n ?? 0;
157
+ if (!Number.isSafeInteger(d) || d < 0 || a !== void 0 && (!Number.isSafeInteger(a) || a < 0)) throw N("offset and length are whole numbers");
158
+ const h = await l(() => r.read(f.ref, d, a));
159
+ return f.version = h.version, f.size = h.size, h;
160
+ }, T = async ({ handle: e }) => {
161
+ const n = v(e, "read", "folder"), a = await l(() => r.list(n.ref)), f = [];
162
+ for (const d of a) {
163
+ if (!n.accept.includes(C(c(d))) || !s.read.includes(C(c(d)))) continue;
164
+ const h = await l(() => r.stat(d));
165
+ h?.kind === "file" && f.push(w(E(d, h, ["read"], "list")));
166
+ }
167
+ return { files: f };
168
+ }, U = async (e) => {
169
+ const n = v(e?.handle, void 0, "file"), a = n.rights.includes("create");
170
+ if (!a && !n.rights.includes("write")) throw m("file-not-granted", "this handle has no create or write right");
171
+ if (a && n.committed) throw m("already-committed", "this file was already committed");
172
+ if (!H(e.bytes)) throw N("bytes is an ArrayBuffer");
173
+ if (e.offset !== n.staged) throw N(`offset is ${n.staged}, the bytes staged so far`);
174
+ const f = e.bytes.byteLength;
175
+ if (t.quota?.perGrant !== void 0 && n.written + f > t.quota.perGrant || t.quota?.perSession !== void 0 && q + f > t.quota.perSession)
176
+ throw m("quota", "this write passes the host's cap");
177
+ if (e.final && !a) {
178
+ if (typeof e.expected != "string") throw m("conflict", "the final chunk carries the version it replaces");
179
+ if (await l(() => r.unsaved?.(n.ref) ?? !1)) throw m("unsaved-edits", "the file is open with unsaved edits");
180
+ n.expected = e.expected;
181
+ }
182
+ if (!n.staging) {
183
+ const S = () => a ? { mode: "create" } : { mode: "replace", expected: n.expected ?? "" };
184
+ n.staging = r.stage ? r.stage(n.ref, S) : be(r, () => n.ref, S);
185
+ }
186
+ const d = n.staging;
187
+ if (await l(() => d.append(new Uint8Array(e.bytes.slice(0)))), n.staged += f, n.written += f, q += f, !e.final) return {};
188
+ const h = await B(n, d, a);
189
+ return n.staging = null, n.staged = 0, n.expected = null, n.version = h.version, a && (n.committed = !0), { version: h.version };
190
+ }, B = async (e, n, a) => {
191
+ for (let f = 0; ; f += 1)
192
+ try {
193
+ return await l(() => n.commit());
194
+ } catch (d) {
195
+ const h = d instanceof b && d.data?.reason === "conflict";
196
+ if (!a || !h || e.flow !== "create" || r.stage || f >= 8) throw d;
197
+ const S = await l(() => L(e.folder, e.name));
198
+ e.ref = S.ref, e.name = S.name;
199
+ }
200
+ }, D = async ({ handles: e }) => {
201
+ for (const n of Array.isArray(e) ? e : []) {
202
+ const a = typeof n == "string" ? g.get(n) : void 0;
203
+ a && await O(a);
204
+ }
205
+ return {};
206
+ }, V = async (e) => {
207
+ if (!t.print) throw m("unsupported", "this host does not print");
208
+ if (!s.print) throw m("not-allowed", "the kit may not print");
209
+ I("files/print");
210
+ let n;
211
+ if (!e || typeof e != "object") throw N("a print takes PDF bytes or a handle");
212
+ if ("handle" in e) {
213
+ const f = v(e.handle, "read", "file");
214
+ if (C(f.name) !== "pdf" && f.mime !== "application/pdf") throw m("not-allowed", "only a PDF prints");
215
+ n = await Y(f.ref);
216
+ } else {
217
+ if (e.mime !== "application/pdf" || !H(e.bytes)) throw N("a print takes PDF bytes or a handle");
218
+ n = new Uint8Array(e.bytes.slice(0));
219
+ }
220
+ const a = typeof e.title == "string" ? e.title : "";
221
+ return { printed: await l(() => t.print({ bytes: n, title: a })) === !0 };
222
+ }, Y = async (e) => {
223
+ const n = [];
224
+ let a = 0;
225
+ for (; ; ) {
226
+ const { bytes: h, size: S } = await l(() => r.read(e, a, void 0));
227
+ if (n.push(new Uint8Array(h)), a += h.byteLength, a >= S || h.byteLength === 0) break;
228
+ }
229
+ const f = new Uint8Array(a);
230
+ let d = 0;
231
+ for (const h of n)
232
+ f.set(h, d), d += h.byteLength;
233
+ return f;
234
+ }, X = {
235
+ "files/pick": o,
236
+ "files/create": p,
237
+ "files/stat": async ({ handle: e }) => {
238
+ const n = v(e);
239
+ if (n.rights.includes("create") && !n.committed && n.kind === "file") return w(n);
240
+ const a = await l(() => r.stat(n.ref));
241
+ if (!a) throw m("file-not-granted", "the file is gone");
242
+ return Object.assign(n, { version: a.version, size: a.size, mime: a.mime ?? n.mime }), w(n);
243
+ },
244
+ "files/read": R,
245
+ "files/list": T,
246
+ "files/write": U,
247
+ "files/release": D,
248
+ "files/print": V
249
+ };
250
+ return {
251
+ id: i,
252
+ capabilities: $,
253
+ grant: async (e, n, { flow: a, approved: f }) => {
254
+ if (k) throw m("file-not-granted", "the session has ended");
255
+ const d = await l(() => r.stat(e)), h = c(e);
256
+ if (n.includes("write")) {
257
+ if (t.readOnly) throw m("not-allowed", "a read-only session replaces no file");
258
+ if (a === "agent" && f !== !0) throw m("not-allowed", "an agent replaces a file only through a draft or the person's approval");
259
+ if (d?.kind !== "file") throw m("not-allowed", "there is no such file to replace");
260
+ y(h);
261
+ }
262
+ if (n.includes("read")) {
263
+ if (!d) throw m("not-allowed", "there is no such file");
264
+ if (d.kind === "file") P(h);
265
+ else if (!s.folders) throw m("not-allowed", "the kit may not read folders");
266
+ }
267
+ if (n.includes("create") && (!d || d.kind === "file")) {
268
+ if (d) throw m("not-allowed", "a create grant never names an existing file");
269
+ y(h);
270
+ }
271
+ return w(E(e, d, [...new Set(n)], a, d?.kind === "folder" ? { accept: s.read } : {}));
272
+ },
273
+ revoke: async (e) => {
274
+ const n = [];
275
+ for (const a of e) {
276
+ const f = g.get(a);
277
+ f && (await O(f), n.push(a));
278
+ }
279
+ n.length && t.revoked?.(n);
280
+ },
281
+ grants: () => [...g.values()].map(({ handle: e, session: n, kit: a, principal: f, flow: d, rights: h, kind: S, name: x }) => ({ handle: e, session: n, kit: a, principal: f, flow: d, rights: [...h], kind: S, name: x })),
282
+ serve: async (e, n) => {
283
+ if (t.trace?.(e, n), k) throw m("file-not-granted", "the session has ended");
284
+ return X[e](n);
285
+ },
286
+ end: async () => {
287
+ k = !0;
288
+ for (const e of [...g.values()]) await O(e);
289
+ }
290
+ };
291
+ }
292
+ function K(t) {
293
+ if (/^([A-Za-z]:)?[\\/]/.test(t)) return null;
294
+ const r = [];
295
+ for (const i of t.replace(/\\/g, "/").split("/"))
296
+ if (!(!i || i === "."))
297
+ if (i === "..") {
298
+ if (!r.length) return null;
299
+ r.pop();
300
+ } else r.push(i);
301
+ return r.length ? r.join("/") : null;
302
+ }
303
+ function Se(t, r, i) {
304
+ const s = K(t), c = [];
305
+ for (const u of i) {
306
+ const g = typeof u?.path == "string" ? K(u.path) : null;
307
+ if (!g || g === s || g.split("/").some((w) => w.startsWith("."))) continue;
308
+ const k = g.split("/").pop(), q = k.includes(".") ? k.slice(k.lastIndexOf(".") + 1).toLowerCase() : "";
309
+ if (!r.accept.includes(q)) continue;
310
+ const $ = { path: oe(t, g), name: k, version: typeof u.version == "string" ? u.version : null };
311
+ if (c.some((w) => w.path === $.path) || c.push($), !r.multiple) break;
312
+ }
313
+ return c;
314
+ }
315
+ function A(t) {
316
+ throw new b(-32601, `${t} is not supported by this host`);
317
+ }
318
+ function Ie(t, r) {
319
+ const { handlers: i } = r, s = { agent: i.openAgent, "pick-file": i.pick, replica: i.replicaRead && i.replicaWrite, customize: i.customize, lease: i.leases, presence: i.presence }, c = Object.entries(s).filter(([, w]) => w).map(([w]) => w);
320
+ i.generate && c.push("generate"), i.open && c.push("open-file"), i.openUrl && c.push("open-url");
321
+ const u = r.document.readOnly === !0;
322
+ i.pickLinks && !u && c.push("links-pick"), i.fetchImage && !u && c.push("fetch-image");
323
+ const g = Object.entries(i.actions ?? {}).filter(([, w]) => typeof w == "function");
324
+ c.push(...g.map(([w]) => `${te}${w}`));
325
+ const k = Object.entries(i.services ?? {}).filter(([w, E]) => typeof E == "function" && ne.includes(w) && ie(w, r.document));
326
+ c.push(...k.map(([w]) => `${se}${w}`)), i.comments && c.push("comment-anchors"), r.files && c.push("files", ...r.files.pick ? ["files-pick"] : [], ...r.files.print ? ["print"] : []);
327
+ const q = r.timeoutMs ?? 12e4, $ = (w, E) => {
328
+ const v = new MessageChannel(), l = new ae(v.port1, "h");
329
+ let O = null;
330
+ l.handle("host/read", (o) => i.read(o)), l.handle("host/stamp", (o) => i.stamp(o)), l.handle("host/write", (o) => i.write(o)), l.handle("host/pick", (o) => i.pick ? i.pick(o) : A("host/pick")), l.handle("host/openAgent", async (o) => (i.openAgent || A("host/openAgent"), await i.openAgent(o), {}));
331
+ const { replicaRead: I, replicaWrite: L } = i;
332
+ l.handle("host/replicaRead", (o) => I && L ? I(o) : A("host/replicaRead")), l.handle("host/replicaWrite", async (o) => ((!I || !L) && A("host/replicaWrite"), await L(o), {})), l.handle("host/customize", async (o) => (i.customize || A("host/customize"), await i.customize(o), {})), l.handle("host/leaseAcquire", (o) => i.leases ? i.leases.acquire(o) : A("host/leaseAcquire")), l.handle("host/leaseRelease", async (o) => (i.leases || A("host/leaseRelease"), await i.leases.release(o), {})), l.handle("host/leases", async () => (i.leases || A("host/leases"), { leases: await i.leases.list() })), l.handle("host/generate", (o) => {
333
+ if (i.generate || A("host/generate"), !ce(o?.purpose, O)) throw new b(-32e3, `a kit may not generate for ${JSON.stringify(o?.purpose)}`, { reason: "not-allowed" });
334
+ return i.generate(o);
335
+ }), l.handle("host/action", (o) => {
336
+ const p = typeof o?.id == "string" ? g.find(([R]) => R === o.id)?.[1] : void 0;
337
+ if (!p) throw new b(-32e3, `this host does not serve the action ${String(o?.id)}`, { reason: "not-allowed" });
338
+ return p(o.params && typeof o.params == "object" ? o.params : {});
339
+ }), l.handle("host/open", async (o) => {
340
+ i.open || A("host/open");
341
+ const p = le(o);
342
+ if (!p) throw new b(-32602, "host/open needs a link with a path, a name, or a docId");
343
+ return { opened: (await i.open(p))?.opened !== !1 };
344
+ }), l.handle("host/openUrl", async (o) => {
345
+ if (i.openUrl || A("host/openUrl"), !de(o?.url)) throw new b(-32e3, "a host opens only https:, http:, and mailto: addresses", { reason: "not-allowed" });
346
+ return { opened: (await i.openUrl({ url: o.url }))?.opened !== !1 };
347
+ }), l.handle("host/fetchImage", async (o) => {
348
+ if (i.fetchImage || A("host/fetchImage"), u) throw new b(-32e3, "a read-only document fetches no pictures", { reason: "read-only" });
349
+ if (!fe(o?.url)) throw new b(-32e3, "a host fetches only https: and http: addresses", { reason: "not-allowed" });
350
+ const p = await i.fetchImage({ url: o.url });
351
+ if (!(p?.bytes instanceof ArrayBuffer) || !ue.includes(p.mime)) throw new b(-32e3, `${o.url} is not a picture`, { reason: "unsupported" });
352
+ return { bytes: p.bytes, mime: p.mime };
353
+ }), l.handle("links/pick", async (o) => {
354
+ if (i.pickLinks || A("links/pick"), u) throw new b(-32e3, "a read-only document links no files", { reason: "read-only" });
355
+ const p = he(o);
356
+ if (!p) throw new b(-32602, "links/pick needs a purpose and at least one extension without the dot");
357
+ return { links: Se(r.document.path, p, await i.pickLinks(p) ?? []) };
358
+ });
359
+ const P = r.files ? Re({ ...r.files, readOnly: u, revoked: (o) => l.notify("files/revoked", { handles: o }) }) : null;
360
+ if (P) for (const o of Ee) l.handle(o, (p) => P.serve(o, p));
361
+ l.on("document/conflicts", (o) => i.conflicts?.(o)), l.on("document/schema", (o) => {
362
+ const p = pe(o);
363
+ p && i.schema?.(p);
364
+ }), l.on("draft/changed", (o) => i.draftChanged?.(o)), l.on("presence/set", (o) => {
365
+ const p = j(o);
366
+ p && i.presence?.(p);
367
+ }), l.on("document/changed", (o) => i.changed(o)), l.on("replica/changed", (o) => i.replicaChanged?.(o)), l.on("host/notify", (o) => i.notify?.(o)), l.on("host/shortcut", (o) => i.shortcut?.(o)), l.on("ui/action", (o) => i.action?.(o)), l.handle("host/service", (o) => {
368
+ const p = o?.service, R = k.find(([U]) => U === p)?.[1];
369
+ if (!R) throw new b(-32e3, `this host does not serve ${String(p)}`, { reason: "not-allowed" });
370
+ const T = me(o);
371
+ if (!T) throw new b(-32602, `bad params for ${String(p)}`);
372
+ return R(T.params);
373
+ }), l.on("comments/activated", (o) => {
374
+ typeof o?.id == "string" && o.id && i.comments?.activated(o.id);
375
+ }), w.postMessage({ kitionKitUi: 1, protocol: z, id: E }, r.origin, [v.port2]);
376
+ const y = { ...r.document, bytes: r.document.bytes?.slice(0) }, _ = l.request(
377
+ "ui/initialize",
378
+ { protocol: z, host: r.host, document: y, theme: r.theme, locale: r.locale, shortcuts: r.shortcuts, capabilities: c, capabilitySets: r.capabilitySets ?? [], ui: r.ui },
379
+ { transfer: !0 }
380
+ );
381
+ return _.then(
382
+ (o) => {
383
+ O = typeof o?.kit?.id == "string" ? o.kit.id : null;
384
+ },
385
+ () => {
386
+ }
387
+ ), { peer: l, files: P, initialized: _ };
388
+ };
389
+ return new Promise((w, E) => {
390
+ let v = null;
391
+ const l = (y) => {
392
+ y?.peer.close(), y?.files?.end();
393
+ }, O = () => {
394
+ clearTimeout(L), window.removeEventListener("message", P), r.signal?.removeEventListener("abort", I);
395
+ }, I = () => {
396
+ O(), l(v), E(new Error("the kit mount was abandoned"));
397
+ };
398
+ if (r.signal?.aborted) {
399
+ E(new Error("the kit mount was abandoned"));
400
+ return;
401
+ }
402
+ r.signal?.addEventListener("abort", I);
403
+ const L = setTimeout(() => {
404
+ O(), l(v), E(new Error("the kit did not open the document in time"));
405
+ }, q), P = (y) => {
406
+ if (y.source !== t.contentWindow || !re(y.data) || y.data.ready !== z || r.origin !== "*" && y.origin !== r.origin || v?.id === y.data.id) return;
407
+ l(v);
408
+ const { peer: _, files: o, initialized: p } = $(y.source, y.data.id);
409
+ v = { peer: _, files: o, id: y.data.id }, p.then(
410
+ (R) => {
411
+ v?.peer === _ && (O(), w(Ae(_, R, o)));
412
+ },
413
+ (R) => {
414
+ v?.peer === _ && (O(), o?.end(), E(R instanceof Error ? R : new Error(String(R))));
415
+ }
416
+ );
417
+ };
418
+ window.addEventListener("message", P), t.contentWindow?.postMessage({ kitionKitUi: 1, hello: z }, r.origin);
419
+ });
420
+ }
421
+ function Ae(t, r, i) {
422
+ return {
423
+ kit: r.kit,
424
+ capabilities: r.capabilities,
425
+ state: () => t.request("document/state", {}),
426
+ save: () => t.request("document/save", {}),
427
+ fileChanged: (s) => t.notify("document/fileChanged", { version: s }),
428
+ fileHeld: (s) => t.notify("document/held", { version: s }),
429
+ setTheme: (s) => t.notify("ui/theme", { theme: s }),
430
+ setLocale: (s) => t.notify("ui/locale", { locale: s }),
431
+ focus: () => t.notify("ui/focus", {}),
432
+ configure: (s) => t.notify("ui/configure", { ui: s }),
433
+ leasesChanged: (s) => t.notify("lease/changed", { leases: s }),
434
+ peersChanged: (s) => t.notify("presence/peers", { peers: s }),
435
+ reveal: (s) => t.notify("document/reveal", { view: s }),
436
+ showComments: (s) => {
437
+ const c = s.flatMap((u) => {
438
+ const g = we(u.anchor);
439
+ return g && typeof u.id == "string" ? [{ id: u.id, anchor: g, resolved: u.resolved === !0, count: Number.isSafeInteger(u.count) ? u.count : 0 }] : [];
440
+ });
441
+ t.notify("comments/show", { threads: c });
442
+ },
443
+ locateComments: async (s) => {
444
+ if (!r.capabilities.includes("comment-anchors")) return s.map(() => !1);
445
+ const { found: c } = await t.request("comments/locate", { anchors: s });
446
+ return s.map((u, g) => c?.[g] === !0);
447
+ },
448
+ onPresence: (s) => t.on("presence/set", (c) => {
449
+ const u = j(c);
450
+ u && s(u);
451
+ }),
452
+ elements: () => t.request("ui/elements", {}),
453
+ check: async (s) => r.capabilities.includes("check") ? (await t.request("document/check", s?.draft ? { draft: !0 } : {})).diagnostics : [],
454
+ ai: {
455
+ inspect: (s) => t.request("ai/inspect", s ?? {}),
456
+ commands: (s) => t.request("ai/commands", { query: s }),
457
+ run: (s, c, u) => t.request("ai/run", {
458
+ steps: s,
459
+ save: c,
460
+ ...u?.draft ? { draft: !0 } : {},
461
+ ...u?.origin ? { origin: u.origin } : {},
462
+ ...u?.originLabel != null ? { originLabel: u.originLabel } : {}
463
+ }),
464
+ preview: (s, c) => t.request("ai/preview", c?.draft ? { maxSize: s, draft: !0 } : { maxSize: s }),
465
+ version: async () => (await t.request("ai/version", {})).version,
466
+ premise: (s, c) => t.request("ai/premise", { method: s, params: c }),
467
+ changes: (s, c) => t.request("ai/changes", c ? { since: s, schema: c } : { since: s })
468
+ },
469
+ draft: {
470
+ state: () => t.request("draft/state", {}),
471
+ ready: () => t.request("draft/ready", {}),
472
+ reopen: () => t.request("draft/reopen", {}),
473
+ compare: (s) => t.request("draft/compare", s ?? {}),
474
+ merge: (s, c) => t.request("draft/merge", c ? { origin: s, schema: c } : { origin: s }),
475
+ discard: () => t.request("draft/discard", {})
476
+ },
477
+ replica: {
478
+ version: async () => (await t.request("replica/version", {})).version,
479
+ exportChanges: (s) => t.request("replica/export", { since: s }),
480
+ importChanges: (s, c) => t.request("replica/import", { changes: s, blobs: c }),
481
+ info: async () => (await t.request("replica/info", {})).docId,
482
+ onChanged: (s) => t.on("replica/changed", (c) => s(c.version))
483
+ },
484
+ model: {
485
+ describe: (s) => t.request("model/describe", s ? { schema: s } : {}),
486
+ batch: (s) => t.request("model/batch", s)
487
+ },
488
+ files: i && { grant: i.grant, revoke: i.revoke, grants: i.grants },
489
+ close: () => {
490
+ t.close(), i?.end();
491
+ }
492
+ };
493
+ }
494
+ export {
495
+ Le as ACTION_ERROR_REASONS,
496
+ Pe as FETCH_IMAGE_ERROR_REASONS,
497
+ Ce as FETCH_IMAGE_TYPES,
498
+ Ee as FILES_METHODS,
499
+ Ne as GENERATE_ERROR_REASONS,
500
+ $e as GENERATE_PURPOSES,
501
+ Te as HOST_SERVICES,
502
+ ze as KIT_UI_PROTOCOL,
503
+ Ue as KitRpcError,
504
+ xe as LEASE_HELD_REASON,
505
+ Fe as OPEN_ERROR_REASONS,
506
+ He as OPEN_URL_SCHEMES,
507
+ Me as SERVICE_ERROR_REASONS,
508
+ C as extensionOf,
509
+ Ge as fetchImageErrorReason,
510
+ m as fileError,
511
+ Ke as fileErrorReason,
512
+ We as hostRequestErrorReason,
513
+ je as isFetchableUrl,
514
+ Be as isGeneratePurpose,
515
+ De as isOpenableUrl,
516
+ Ve as linkPathFrom,
517
+ Ie as mountKit,
518
+ Ye as openErrorReason,
519
+ Re as openFileSession,
520
+ Xe as parseCommentAnchor,
521
+ Je as parseKitView,
522
+ Ze as parseLinkRef,
523
+ Qe as parseLinksPickParams,
524
+ et as parseOpenParams,
525
+ tt as parseServiceParams,
526
+ Se as pickedLinks,
527
+ M as sanitizeFileName,
528
+ nt as serviceAllowed,
529
+ ye as unusedName
530
+ };
@@ -0,0 +1,163 @@
1
+ /**
2
+ * The host's side of KitFiles 1.0 (Kition platform `docs/platform/sets/files.md`; Kit UI protocol section
3
+ * 7g): a session's grant table (handle → session, kit, principal, rights, kind), the `files/*`
4
+ * requests served from it with the host's own storage, staged writes, and names that never
5
+ * replace a file. The host's storage speaks in its own references (`KitFileRef`, such as a
6
+ * workspace path); they never leave this module: the kit sees only handles and display names
7
+ * (FA-P2, UI-F1).
8
+ */
9
+ import { KitRpcError, type KitFileErrorReason, type KitFileRight, type KitFileStat, type KitFilesPickParams, type KitToHost } from '@kition/kit-ui-protocol';
10
+ /** The host's own name for a file or folder (a workspace path). The kit never sees it. */
11
+ export type KitFileRef = string;
12
+ /** A file or folder as the host's storage sees it now. */
13
+ export type KitFileEntry = {
14
+ kind: 'file' | 'folder';
15
+ size?: number;
16
+ mime?: string;
17
+ version: string | null;
18
+ };
19
+ /** A write in progress, kept by the storage (a temporary file) until it commits or is aborted. */
20
+ export type KitFileStaging = {
21
+ append: (bytes: Uint8Array) => Promise<void>;
22
+ /** Commits atomically (temporary file, then rename, H4), as `commit` does with the staged bytes. */
23
+ commit: () => Promise<{
24
+ version: string;
25
+ }>;
26
+ abort: () => Promise<void>;
27
+ };
28
+ /** How a staged write commits: a new file (never an existing one), or a replacement of the version the kit read. */
29
+ export type KitFileCommitMode = {
30
+ mode: 'create';
31
+ } | {
32
+ mode: 'replace';
33
+ expected: string;
34
+ };
35
+ /**
36
+ * The host's storage, in its own references. Every answer about a file the kit may not see (outside
37
+ * the workspace, the host's own data, a hidden path; H3, LR2, FA8) is the same as for a missing file.
38
+ */
39
+ export type KitFilesStorage = {
40
+ /** The file or folder at `ref`; `null` when there is none or the kit may not see it. */
41
+ stat: (ref: KitFileRef) => KitFileEntry | null | Promise<KitFileEntry | null>;
42
+ /** At most `length` bytes from `offset` (to the end without `length`); `size` is the whole file's. */
43
+ read: (ref: KitFileRef, offset: number, length: number | undefined) => Promise<{
44
+ bytes: ArrayBuffer;
45
+ version: string;
46
+ size: number;
47
+ }>;
48
+ /** A folder's entries, not recursively. */
49
+ list: (ref: KitFileRef) => KitFileRef[] | Promise<KitFileRef[]>;
50
+ /** The reference of `name` in `folder`; `null` is the document's own folder. */
51
+ child: (folder: KitFileRef | null, name: string) => KitFileRef;
52
+ /** The display name of `ref`: its last segment. Default: what follows the last `/` or `\`. */
53
+ name?: (ref: KitFileRef) => string;
54
+ /**
55
+ * Puts `bytes` at `ref` atomically. `create` MUST refuse a file that exists (throw `fileError('conflict')`);
56
+ * `replace` MUST refuse unless the file's version is still `expected` (`conflict`).
57
+ */
58
+ commit: (ref: KitFileRef, bytes: Uint8Array, mode: KitFileCommitMode) => Promise<{
59
+ version: string;
60
+ }>;
61
+ /** Stages a write elsewhere than in memory (a temporary file), for exports of any length. Absent: staged in memory, then `commit`. */
62
+ stage?: (ref: KitFileRef, mode: () => KitFileCommitMode) => KitFileStaging;
63
+ /** The file is open with unsaved edits in an editor (FA14). */
64
+ unsaved?: (ref: KitFileRef) => boolean | Promise<boolean>;
65
+ };
66
+ /** What a kit may ask for, from its manifest's `files` (K15): extensions without the dot. */
67
+ export type KitFilesManifest = {
68
+ read?: string[];
69
+ create?: string[];
70
+ folders?: boolean;
71
+ print?: boolean;
72
+ };
73
+ /** How a handle was granted (KitFiles section 3), for the grant log. */
74
+ export type KitFileGrantFlow = 'pick' | 'create' | 'list' | 'agent' | 'drop';
75
+ /** One grant, as the host records it in its session log (section 7, A10, A30) and shows it (FA16). */
76
+ export type KitFileGrant = {
77
+ handle: string;
78
+ session: string;
79
+ kit: string;
80
+ principal: string;
81
+ flow: KitFileGrantFlow;
82
+ rights: KitFileRight[];
83
+ kind: 'file' | 'folder';
84
+ name: string;
85
+ };
86
+ export type KitFilesOptions = {
87
+ storage: KitFilesStorage;
88
+ /** The kit's id, and the person (or the person an agent runs for) the handles are bound to (FA1). */
89
+ kit: string;
90
+ principal: string;
91
+ /** The kit manifest's `files` lists (K15). Absent: the kit asked for nothing, and every grant is refused. */
92
+ manifest?: KitFilesManifest;
93
+ /** The host's picker (capability `files-pick`): answers the references the person chose, none when they cancel. */
94
+ pick?: (params: KitFilesPickParams) => Promise<KitFileRef[]>;
95
+ /** The system's print dialog (capability `print`): answers whether the person printed. */
96
+ print?: (job: {
97
+ bytes: Uint8Array;
98
+ title: string;
99
+ }) => Promise<boolean>;
100
+ /**
101
+ * Whether the person just made a gesture in the kit (FA6, FA11). Default: the page's transient
102
+ * user activation, which a click in the kit's frame gives its parent too; true where the browser
103
+ * does not tell.
104
+ */
105
+ gesture?: () => boolean;
106
+ /** Caps on the bytes written per grant and per session (FA10). */
107
+ quota?: {
108
+ perGrant?: number;
109
+ perSession?: number;
110
+ };
111
+ /** Every grant, for the host's session log. */
112
+ log?: (grant: KitFileGrant) => void;
113
+ /** Every `files/*` request the kit sends, before it is served (`@kition/kit-dev-host`'s `checkNoPaths`). */
114
+ trace?: (method: string, params: unknown) => void;
115
+ };
116
+ /** A `files/*` refusal: `-32000` with `error.data.reason` (KitFiles section 10). */
117
+ export declare function fileError(reason: KitFileErrorReason, message: string): KitRpcError;
118
+ /** The extension of a name, lower case, without the dot; empty when it has none. */
119
+ export declare function extensionOf(name: string): string;
120
+ /**
121
+ * A name the host may create (FA15): the last segment only, no control characters or characters
122
+ * the platforms reserve, no leading dot, no trailing dot or space, no reserved device name
123
+ * (`CON`, `NUL` on Windows), at most 255 characters; `Untitled` when nothing is left.
124
+ */
125
+ export declare function sanitizeFileName(suggested: string): string;
126
+ /** `Report.pdf`, then `Report 2.pdf`, `Report 3.pdf`, …: the first name `taken` says is free (FA7). */
127
+ export declare function unusedName(name: string, taken: (candidate: string) => boolean | Promise<boolean>): Promise<string>;
128
+ /** One kit session's file grants and the `files/*` requests served from them. */
129
+ export type KitFileSession = {
130
+ /** This session's id (FA1). */
131
+ id: string;
132
+ /** The capabilities to list in `ui/initialize`: `files`, and `files-pick` and `print` when the host has them. */
133
+ capabilities: string[];
134
+ /**
135
+ * Grants a handle on a file the host chose (an agent's `file` parameter, A28; a drop): the same
136
+ * policy as the kit's own requests. A `write` grant from an agent needs `approved` (a draft beside
137
+ * the file, or the person's explicit approval; FA13), and no session that is read-only gets one (FA17).
138
+ * The document the agent's tool call targets is never granted here: saving it is editing it
139
+ * (`host/write`, A7, A12), not replacing a file under FA13.
140
+ */
141
+ grant: (ref: KitFileRef, rights: KitFileRight[], options: {
142
+ flow: 'agent' | 'drop';
143
+ approved?: boolean;
144
+ }) => Promise<KitFileStat>;
145
+ /** Revokes handles early (FA4, FA16) and tells the kit (`files/revoked`). */
146
+ revoke: (handles: string[]) => Promise<void>;
147
+ /** What this session holds now (FA16). */
148
+ grants: () => KitFileGrant[];
149
+ /** Serves a `files/*` request from the kit. */
150
+ serve: <M extends FilesMethod>(method: M, params: KitToHost[M][0]) => Promise<KitToHost[M][1]>;
151
+ /** The session ended (the frame closed): every handle expires and staged writes are dropped (FA4, FA9). */
152
+ end: () => Promise<void>;
153
+ };
154
+ export type FilesMethod = 'files/pick' | 'files/create' | 'files/stat' | 'files/read' | 'files/list' | 'files/write' | 'files/release' | 'files/print';
155
+ export declare const FILES_METHODS: FilesMethod[];
156
+ /**
157
+ * Opens one kit session's grant table. `readOnly` is the document's (UI-K7, FA17); `revoked` tells
158
+ * the kit of handles revoked early.
159
+ */
160
+ export declare function openFileSession(options: KitFilesOptions & {
161
+ readOnly?: boolean;
162
+ revoked?: (handles: string[]) => void;
163
+ }): KitFileSession;
@@ -0,0 +1,315 @@
1
+ /**
2
+ * The host's side of the Kit UI protocol (Kition platform docs/platform/reference/ui-protocol.md): mount an embedded kit UI in an
3
+ * iframe, hand it its port, initialize it with the document, theme, and locale, and serve its
4
+ * file calls with the host's own handlers. Framework-free.
5
+ */
6
+ import { KIT_UI_PROTOCOL, KitRpcError, LEASE_HELD_REASON, type AiRunParams, type AiRunResult, type AiStep, type DocumentState, type InitializeResult, type KitConflict, type KitDocumentInit, type KitLease, type KitLinksPickParams, type KitNotifications, type KitPeerPresence, type KitPresence, type KitPresenceCaret, type KitSchemaReport, type KitTheme, type KitToHost, type KitUiConfig, type KitUiElement, type KitView, type DraftComparison, type DraftInfo, type DraftOrigin, type DraftSummary, type ModelBatchParams, type ModelBatchResult, type StoredReplica, type KitDiagnostic, type KitCommentAnchor, type KitHostService, type KitHostServices, type KitShownThread } from '@kition/kit-ui-protocol';
7
+ import { type KitFileSession, type KitFilesOptions } from './files.js';
8
+ export { KIT_UI_PROTOCOL, KitRpcError, LEASE_HELD_REASON };
9
+ export { fileErrorReason, hostRequestErrorReason, isGeneratePurpose, ACTION_ERROR_REASONS, GENERATE_ERROR_REASONS, GENERATE_PURPOSES } from '@kition/kit-ui-protocol';
10
+ export { extensionOf, fileError, openFileSession, sanitizeFileName, unusedName, FILES_METHODS } from './files.js';
11
+ export type { FilesMethod, KitFileCommitMode, KitFileEntry, KitFileGrant, KitFileGrantFlow, KitFileRef, KitFileSession, KitFileStaging, KitFilesManifest, KitFilesOptions, KitFilesStorage } from './files.js';
12
+ export type { KitFileErrorReason, KitFileRight, KitFileStat, KitFilesPickParams } from '@kition/kit-ui-protocol';
13
+ export type { KitActionErrorReason, KitActionParams, KitActionResult, KitDefinedGeneratePurpose, KitGenerateErrorReason, KitGenerateMessage, KitGenerateParams, KitGeneratePart, KitGeneratePurpose, KitGenerateResult } from '@kition/kit-ui-protocol';
14
+ export type { KitView } from '@kition/kit-ui-protocol';
15
+ export { parseKitView } from '@kition/kit-ui-protocol';
16
+ export { HOST_SERVICES, SERVICE_ERROR_REASONS, parseCommentAnchor, parseServiceParams, serviceAllowed } from '@kition/kit-ui-protocol';
17
+ export type { KitCommentAnchor, KitHostService, KitHostServices, KitPerson, KitServiceErrorReason, KitServiceParams, KitServiceResult, KitShownThread } from '@kition/kit-ui-protocol';
18
+ export type { KitLinkRef, KitLinksPickParams, KitOpenErrorReason, KitOpenParams, KitOpenResult, KitPickedLink } from '@kition/kit-ui-protocol';
19
+ export { isOpenableUrl, linkPathFrom, openErrorReason, parseLinkRef, parseLinksPickParams, parseOpenParams, OPEN_ERROR_REASONS, OPEN_URL_SCHEMES } from '@kition/kit-ui-protocol';
20
+ export type { KitFetchImageErrorReason, KitFetchImageResult, KitFetchImageType } from '@kition/kit-ui-protocol';
21
+ export { FETCH_IMAGE_ERROR_REASONS, FETCH_IMAGE_TYPES, fetchImageErrorReason, isFetchableUrl } from '@kition/kit-ui-protocol';
22
+ export type { DocumentState, DraftComparison, DraftInfo, DraftOrigin, DraftSummary, InitializeResult, KitConflict, KitDocumentInit, KitLease, KitPeerPresence, KitPresence, KitPresenceCaret, KitSchemaReport, KitTheme, KitUiConfig, KitUiElement, ModelBatchParams, ModelBatchResult, StoredReplica };
23
+ type Params<M extends keyof KitToHost> = KitToHost[M][0];
24
+ type Result<M extends keyof KitToHost> = KitToHost[M][1] | Promise<KitToHost[M][1]>;
25
+ /** What the host does for the kit. Every path is workspace-relative; the host checks it (UI-H2). */
26
+ export type KitHostHandlers = {
27
+ read: (params: Params<'host/read'>) => Result<'host/read'>;
28
+ stamp: (params: Params<'host/stamp'>) => Result<'host/stamp'>;
29
+ write: (params: Params<'host/write'>) => Result<'host/write'>;
30
+ pick?: (params: Params<'host/pick'>) => Result<'host/pick'>;
31
+ openAgent?: (params: Params<'host/openAgent'>) => void | Promise<void>;
32
+ /**
33
+ * The document's stored replica and its keeping (capability `replica`, with `replicaWrite`):
34
+ * `null` when none is stored. The kit decides whether it still belongs to the file.
35
+ */
36
+ replicaRead?: (params: Params<'host/replicaRead'>) => Result<'host/replicaRead'>;
37
+ replicaWrite?: (params: Params<'host/replicaWrite'>) => void | Promise<void>;
38
+ /** `replica/changed`: the replica's version after an edit, for collaboration. */
39
+ replicaChanged?: (params: KitNotifications['replica/changed']) => void;
40
+ /** `document/changed`: show the unsaved mark, tell the agent. */
41
+ changed: (state: KitNotifications['document/changed']) => void;
42
+ notify?: (notice: KitNotifications['host/notify']) => void;
43
+ /** A host shortcut pressed inside the kit (UI-K5). */
44
+ shortcut?: (key: KitNotifications['host/shortcut']) => void;
45
+ /** `host/customize`: keep the person's hides for this kit (capability `customize`, section 9). */
46
+ customize?: (params: Params<'host/customize'>) => void | Promise<void>;
47
+ /** `ui/action`: one of the host's buttons was pressed. */
48
+ action?: (params: KitNotifications['ui/action']) => void;
49
+ /**
50
+ * Leases on the document's scopes (capability `lease`, section 7b): `acquire` takes or renews
51
+ * one and keeps it until `release` (or the kit closes, when the host releases what it still
52
+ * holds for it); answers `{ lease: null }` when nobody is there to coordinate with. A refusal
53
+ * throws a `KitRpcError` whose `data` is `{ reason: 'held', lease }` (or `{ reason: 'read-only' }`).
54
+ * `list` is the document's leases now; `KitConnection.leasesChanged` tells the kit of changes.
55
+ */
56
+ leases?: {
57
+ acquire: (params: Params<'host/leaseAcquire'>) => Result<'host/leaseAcquire'>;
58
+ release: (params: Params<'host/leaseRelease'>) => void | Promise<void>;
59
+ list: () => KitLease[] | Promise<KitLease[]>;
60
+ };
61
+ /** `document/conflicts`: the document's unresolved conflict objects (section 7c). */
62
+ conflicts?: (params: KitNotifications['document/conflicts']) => void;
63
+ /**
64
+ * `document/schema`: a newer kit edited the document (section 7f; KitModel rule M5a),
65
+ * checked. The host tells the person and offers the update, without blocking editing.
66
+ */
67
+ schema?: (params: KitNotifications['document/schema']) => void;
68
+ /** `draft/changed`: the agent's draft opened, changed, became ready, or closed (section 7d). */
69
+ draftChanged?: (params: KitNotifications['draft/changed']) => void;
70
+ /**
71
+ * `presence/set`: what the person shares with the other people in the document (capability
72
+ * `presence`, section 7e), checked; the host relays it to them. `KitConnection.peersChanged`
73
+ * tells the kit what they share.
74
+ */
75
+ presence?: (presence: KitPresence) => void;
76
+ /**
77
+ * `host/generate`: run a model for the kit with the person's settings (capability `generate`,
78
+ * section 7j). Refuse with a `KitRpcError(-32000, …, { reason })`, `reason` one of
79
+ * `GENERATE_ERROR_REASONS`. Never give the kit a key or an endpoint (UI-G2). A purpose that is
80
+ * neither defined nor the kit's own (`isGeneratePurpose`) is refused as `not-allowed` before
81
+ * it gets here; the host MAY refuse a kit's own purpose too, and serves every defined one.
82
+ */
83
+ generate?: (params: Params<'host/generate'>) => Result<'host/generate'>;
84
+ /**
85
+ * `host/action`: the host's actions by id, each listed as capability `action:<id>` (section
86
+ * 7j), such as `workflow.run` and `design.fromRecord`. An id the host does not serve is refused
87
+ * with reason `not-allowed`.
88
+ */
89
+ actions?: Record<string, (params: Record<string, unknown>) => Result<'host/action'>>;
90
+ /**
91
+ * `host/service`: the host's services by id (minor version 2.6, section 7k; managed co-editing
92
+ * D4), each listed as capability `service:<id>`. Params arrive checked (`parseServiceParams`,
93
+ * UI-V3); a service not served is refused `not-allowed`.
94
+ */
95
+ services?: {
96
+ [S in KitHostService]?: (params: KitHostServices[S][0]) => KitHostServices[S][1] | Promise<KitHostServices[S][1]>;
97
+ };
98
+ /**
99
+ * The host keeps comment threads itself (capability `comment-anchors`, section 7k):
100
+ * `activated` hears the person click a thread's marker in the kit. Show threads with
101
+ * `KitConnection.showComments`.
102
+ */
103
+ comments?: {
104
+ activated: (id: string) => void;
105
+ };
106
+ /**
107
+ * `host/open`: open a workspace file in the host (capability `open-file`, section 7i; KitLinks
108
+ * 1.0 OP1 to OP5), with its `view` (OP3), creating a missing one when asked (OP4). The params
109
+ * arrive checked (`parseOpenParams`); the host resolves the link against the document's folder,
110
+ * keeps it inside the workspace (UI-H2), and refuses with a `KitRpcError(-32000, …, { reason })`,
111
+ * `reason` one of `OPEN_ERROR_REASONS`.
112
+ */
113
+ open?: (params: Params<'host/open'>) => Result<'host/open'>;
114
+ /**
115
+ * `host/openUrl`: open a web address in the system's browser or mail client after the person
116
+ * confirmed it (capability `open-url`; OP6 to OP9). Only `https:`, `http:`, and `mailto:` reach
117
+ * it: others are refused as `not-allowed` before (OP7).
118
+ */
119
+ openUrl?: (params: Params<'host/openUrl'>) => Result<'host/openUrl'>;
120
+ /**
121
+ * `host/fetchImage`: download a picture the person pasted or dropped by its web address
122
+ * (capability `fetch-image`, section 7l), from public addresses only: never the person's
123
+ * computer or local network, at every redirect. Only `https:` and `http:` reach it, and only
124
+ * for a document the kit may edit; an answer whose `mime` is not in `FETCH_IMAGE_TYPES` is
125
+ * refused as `unsupported`. Refuse with `KitRpcError(-32000, …, { reason })`, `reason` one of
126
+ * `FETCH_IMAGE_ERROR_REASONS`.
127
+ */
128
+ fetchImage?: (params: Params<'host/fetchImage'>) => Result<'host/fetchImage'>;
129
+ /**
130
+ * `links/pick`: the host's chooser of existing workspace files to link (capability `links-pick`,
131
+ * section 7i; UI-N2 to UI-N4), never copied. The params arrive checked (`parseLinksPickParams`);
132
+ * the handler answers the chosen files' workspace paths and versions (none when the person
133
+ * cancels), and `mountKit` turns them into document-relative links, leaving out hidden paths,
134
+ * the document itself, and files outside `accept`. Not listed, and refused as `read-only`, for
135
+ * a read-only document. The host serves `host/read` and `host/stamp` of the paths it answers (UI-N3).
136
+ */
137
+ pickLinks?: (params: KitLinksPickParams) => PickedWorkspaceFile[] | Promise<PickedWorkspaceFile[]>;
138
+ };
139
+ /** A file the person chose in the host's `links/pick` chooser: its workspace path and version stamp. */
140
+ export type PickedWorkspaceFile = {
141
+ path: string;
142
+ version: string | null;
143
+ };
144
+ /**
145
+ * The links `links/pick` answers for the files a host's chooser returned (UI-N2): each in the
146
+ * document-relative form, once, without hidden paths (LR2), the document itself, or a file whose
147
+ * extension is not in `accept`; only the first unless `multiple`.
148
+ */
149
+ export declare function pickedLinks(documentPath: string, params: KitLinksPickParams, chosen: PickedWorkspaceFile[]): {
150
+ path: string;
151
+ name: string;
152
+ version: string | null;
153
+ }[];
154
+ export type MountOptions = {
155
+ /** The kit UI's origin, for the handshake (`location.origin` for a kit served by the host). */
156
+ origin: string;
157
+ host: {
158
+ name: string;
159
+ version: string;
160
+ };
161
+ document: KitDocumentInit;
162
+ theme: KitTheme;
163
+ locale: string;
164
+ shortcuts: string[];
165
+ /** The UI configuration (protocol section 9). */
166
+ ui?: KitUiConfig;
167
+ /** The capability sets the host serves (`ui/initialize` `capabilitySets`), such as `KitCollab 1.0`. */
168
+ capabilitySets?: string[];
169
+ handlers: KitHostHandlers;
170
+ /**
171
+ * Serves KitFiles 1.0 (`files/*`, protocol section 7g): the host's storage, the kit manifest's
172
+ * `files` lists, its picker and printer. Lists `files`, and `files-pick` and `print` when it
173
+ * has them. Each kit document the frame loads gets its own grant table, ended with it.
174
+ */
175
+ files?: KitFilesOptions;
176
+ /** How long the kit may take to open the document. */
177
+ timeoutMs?: number;
178
+ /** Abandons the mount (the frame went away first): stops listening and rejects. */
179
+ signal?: AbortSignal;
180
+ };
181
+ /** A mounted kit UI. */
182
+ export type KitConnection = {
183
+ kit: InitializeResult['kit'];
184
+ capabilities: string[];
185
+ state: () => Promise<DocumentState>;
186
+ save: () => Promise<{
187
+ saved: boolean;
188
+ version: string | null;
189
+ }>;
190
+ fileChanged: (version: string) => void;
191
+ /** Tells the kit the file is now `version` and its document already holds it (`document/held`, protocol 2.6): no conflict. */
192
+ fileHeld: (version: string) => void;
193
+ setTheme: (theme: KitTheme) => void;
194
+ setLocale: (locale: string) => void;
195
+ focus: () => void;
196
+ /**
197
+ * Replaces the UI configuration (`ui/configure`). A host that mounts the kit again passes its
198
+ * latest configuration as the `ui` option.
199
+ */
200
+ configure: (ui: KitUiConfig) => void;
201
+ /** Tells the kit the document's leases changed (`lease/changed`, capability `lease`). */
202
+ leasesChanged: (leases: KitLease[]) => void;
203
+ /** Tells the kit who else is in the document and what they share (`presence/peers`, capability `presence`): the whole list. */
204
+ peersChanged: (peers: KitPeerPresence[]) => void;
205
+ /**
206
+ * Shows `view` in the open document (`document/reveal`, section 7i, OP3), as the `document.view`
207
+ * a new editor opens at. A kit that cannot show it ignores it.
208
+ */
209
+ reveal: (view: KitView) => void;
210
+ /** Tells the kit the host's threads to mark (`comments/show`, capability `comment-anchors`): the whole list; malformed anchors are left out. */
211
+ showComments: (threads: KitShownThread[]) => void;
212
+ /** Whether the kit finds each anchor now (`comments/locate`); all `false` from a kit without `comment-anchors`. */
213
+ locateComments: (anchors: KitCommentAnchor[]) => Promise<boolean[]>;
214
+ /**
215
+ * Hears every `presence/set` the kit sends (what the person selected, where their caret is),
216
+ * checked; answers an unsubscribe. The object model's `selection` event follows it.
217
+ */
218
+ onPresence: (listener: (presence: KitPresence) => void) => () => void;
219
+ /** The editor's elements (`ui/elements`). Rejects with -32601 when the kit did not declare its UI. */
220
+ elements: () => Promise<KitUiElement[]>;
221
+ /**
222
+ * The engine's diagnostics on the document (`document/check`, capability `check`), errors first;
223
+ * `draft` checks the agent's draft. A kit without the capability answers no diagnostics here.
224
+ */
225
+ check: (options?: {
226
+ draft?: boolean;
227
+ }) => Promise<KitDiagnostic[]>;
228
+ /**
229
+ * The Kit AI bridge; `draft` (capability `draft`) works on the agent's draft instead of the live
230
+ * document. `run`'s steps are the agent's, or with `origin: 'system'` (protocol 2.7) the host's
231
+ * own change, recorded with `originLabel` (`host` when absent) and no undo step in any history.
232
+ * Only the host's own features send `origin`, never a model's call.
233
+ */
234
+ ai: {
235
+ inspect: (options?: {
236
+ draft?: boolean;
237
+ context?: AiStep['context'];
238
+ part?: number;
239
+ }) => Promise<Record<string, unknown>>;
240
+ commands: (query: string) => Promise<Array<Record<string, unknown>>>;
241
+ run: (steps: AiStep[], save: boolean, options?: Pick<AiRunParams, 'draft' | 'origin' | 'originLabel'>) => Promise<AiRunResult>;
242
+ preview: (maxSize: number, options?: {
243
+ draft?: boolean;
244
+ }) => Promise<{
245
+ png: string;
246
+ }>;
247
+ /** (2.9, capability `changes`) The replica's version, base64: what `changes` takes back. */
248
+ version: () => Promise<string>;
249
+ /** Read-only callbacks for the SDK premise guard (capability `premises`). */
250
+ premise: (method: string, params: Record<string, unknown>) => Promise<unknown>;
251
+ /**
252
+ * (2.9, capability `changes`) What changed since the version `since`: the change set and the
253
+ * version now, or `changes: null` and why. `schema` is the kit's, as for `model.describe`.
254
+ */
255
+ changes: (since: string, schema?: object) => Promise<{
256
+ changes: Record<string, unknown> | null;
257
+ unavailable?: string;
258
+ version: string;
259
+ }>;
260
+ };
261
+ /**
262
+ * The agent's draft, when the kit lists the `draft` capability (section 7d). `ready` and
263
+ * `reopen` may be the agent's; `merge` and `discard` MUST come from the person's explicit
264
+ * approval, never from a model.
265
+ */
266
+ draft: {
267
+ state: () => Promise<DraftInfo>;
268
+ ready: () => Promise<DraftInfo>;
269
+ reopen: () => Promise<DraftInfo>;
270
+ compare: (options?: {
271
+ maxSize?: number;
272
+ schema?: object;
273
+ }) => Promise<DraftComparison>;
274
+ merge: (origin: DraftOrigin, schema?: object) => Promise<{
275
+ merged: boolean;
276
+ summary: DraftSummary;
277
+ }>;
278
+ discard: () => Promise<DraftInfo>;
279
+ };
280
+ /** The document's KDM replica, when the kit declares the `replica` capability. */
281
+ replica: {
282
+ version: () => Promise<ArrayBuffer>;
283
+ exportChanges: (since: ArrayBuffer) => Promise<{
284
+ changes: ArrayBuffer;
285
+ blobs: ArrayBuffer;
286
+ }>;
287
+ importChanges: (changes: ArrayBuffer, blobs: ArrayBuffer) => Promise<{
288
+ damage: unknown;
289
+ }>;
290
+ /** The replica's own id (minor version 1.3), when the kit's engine has one; `null` otherwise. */
291
+ info: () => Promise<string | null>;
292
+ /** Hears every `replica/changed` (the replica's version after an edit); answers an unsubscribe. */
293
+ onChanged: (listener: (version: ArrayBuffer) => void) => () => void;
294
+ };
295
+ /**
296
+ * The object model answered by the kit itself, when it lists the `model` capability (section
297
+ * 7a): a batch is one undo step of the kit's own history. A refused batch rejects with a
298
+ * `KitRpcError` whose `data` is `{ code, index, message }`.
299
+ */
300
+ model: {
301
+ describe: (schema?: object) => Promise<Record<string, unknown>>;
302
+ batch: (params: ModelBatchParams) => Promise<ModelBatchResult>;
303
+ };
304
+ /**
305
+ * The session's file grants, when the host serves `files` (KitFiles 1.0): grant a handle for an
306
+ * agent's `file` parameter or a drop, revoke handles, list what the kit holds (FA16).
307
+ */
308
+ files: Pick<KitFileSession, 'grant' | 'revoke' | 'grants'> | null;
309
+ close: () => void;
310
+ };
311
+ /**
312
+ * Hands `frame` (already loaded with the kit's UI entry) its port and initializes it. Resolves
313
+ * when the kit has opened the document; rejects with the kit's error otherwise.
314
+ */
315
+ export declare function mountKit(frame: HTMLIFrameElement, options: MountOptions): Promise<KitConnection>;
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@kition/kit-host",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "The host's side of the Kit UI protocol: mount an embedded kit UI in an iframe and serve its file calls.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/types/src/index.d.ts",
10
+ "import": "./dist/index.js"
11
+ }
12
+ },
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "dependencies": {
17
+ "@kition/kit-ui-protocol": "0.2.0"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/KitionAI/kition-sdk.git",
22
+ "directory": "packages/kit-host"
23
+ },
24
+ "types": "./dist/types/src/index.d.ts",
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "main": "./dist/index.js",
29
+ "scripts": {
30
+ "build": "node ../../tools/build-package.mjs"
31
+ }
6
32
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.