@kition/kit-engine 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,278 @@
1
+ import { person as C, system as b, randomActor as y, undoScopeOf as E, Replica as x, decodeOrigin as O, Version as f } from "@kition/kdm";
2
+ const v = C("host:person"), p = { kind: "none" }, S = { kind: "full" };
3
+ function R(t, i) {
4
+ return t.kind === "full" || i.kind === "full" ? S : t.kind === "none" ? i : i.kind === "none" ? t : { kind: "rects", rects: [...t.rects, ...i.rects] };
5
+ }
6
+ class d {
7
+ constructor(i, s) {
8
+ this.model = i, this.replica = s, s.takeChanged(), this.viewState = i.load(s), s.takeChanged(), this.savedVersion = s.version();
9
+ }
10
+ viewState;
11
+ savedVersion;
12
+ /** The version the bytes of the last `save()` hold, until `markSaved`. */
13
+ pendingSave = null;
14
+ revisionCount = 0n;
15
+ get view() {
16
+ return this.viewState;
17
+ }
18
+ get revision() {
19
+ return this.revisionCount;
20
+ }
21
+ get dirty() {
22
+ return !this.replica.version().equals(this.savedVersion);
23
+ }
24
+ /** Runs a command as `origin`; the view follows what it committed. */
25
+ execute(i, s, n) {
26
+ const u = this.replica.version(), e = this.model.command(this.viewState, this.replica, i, s, n), r = this.replica.takeChanged();
27
+ return r.size > 0 && this.refresh(r), this.replica.version().equals(u) || (this.revisionCount += 1n), e;
28
+ }
29
+ /** Applies only a validated file difference, retaining both undo histories and identities. */
30
+ reread(i) {
31
+ const s = this.replica.version();
32
+ this.replica.transact({ kind: "import", principal: "file reread" }, (u) => i(this.viewState, u));
33
+ const n = this.refresh(this.replica.takeChanged());
34
+ return this.replica.version().equals(s) || (this.revisionCount += 1n), this.savedVersion = this.replica.version(), this.pendingSave = null, n;
35
+ }
36
+ /** Imports another replica's changes; repairs what they left invalid. */
37
+ importChanges(i) {
38
+ const s = this.replica.version();
39
+ this.replica.importChanges(i);
40
+ const n = this.settle();
41
+ return this.replica.version().equals(s) || (this.revisionCount += 1n), n;
42
+ }
43
+ /** Undoes the person's last step (KitModel M12a: never an agent's). */
44
+ undo() {
45
+ return this.undoIn("person");
46
+ }
47
+ redo() {
48
+ return this.redoIn("person");
49
+ }
50
+ /** Undoes the last step of `scope` (an agent's undo takes back only the agent's steps); repairs the result. */
51
+ undoIn(i) {
52
+ const s = this.replica.undoIn(i), n = s ? this.settle() : p;
53
+ return s && (this.revisionCount += 1n), { done: s, damage: n };
54
+ }
55
+ redoIn(i) {
56
+ const s = this.replica.redoIn(i), n = s ? this.settle() : p;
57
+ return s && (this.revisionCount += 1n), { done: s, damage: n };
58
+ }
59
+ /** The file bytes; the document stays unsaved until `markSaved`. */
60
+ save(i) {
61
+ const s = this.model.export(this.viewState, this.replica, i);
62
+ return this.pendingSave = this.replica.version(), s;
63
+ }
64
+ markSaved() {
65
+ this.pendingSave && (this.savedVersion = this.pendingSave), this.pendingSave = null;
66
+ }
67
+ /** After an import, undo, or redo: validate over what changed (a `system` repair), then apply both. */
68
+ settle() {
69
+ const i = this.replica.takeChanged();
70
+ if (i.size === 0) return p;
71
+ const s = this.model.validate;
72
+ let n = null;
73
+ if (s) {
74
+ try {
75
+ this.replica.transact(b("repair"), (e) => s.call(this.model, e, this.replica, i));
76
+ } catch (e) {
77
+ n = e;
78
+ }
79
+ for (const e of this.replica.takeChanged()) i.add(e);
80
+ }
81
+ const u = this.refresh(i);
82
+ if (n) throw n;
83
+ return u;
84
+ }
85
+ /** Applies `changed` to the view; if that fails, loads the view again so it still matches. */
86
+ refresh(i) {
87
+ try {
88
+ const s = this.model.apply(this.viewState, this.replica, i);
89
+ return this.replica.takeChanged(), s;
90
+ } catch {
91
+ return this.viewState = this.model.load(this.replica), this.replica.takeChanged(), S;
92
+ }
93
+ }
94
+ }
95
+ function l(t) {
96
+ if (t.trim() === "") return {};
97
+ const i = JSON.parse(t);
98
+ if (i === null || typeof i != "object" || Array.isArray(i)) throw new Error(`the parameters are not a JSON object: ${t}`);
99
+ return i;
100
+ }
101
+ function o(t) {
102
+ return JSON.stringify(t === void 0 ? null : t);
103
+ }
104
+ function g(t, i) {
105
+ return new Uint8Array(Math.max(0, Math.floor(t)) * Math.max(0, Math.floor(i)) * 4);
106
+ }
107
+ function V(t, i = {}) {
108
+ const s = i.actor ?? y;
109
+ class n {
110
+ constructor(e) {
111
+ this.session = e;
112
+ }
113
+ forkForPremises() {
114
+ const e = new n(new d(t, x.load(t.schema, this.session.replica.snapshot(), s()))), r = t.blobs?.(this.session.view, this.session.replica);
115
+ if (r?.length) {
116
+ if (!t.addBlobs) throw new Error("this kit cannot copy blobs for premise planning");
117
+ t.addBlobs(e.session.view, e.session.replica, r);
118
+ }
119
+ return t.restoreEditorState && t.editorState && e.restoreEditorState(this.editorState()), e;
120
+ }
121
+ static contractVersion() {
122
+ return 1;
123
+ }
124
+ static open(e, r) {
125
+ return new n(new d(t, t.import(e, r, s())));
126
+ }
127
+ /**
128
+ * The file with the replica stored for it: the model's `openReplica`, or, for a format whose
129
+ * files hold their replica, the file alone (the stored replica adds nothing it lacks).
130
+ */
131
+ static openWithReplica(e, r, h, a) {
132
+ return t.openReplica ? new n(new d(t, t.openReplica(e, r, h, a, s()))) : n.open(e, r);
133
+ }
134
+ static create(e, r, h) {
135
+ if (!t.create) throw new Error("this kit cannot create documents");
136
+ return new n(new d(t, t.create(e, { width: r, height: h }, s())));
137
+ }
138
+ size() {
139
+ return t.size?.(this.session.view, this.session.replica) ?? { width: 0, height: 0 };
140
+ }
141
+ get width() {
142
+ return this.size().width;
143
+ }
144
+ get height() {
145
+ return this.size().height;
146
+ }
147
+ get revision() {
148
+ return this.session.revision;
149
+ }
150
+ get dirty() {
151
+ return this.session.dirty;
152
+ }
153
+ get docId() {
154
+ return this.session.replica.docId;
155
+ }
156
+ render(e, r, h, a, c) {
157
+ return g(a, c);
158
+ }
159
+ renderArea(e, r, h, a, c, k) {
160
+ return g(c, k);
161
+ }
162
+ execute(e, r) {
163
+ return this.executeAs(e, r, JSON.stringify([v.kind, v.principal, null]));
164
+ }
165
+ executeAs(e, r, h) {
166
+ const a = O(h);
167
+ if (!a) throw new Error(`origin is not [kind, principal, label]: ${h}`);
168
+ const c = l(r);
169
+ return o(e === "edit.undo" || e === "undo" ? this.session.undoIn(w(c, a)) : e === "edit.redo" || e === "redo" ? this.session.redoIn(w(c, a)) : this.session.execute(e, c, a));
170
+ }
171
+ inspect() {
172
+ const e = t.inspect?.(this.session.view, this.session.replica) ?? {};
173
+ return o({ ...e, canUndo: this.canUndo(), canRedo: this.canRedo() });
174
+ }
175
+ check() {
176
+ const e = { error: 0, warning: 1, info: 2 }, r = [...t.check?.(this.session.view, this.session.replica) ?? []].sort((h, a) => e[h.severity] - e[a.severity]);
177
+ return o({ diagnostics: r });
178
+ }
179
+ commands() {
180
+ return o(this.catalog());
181
+ }
182
+ premiseRead(e, r) {
183
+ if (e === "projected" && t.projectedObjects) return o(t.projectedObjects(this.session.view, this.session.replica));
184
+ if (e === "state") return o({ state: JSON.parse(this.editorState()) });
185
+ if (t.premise) return o(t.premise(this.session.view, this.session.replica, e, {
186
+ step: 0,
187
+ changes: null,
188
+ ...l(r),
189
+ state: JSON.parse(this.editorState())
190
+ }));
191
+ if (e === "under") return "null";
192
+ if (e === "inputs") return '{"inputs":[]}';
193
+ if (e === "identity") return '{"unproven":[]}';
194
+ if (e === "derived") return '{"objects":[]}';
195
+ if (e === "blob-support") return '{"available":false}';
196
+ throw new Error(`unsupported premise request: ${e}`);
197
+ }
198
+ editorState() {
199
+ return !t.editorState || !t.restoreEditorState || !t.setContext ? "null" : o(t.editorState(this.session.view, this.session.replica));
200
+ }
201
+ restoreEditorState(e) {
202
+ if (!t.restoreEditorState) throw new Error("this kit cannot restore editor context");
203
+ t.restoreEditorState(this.session.view, this.session.replica, JSON.parse(e));
204
+ }
205
+ setContext(e) {
206
+ if (!t.setContext) throw new Error("this kit cannot set editor context");
207
+ t.setContext(this.session.view, this.session.replica, l(e));
208
+ }
209
+ disabledCommands() {
210
+ return o(this.catalog().filter((e) => !e.enabled).map((e) => e.id));
211
+ }
212
+ catalog() {
213
+ const e = [
214
+ { id: "edit.undo", title: "Undo", menu: ["Edit"], shortcut: "Cmd+Z", mutates: !0, enabled: this.canUndo() },
215
+ { id: "edit.redo", title: "Redo", menu: ["Edit"], shortcut: "Cmd+Shift+Z", mutates: !0, enabled: this.canRedo() }
216
+ ], r = t.commands(this.session.view, this.session.replica);
217
+ return [...e.filter((h) => !r.some((a) => a.id === h.id)), ...r];
218
+ }
219
+ save(e = "document") {
220
+ return this.session.save(e);
221
+ }
222
+ markSaved() {
223
+ this.session.markSaved();
224
+ }
225
+ free() {
226
+ }
227
+ version() {
228
+ return this.session.replica.version().encode();
229
+ }
230
+ exportChanges(e) {
231
+ return this.session.replica.exportChanges(e.length === 0 ? f.empty() : f.decode(e));
232
+ }
233
+ importChanges(e) {
234
+ return o(this.session.importChanges(e));
235
+ }
236
+ snapshot() {
237
+ return this.session.replica.snapshot();
238
+ }
239
+ undo() {
240
+ return o(this.session.undo());
241
+ }
242
+ redo() {
243
+ return o(this.session.redo());
244
+ }
245
+ canUndo() {
246
+ return this.session.replica.canUndo();
247
+ }
248
+ canRedo() {
249
+ return this.session.replica.canRedo();
250
+ }
251
+ schemaVersion() {
252
+ return this.session.replica.schema.schemaVersion;
253
+ }
254
+ authorSchemaVersion() {
255
+ return this.session.replica.authorSchemaVersion();
256
+ }
257
+ blobs() {
258
+ return t.blobs?.(this.session.view, this.session.replica) ?? new Uint8Array(0);
259
+ }
260
+ addBlobs(e) {
261
+ if (t.addBlobs) t.addBlobs(this.session.view, this.session.replica, e);
262
+ else if (e.length > 0) throw new Error("this kit's documents hold no media");
263
+ }
264
+ }
265
+ return n;
266
+ }
267
+ function w(t, i) {
268
+ const s = t.scope;
269
+ if (s == null) return E(i.kind) ?? "person";
270
+ if (s === "person" || s === "agent") return s;
271
+ throw new Error(`invalid-params: scope is "person" or "agent", not ${JSON.stringify(s)}`);
272
+ }
273
+ export {
274
+ d as KitSession,
275
+ w as historyScope,
276
+ V as kitEngineClass,
277
+ R as mergeDamage
278
+ };
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Engine contract 2 as TypeScript (Kition platform docs/platform/kits/engine.md, architecture 7.2): the document
3
+ * class a kit's engine worker drives. A WebAssembly engine made with `export_kit_document!` and
4
+ * `export_kit_session!` has exactly these members, so one worker (`@kition/kit-editor`), the embed
5
+ * SDK, and the object model serve both runtimes.
6
+ */
7
+ /** One historical coverage comparison from the kit's `covered` premise callback. */
8
+ export interface Covered {
9
+ id: string | number;
10
+ covered: boolean | null;
11
+ /** The held object no longer exists. The guard refuses with `deleted`. */
12
+ gone?: boolean;
13
+ content?: 'same' | 'changed' | 'deleted' | 'unknown';
14
+ }
15
+ export interface CoveredAt {
16
+ under: Array<string | number>;
17
+ covered: Covered[];
18
+ }
19
+ /** One command as `commands()` lists it (Kition platform docs/platform/reference/contract.md). */
20
+ export type KitEngineCommand = {
21
+ id: string;
22
+ title: string;
23
+ /** What the command does, when to choose it, and what it changes or answers: one or two sentences, never the title again or the parameter notation (`kition_kit::testing::check_commands`). */
24
+ description?: string | null;
25
+ /** The menu path, for example `["Page", "New"]`; `null` or empty when it is in no menu. */
26
+ menu: string[] | null;
27
+ /** As `Cmd+Shift+N`. */
28
+ shortcut: string | null;
29
+ mutates: boolean;
30
+ enabled: boolean;
31
+ /** The parameters as a JSON schema (`ParameterSchemaSpec`); commands with one can be agent tools. */
32
+ schema?: Record<string, unknown> | null;
33
+ /** What the command answers, as one `ValueSchemaSpec` (KHP A1 `output.schema`); optional. */
34
+ outputSchema?: Record<string, unknown> | null;
35
+ /** Parameter notes for an agent. */
36
+ params?: string | null;
37
+ /** Words an agent's command search finds it by that its id, title and params do not say (the effect names `effect.apply` takes); searched, never listed. */
38
+ keywords?: string[] | null;
39
+ };
40
+ /** What a change made stale on screen, as `importChanges` and `undo` answer it (Rust `Damage`). */
41
+ export type KitDamage = {
42
+ kind: 'none';
43
+ } | {
44
+ kind: 'full';
45
+ } | {
46
+ kind: 'rects';
47
+ rects: Array<[number, number, number, number]>;
48
+ };
49
+ export type KitCallContext = {
50
+ on?: Array<string | number>;
51
+ part?: Record<string, unknown>;
52
+ time?: number;
53
+ };
54
+ /** One open document. Every member is synchronous: the worker runs one request at a time. */
55
+ export interface KitEngineDocument {
56
+ readonly width: number;
57
+ readonly height: number;
58
+ /** Moves with every change. */
59
+ readonly revision: bigint;
60
+ /** Whether the document changed since the bytes `markSaved` confirmed. */
61
+ readonly dirty: boolean;
62
+ /** RGBA8 pixels; an engine whose editor draws itself answers transparent pixels. */
63
+ render(x: number, y: number, scale: number, width: number, height: number): Uint8Array;
64
+ renderArea(x0: number, y0: number, x1: number, y1: number, width: number, height: number): Uint8Array;
65
+ /** Runs a command as the host's person, JSON in and out. */
66
+ execute(command: string, params: string): string;
67
+ /** The document as JSON; it includes `canUndo` and `canRedo`. */
68
+ inspect(): string;
69
+ /** Every command as JSON (`KitEngineCommand[]`). */
70
+ commands(): string;
71
+ /** The ids of the commands that cannot run now, as JSON. */
72
+ disabledCommands(): string;
73
+ /** The document's diagnostics as JSON `{ diagnostics: KitEngineDiagnostic[] }` (KHP A21); optional. */
74
+ check?(): string;
75
+ /** The document as file bytes; it stays unsaved until `markSaved`. */
76
+ save(name?: string): Uint8Array;
77
+ markSaved(): void;
78
+ free(): void;
79
+ /** The replica's own id (a sync room's `docId`). */
80
+ readonly docId: string;
81
+ /** The replica's version, encoded. */
82
+ version(): Uint8Array;
83
+ /** The changes since `since` (empty bytes: all of them). */
84
+ exportChanges(since: Uint8Array): Uint8Array;
85
+ /** Imports another replica's changes; answers the damage as JSON. */
86
+ importChanges(changes: Uint8Array): string;
87
+ snapshot(): Uint8Array;
88
+ /** `{"done", "damage"}` as JSON. */
89
+ undo(): string;
90
+ redo(): string;
91
+ canUndo(): boolean;
92
+ canRedo(): boolean;
93
+ /** Runs a command as `origin`, the KDM's commit form `[kind, principal, label]` as JSON. */
94
+ executeAs(command: string, params: string, origin: string): string;
95
+ /** The schema version the replica reads (its kit's `model.schemaVersion`); optional. */
96
+ schemaVersion?(): number;
97
+ /**
98
+ * The newest schema version any of the replica's changes was written under (standard 2.0 rule
99
+ * M5a), or `null` when none records one; optional. Above `schemaVersion()`, a newer kit edited
100
+ * the document, and the host tells the person (Kit UI protocol `document/schema`).
101
+ */
102
+ authorSchemaVersion?(): number | null;
103
+ /**
104
+ * The blobs the replica's changes refer to, as a bundle for `addBlobs`; a host sends them with
105
+ * every exchange of changes. Empty for a document without media.
106
+ */
107
+ blobs(): Uint8Array;
108
+ addBlobs(blobs: Uint8Array): void;
109
+ /** Read-only premise callbacks, JSON in and out, evaluated in the worker's call context. */
110
+ premiseRead?(method: string, params: string): string;
111
+ forkForPremises?(): KitEngineDocument;
112
+ /** Opaque transient state, or JSON null when the kit cannot isolate agent contexts. */
113
+ editorState?(): string;
114
+ restoreEditorState?(state: string): void;
115
+ setContext?(context: string): void;
116
+ }
117
+ /** The document class a module exports under the manifest's `engine.class`. */
118
+ export interface KitEngineClass {
119
+ /** 1: hosts built for contract 1 open it; the manifest and the session members make it contract 2. */
120
+ contractVersion(): number;
121
+ open(name: string, bytes: Uint8Array): KitEngineDocument;
122
+ /** Opens a file with the replica stored for it; a file that holds its replica may ignore them. */
123
+ openWithReplica(name: string, bytes: Uint8Array, snapshot: Uint8Array, blobs: Uint8Array): KitEngineDocument;
124
+ create(name: string, width: number, height: number): KitEngineDocument;
125
+ }
126
+ /**
127
+ * What a `ts-worker` module's default export receives before its first document (rule K11): where
128
+ * the module was loaded from, and, where `fetch` cannot read files (Node), how to read one of the
129
+ * package's files by its path relative to `base`.
130
+ */
131
+ export type KitEngineInit = {
132
+ base: string;
133
+ read?: (file: string) => Promise<Uint8Array>;
134
+ };
135
+ /** The module's default export: prepares the engine (for example, loads its dependencies' WebAssembly). */
136
+ export type KitEngineModuleInit = (init: KitEngineInit) => Promise<void>;
137
+ /** One thing an engine found wrong with its document (KHP A21): a stable `<kit>.<name>` code, what it is about (none set: the whole document; pages and slides count from 1), and a command hint to fix it. */
138
+ export type KitEngineDiagnostic = {
139
+ code: string;
140
+ severity: 'error' | 'warning' | 'info';
141
+ target: {
142
+ objectId?: string;
143
+ path?: string;
144
+ page?: number;
145
+ slide?: number;
146
+ sheet?: string;
147
+ cell?: string;
148
+ };
149
+ message: string;
150
+ fix?: {
151
+ command: string;
152
+ params?: Record<string, unknown>;
153
+ };
154
+ };
@@ -0,0 +1,2 @@
1
+ export type { Covered, CoveredAt, KitCallContext, KitDamage, KitEngineClass, KitEngineCommand, KitEngineDiagnostic, KitEngineDocument, KitEngineInit, KitEngineModuleInit } from './contract.js';
2
+ export { historyScope, kitEngineClass, KitSession, mergeDamage, type KitEngineClassOptions, type KitModel, type KitSize } from './session.js';
@@ -0,0 +1,133 @@
1
+ /**
2
+ * `KitSession`: the TypeScript twin of `kition_kit::session` (architecture 7.1 and 7.2). A kit
3
+ * supplies a `KitModel`, its materialised view over a KDM replica and its commands, and
4
+ * `kitEngineClass` makes the contract 2 document class from it: the replica, the exchange of
5
+ * changes, undo and redo, the saved state, and the JSON of the contract.
6
+ */
7
+ import { Replica, type ObjectId, type Origin, type ProjectedObject, type Schema, type Tx, type UndoScope } from '@kition/kdm';
8
+ import type { KitCallContext, KitDamage, KitEngineClass, KitEngineCommand, KitEngineDiagnostic, KitEngineDocument } from './contract.js';
9
+ export type KitSize = {
10
+ width: number;
11
+ height: number;
12
+ };
13
+ /**
14
+ * A kit's engine on the KDM: its view of a replica and how commands change the replica.
15
+ *
16
+ * - E11: `load` builds the view, `apply` patches it from the objects an import, undo, or redo
17
+ * changed (throw to have it loaded again).
18
+ * - E12: `command` turns a command into transactions on the replica (`replica.transact`); a view
19
+ * that changes itself first records the difference as the command's transaction, as long as
20
+ * `apply` still brings it up to date.
21
+ * - E13: `import` makes a new replica from file bytes (`Replica.createWith`), `export` writes the
22
+ * file from the replica.
23
+ * - E14: `validate` repairs what a merge left invalid; its changes commit with origin `system`.
24
+ */
25
+ export interface KitModel<View> {
26
+ readonly schema: Schema;
27
+ projectedObjects?(view: View, replica: Replica): ProjectedObject[];
28
+ load(replica: Replica): View;
29
+ apply(view: View, replica: Replica, changed: ReadonlySet<ObjectId>): KitDamage;
30
+ /** Runs `id`; answers its JSON result. Throw to refuse it. */
31
+ command(view: View, replica: Replica, id: string, params: Record<string, unknown>, origin: Origin): unknown;
32
+ commands(view: View, replica: Replica): KitEngineCommand[];
33
+ /** Repairs, as one transaction; answers whether it wrote anything. */
34
+ validate?(tx: Tx, replica: Replica, changed: ReadonlySet<ObjectId>): boolean;
35
+ import(name: string, bytes: Uint8Array, actor: bigint): Replica;
36
+ /**
37
+ * Opens file bytes with the replica a host stored for them (`openWithReplica`), for a format that
38
+ * does not hold its replica (Markdown): the replica from `snapshot` (a KDM snapshot or a full
39
+ * change export, `blobs` its media), and what the file says that it lacks as a `system` import
40
+ * change; empty `bytes` open the replica alone. Without it, a stored replica adds nothing to a
41
+ * file that holds its own, which opens as `import` makes it.
42
+ */
43
+ openReplica?(name: string, bytes: Uint8Array, snapshot: Uint8Array, blobs: Uint8Array, actor: bigint): Replica;
44
+ export(view: View, replica: Replica, name: string): Uint8Array;
45
+ /** A new document; without it, `create` refuses. */
46
+ create?(name: string, size: KitSize, actor: bigint): Replica;
47
+ /**
48
+ * Media: the blob bundle the replica's changes refer to, and taking one in. Without them the
49
+ * document has no media: `blobs()` is empty and a bundle someone sends is refused.
50
+ */
51
+ blobs?(view: View, replica: Replica): Uint8Array;
52
+ addBlobs?(view: View, replica: Replica, blobs: Uint8Array): void;
53
+ /** What `inspect()` adds to `canUndo` and `canRedo`. */
54
+ inspect?(view: View, replica: Replica): Record<string, unknown>;
55
+ /** What is wrong with the document (Kit Harness Protocol (KHP) A21); without it, `check()` answers none. It must not change the document. */
56
+ check?(view: View, replica: Replica): KitEngineDiagnostic[];
57
+ /** The document's size in pixels (0 × 0 when the editor draws itself). */
58
+ size?(view: View, replica: Replica): KitSize;
59
+ /** Kit-defined guard reads; return null from `under` when the command has no extra premises. */
60
+ premise?(view: View, replica: Replica, method: string, params: Record<string, unknown>): unknown;
61
+ /** Transient selection/part/time state. Supply all three hooks to isolate agent calls. */
62
+ editorState?(view: View, replica: Replica): unknown;
63
+ restoreEditorState?(view: View, replica: Replica, state: unknown): void;
64
+ setContext?(view: View, replica: Replica, context: KitCallContext): void;
65
+ }
66
+ /** Both damages: full absorbs everything, rects add up. */
67
+ export declare function mergeDamage(a: KitDamage, b: KitDamage): KitDamage;
68
+ /** One document: a replica, the model's view of it, and its saved state. */
69
+ export declare class KitSession<View> {
70
+ readonly model: KitModel<View>;
71
+ readonly replica: Replica;
72
+ private viewState;
73
+ private savedVersion;
74
+ /** The version the bytes of the last `save()` hold, until `markSaved`. */
75
+ private pendingSave;
76
+ private revisionCount;
77
+ constructor(model: KitModel<View>, replica: Replica);
78
+ get view(): View;
79
+ get revision(): bigint;
80
+ get dirty(): boolean;
81
+ /** Runs a command as `origin`; the view follows what it committed. */
82
+ execute(id: string, params: Record<string, unknown>, origin: Origin): unknown;
83
+ /** Applies only a validated file difference, retaining both undo histories and identities. */
84
+ reread(reconcile: (view: View, tx: Tx) => void): KitDamage;
85
+ /** Imports another replica's changes; repairs what they left invalid. */
86
+ importChanges(bytes: Uint8Array): KitDamage;
87
+ /** Undoes the person's last step (KitModel M12a: never an agent's). */
88
+ undo(): {
89
+ done: boolean;
90
+ damage: KitDamage;
91
+ };
92
+ redo(): {
93
+ done: boolean;
94
+ damage: KitDamage;
95
+ };
96
+ /** Undoes the last step of `scope` (an agent's undo takes back only the agent's steps); repairs the result. */
97
+ undoIn(scope: UndoScope): {
98
+ done: boolean;
99
+ damage: KitDamage;
100
+ };
101
+ redoIn(scope: UndoScope): {
102
+ done: boolean;
103
+ damage: KitDamage;
104
+ };
105
+ /** The file bytes; the document stays unsaved until `markSaved`. */
106
+ save(name: string): Uint8Array;
107
+ markSaved(): void;
108
+ /** After an import, undo, or redo: validate over what changed (a `system` repair), then apply both. */
109
+ private settle;
110
+ /** Applies `changed` to the view; if that fails, loads the view again so it still matches. */
111
+ private refresh;
112
+ }
113
+ /** Options of `kitEngineClass`. */
114
+ export type KitEngineClassOptions = {
115
+ /** The actor of each new replica; a random one by default (each open document is its own replica). */
116
+ actor?: () => bigint;
117
+ };
118
+ /**
119
+ * The contract 2 document class for `model`, to export under the manifest's `engine.class`:
120
+ *
121
+ * ```ts
122
+ * export const BoardDocument = kitEngineClass(boardModel)
123
+ * ```
124
+ */
125
+ export declare function kitEngineClass<View>(model: KitModel<View>, options?: KitEngineClassOptions): KitEngineClass & (new (session: KitSession<View>) => KitEngineDocument & {
126
+ readonly session: KitSession<View>;
127
+ });
128
+ /**
129
+ * The undo scope an `edit.undo` or `edit.redo` works in (KitModel M12a): the one its `scope`
130
+ * parameter names (`"person"` or `"agent"`), else its origin's (`agent` for an agent's step,
131
+ * `person` for the person's and for scripts). The Rust twin is `kition_kit::session::history_scope`.
132
+ */
133
+ export declare function historyScope(params: Record<string, unknown>, origin: Origin): UndoScope;
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@kition/kit-engine",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "Engine contract 2 in TypeScript: the document class a kit's engine worker drives, and KitSession, which makes one from a kit model on the Kit Data Model.",
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/kdm": "0.2.0"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/KitionAI/kition-sdk.git",
22
+ "directory": "packages/kit-engine"
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.