@northtalk/ts 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +59 -2
- package/UNICODE-LICENSE.txt +39 -0
- package/base64-DORMd3Hv.js +6621 -0
- package/binary-value-CEmh60GC.d.ts +15 -0
- package/capabilities-CH0FkRMq.js +1301 -0
- package/checker-Dc1jl2WH.js +6657 -0
- package/core-DptnvQT9.d.ts +14 -0
- package/debug-CQBxKnJB.d.ts +3065 -0
- package/debug.d.ts +3 -0
- package/debug.js +2 -0
- package/driver.d.ts +41 -0
- package/driver.js +152 -0
- package/encoding-nlrpj-Pb.js +99 -0
- package/engine-BGaJ9dAk.js +326 -0
- package/engine-vbYInVYF.d.ts +86 -0
- package/errors-LYJZ_c8h.js +3735 -0
- package/group-B742gg4T.js +10170 -0
- package/http-capability-CSTkw1Yt.js +728 -0
- package/http.d.ts +59 -0
- package/http.js +465 -0
- package/index.d.ts +651 -0
- package/index.js +44 -0
- package/manifest-BscyH_rW.d.ts +70 -0
- package/manifest-DjsxDSuB.js +129 -0
- package/message-layer.d.ts +12 -0
- package/message-layer.js +4 -0
- package/notify.d.ts +3 -0
- package/notify.js +2 -0
- package/objects-DJ3QtCCs.d.ts +640 -0
- package/objects-Db7IB5vQ.js +91 -0
- package/operation-promises-EgZXG5N_.js +23 -0
- package/package.json +70 -4
- package/readers-BFPuosPk.d.ts +25 -0
- package/readers-CjJHKHvH.js +482 -0
- package/request-pump-binary-DdY3X-yl.js +2246 -0
- package/router--71qvxtY.js +343 -0
- package/router-Zhrw5l__.d.ts +55 -0
- package/session.d.ts +9 -0
- package/session.js +3510 -0
- package/setup.d.ts +3 -0
- package/setup.js +193 -0
- package/sha256-B_kyYw3Z.js +124 -0
- package/sqlite.d.ts +74 -0
- package/sqlite.js +529 -0
- package/store-capability-OZp4hXmj.js +390 -0
- package/store-hJrRULMx.js +60 -0
- package/store.d.ts +21 -0
- package/store.js +4 -0
- package/user-capability-BK4Asg7D.js +276 -0
- package/wasm.d.ts +243 -0
- package/wasm.js +1737 -0
package/session.js
ADDED
|
@@ -0,0 +1,3510 @@
|
|
|
1
|
+
|
|
2
|
+
import { B as range, F as num, K as text, M as map, P as nothing, Qt as parseInstant, dt as characterBoundaries, i as ScriptError, it as builtins, k as listValues, l as Value, mt as lower, n as LoadError, qt as formatInstant, t as HostError, u as bool } from "./errors-LYJZ_c8h.js";
|
|
3
|
+
import { o as stateOf, t as defineObjectKind } from "./objects-Db7IB5vQ.js";
|
|
4
|
+
import { a as defineValueCapability, f as validComputedMessageName, u as shape } from "./capabilities-CH0FkRMq.js";
|
|
5
|
+
import { _ as viewSource, f as declarationDocs, h as leadingDoc, m as functionDoc, o as parseEntry, s as parseSource, t as checkSource } from "./checker-Dc1jl2WH.js";
|
|
6
|
+
import { C as integerValue, H as textForm$1, Q as functionHead, U as waitUs, st as compareText } from "./base64-DORMd3Hv.js";
|
|
7
|
+
import { a as recordLine, c as compileLibrary, h as defaultLimits, i as restore, o as traceValue, u as stdlibSources } from "./group-B742gg4T.js";
|
|
8
|
+
import { c as readDisplay, l as readOrderedJSON, r as decodeValue } from "./readers-CjJHKHvH.js";
|
|
9
|
+
import { n as quoteJSON, t as encodeValue } from "./encoding-nlrpj-Pb.js";
|
|
10
|
+
import { a as shapeData, n as exportManifest, t as canonicalJSON } from "./manifest-DjsxDSuB.js";
|
|
11
|
+
import { n as localeCapability, t as userCapability } from "./user-capability-BK4Asg7D.js";
|
|
12
|
+
import { a as clockCapability, i as calendarCapability, o as consoleCapability, r as storeCapability } from "./store-capability-OZp4hXmj.js";
|
|
13
|
+
import { buildSetupGroup, capabilityOperations, immutableSetup, operationDeclarations, shapeOf } from "./setup.js";
|
|
14
|
+
import { a as encodeContents, i as decodeContents, o as sessionQuotas, t as StoreContentsError } from "./engine-BGaJ9dAk.js";
|
|
15
|
+
import { i as memoryStores } from "./store-hJrRULMx.js";
|
|
16
|
+
//#region src/session/objects.ts
|
|
17
|
+
const externalCollection = () => {
|
|
18
|
+
throw new Error("external collection callback in replay");
|
|
19
|
+
};
|
|
20
|
+
const costFrame = (c) => ({
|
|
21
|
+
fuel: c.fuel,
|
|
22
|
+
alloc: c.alloc ?? 0
|
|
23
|
+
});
|
|
24
|
+
const encodedJSON = Symbol("session Value Encoding");
|
|
25
|
+
const encoded = (json) => ({ [encodedJSON]: json });
|
|
26
|
+
const isJsonObject = (j) => !!j && typeof j === "object" && "kind" in j && j.kind === "object";
|
|
27
|
+
const isJsonNumber = (j) => !!j && typeof j === "object" && "kind" in j && j.kind === "number";
|
|
28
|
+
var TranscriptError = class extends Error {};
|
|
29
|
+
const malformed = (detail) => {
|
|
30
|
+
throw new TranscriptError(`Malformed Transcript: ${detail}`);
|
|
31
|
+
};
|
|
32
|
+
const recordObject = (raw) => {
|
|
33
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return malformed("expected object");
|
|
34
|
+
return raw;
|
|
35
|
+
};
|
|
36
|
+
const exact = (raw, required, optional = []) => {
|
|
37
|
+
const obj = recordObject(raw);
|
|
38
|
+
if (required.some((k) => !(k in obj)) || Object.keys(obj).some((k) => ![...required, ...optional].includes(k))) malformed("missing or extra fields");
|
|
39
|
+
return obj;
|
|
40
|
+
};
|
|
41
|
+
const string = (raw) => typeof raw === "string" ? raw : malformed("expected text");
|
|
42
|
+
const counter = (raw) => {
|
|
43
|
+
if (typeof raw === "number" && Number.isSafeInteger(raw) && raw > 0) return BigInt(raw);
|
|
44
|
+
if (typeof raw === "string" && /^[1-9]\d*$/.test(raw) && BigInt(raw) >= 2n ** 53n) return BigInt(raw);
|
|
45
|
+
return malformed("invalid counter");
|
|
46
|
+
};
|
|
47
|
+
const integer = (n) => n < 2n ** 53n ? Number(n) : n.toString();
|
|
48
|
+
const ref = (raw) => {
|
|
49
|
+
const o = exact(raw, ["kind", "id"]);
|
|
50
|
+
const kind = string(o.kind), id = string(o.id);
|
|
51
|
+
if (!kind) malformed("empty kind");
|
|
52
|
+
return {
|
|
53
|
+
kind,
|
|
54
|
+
id
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
const identity = (o) => `${o.kind}\u0000${o.id}`;
|
|
58
|
+
const serialize = (raw) => {
|
|
59
|
+
if (raw && typeof raw === "object" && encodedJSON in raw) return raw[encodedJSON];
|
|
60
|
+
if (Array.isArray(raw)) return `[${raw.map(serialize).join(",")}]`;
|
|
61
|
+
if (raw && typeof raw === "object") return `{${Object.entries(raw).sort(([a], [b]) => compareText(a, b)).map(([k, v]) => `${quoteJSON(k)}:${serialize(v)}`).join(",")}}`;
|
|
62
|
+
return canonicalJSON(raw);
|
|
63
|
+
};
|
|
64
|
+
const jsonSource = (j) => isJsonObject(j) ? `{${j.pairs.map(([k, v]) => `${quoteJSON(k)}:${jsonSource(v)}`).join(",")}}` : isJsonNumber(j) ? j.source : Array.isArray(j) ? `[${j.map(jsonSource).join(",")}]` : canonicalJSON(j);
|
|
65
|
+
const plain = (j) => isJsonObject(j) ? Object.fromEntries(j.pairs.map(([k, v]) => [k, plain(v)])) : isJsonNumber(j) ? Number(j.source) : Array.isArray(j) ? j.map(plain) : j;
|
|
66
|
+
const parseEnvelope = (source) => {
|
|
67
|
+
const raw = readOrderedJSON(source);
|
|
68
|
+
if (!isJsonObject(raw)) malformed("envelope must be object");
|
|
69
|
+
const obj = plain(raw);
|
|
70
|
+
const f = {
|
|
71
|
+
kind: [[
|
|
72
|
+
"type",
|
|
73
|
+
"name",
|
|
74
|
+
"props",
|
|
75
|
+
"parentKinds"
|
|
76
|
+
], ["elements"]],
|
|
77
|
+
object: [["type", "object"]],
|
|
78
|
+
setup: [["type", "objects"]],
|
|
79
|
+
"property-begin": [[
|
|
80
|
+
"type",
|
|
81
|
+
"crossing",
|
|
82
|
+
"object",
|
|
83
|
+
"property",
|
|
84
|
+
"operation"
|
|
85
|
+
], ["value", "selector"]],
|
|
86
|
+
"property-end": [[
|
|
87
|
+
"type",
|
|
88
|
+
"crossing",
|
|
89
|
+
"reply"
|
|
90
|
+
]],
|
|
91
|
+
input: [[
|
|
92
|
+
"type",
|
|
93
|
+
"request",
|
|
94
|
+
"reply"
|
|
95
|
+
]],
|
|
96
|
+
function: [[
|
|
97
|
+
"type",
|
|
98
|
+
"handle",
|
|
99
|
+
"exposure",
|
|
100
|
+
"path"
|
|
101
|
+
]],
|
|
102
|
+
resolve: [["type", "objects"]]
|
|
103
|
+
}[obj.type];
|
|
104
|
+
if (!f) return malformed("unknown envelope type");
|
|
105
|
+
exact(obj, f[0], f[1]);
|
|
106
|
+
if (obj.type === "object" || obj.type === "property-begin") ref(obj.object);
|
|
107
|
+
if (obj.type === "property-begin") {
|
|
108
|
+
counter(obj.crossing);
|
|
109
|
+
string(obj.property);
|
|
110
|
+
const collection = [
|
|
111
|
+
"count",
|
|
112
|
+
"at",
|
|
113
|
+
"find"
|
|
114
|
+
].includes(string(obj.operation));
|
|
115
|
+
if (!(["get", "set"].includes(obj.operation) || collection) || "value" in obj !== (obj.operation === "set") || "selector" in obj !== (obj.operation === "at" || obj.operation === "find") || collection && obj.property !== "elements") malformed("invalid property operation");
|
|
116
|
+
}
|
|
117
|
+
if (obj.type === "property-end") {
|
|
118
|
+
counter(obj.crossing);
|
|
119
|
+
const r = recordObject(obj.reply);
|
|
120
|
+
if (Object.keys(r).length !== 1 || ![
|
|
121
|
+
"value",
|
|
122
|
+
"ok",
|
|
123
|
+
"fail",
|
|
124
|
+
"hostError"
|
|
125
|
+
].includes(Object.keys(r)[0])) malformed("invalid property reply");
|
|
126
|
+
if ("ok" in r && r.ok !== true || "hostError" in r && r.hostError !== true) malformed("invalid property reply flag");
|
|
127
|
+
if ("fail" in r) validateFailure(r.fail);
|
|
128
|
+
}
|
|
129
|
+
if (obj.type === "input") {
|
|
130
|
+
validateRequest(obj.request);
|
|
131
|
+
const reply = recordObject(obj.reply);
|
|
132
|
+
if (Object.keys(reply).length !== 1) malformed("invalid input reply");
|
|
133
|
+
if ("ok" in reply) {
|
|
134
|
+
const ok = exact(reply.ok, [], ["delivery", "broadcast"]);
|
|
135
|
+
if (Object.keys(ok).length > 1) malformed("invalid input reply");
|
|
136
|
+
for (const v of Object.values(ok)) string(v);
|
|
137
|
+
} else string(exact(reply, ["error"]).error);
|
|
138
|
+
}
|
|
139
|
+
if (obj.type === "function") {
|
|
140
|
+
if (!/^f[1-9]\d*$/.test(string(obj.handle))) malformed("invalid function handle");
|
|
141
|
+
counter(obj.exposure);
|
|
142
|
+
if (!Array.isArray(obj.path) || obj.path.some((p) => typeof p !== "string" && !(typeof p === "number" && Number.isSafeInteger(p) && p >= 0))) malformed("invalid path");
|
|
143
|
+
}
|
|
144
|
+
if (obj.type === "setup") for (const o of Object.values(recordObject(obj.objects))) ref(o);
|
|
145
|
+
if (obj.type === "resolve") {
|
|
146
|
+
if (!Array.isArray(obj.objects)) malformed("invalid resolver outcomes");
|
|
147
|
+
for (const o of obj.objects) {
|
|
148
|
+
const r = exact(o, ["object", "resolved"]);
|
|
149
|
+
ref(r.object);
|
|
150
|
+
if (typeof r.resolved !== "boolean") malformed("invalid resolved");
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (obj.type === "kind") {
|
|
154
|
+
if (!string(obj.name)) malformed("empty kind");
|
|
155
|
+
if (!Array.isArray(obj.props) || !Array.isArray(obj.parentKinds) || obj.parentKinds.some((p) => typeof p !== "string")) malformed("invalid kind");
|
|
156
|
+
const names = /* @__PURE__ */ new Set();
|
|
157
|
+
for (const p of obj.props) {
|
|
158
|
+
const r = exact(p, [
|
|
159
|
+
"name",
|
|
160
|
+
"shape",
|
|
161
|
+
"readOnly",
|
|
162
|
+
"getCost"
|
|
163
|
+
], ["setCost"]);
|
|
164
|
+
const name = string(r.name);
|
|
165
|
+
if (!name || names.has(name)) malformed("duplicate/empty property");
|
|
166
|
+
names.add(name);
|
|
167
|
+
if (typeof r.readOnly !== "boolean" || "setCost" in r === r.readOnly) malformed("invalid property declaration");
|
|
168
|
+
decodeShape(r.shape);
|
|
169
|
+
for (const k of ["getCost", ...!r.readOnly ? ["setCost"] : []]) validateCost(r[k]);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
Object.defineProperty(obj, "raw", { value: raw });
|
|
173
|
+
return obj;
|
|
174
|
+
};
|
|
175
|
+
const nodeAt = (envelope, ...path) => {
|
|
176
|
+
let raw = envelope.raw;
|
|
177
|
+
if (!raw) return readOrderedJSON(serialize(path.reduce((o, k) => Array.isArray(o) && typeof k === "number" ? o[k] : recordObject(o)[k], envelope)));
|
|
178
|
+
for (const key of path) {
|
|
179
|
+
raw = typeof key === "number" && Array.isArray(raw) ? raw[key] : isJsonObject(raw) ? raw.pairs.find(([k]) => k === key)?.[1] : void 0;
|
|
180
|
+
if (raw === void 0) return malformed("missing Value");
|
|
181
|
+
}
|
|
182
|
+
return raw;
|
|
183
|
+
};
|
|
184
|
+
const validateCost = (raw) => {
|
|
185
|
+
const c = exact(raw, ["fuel", "alloc"]);
|
|
186
|
+
if (![c.fuel, c.alloc].every((n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0)) malformed("invalid cost");
|
|
187
|
+
return c;
|
|
188
|
+
};
|
|
189
|
+
const nonnegative = (raw) => typeof raw === "number" && Number.isSafeInteger(raw) && raw >= 0 ? raw : malformed("invalid nonnegative integer");
|
|
190
|
+
const validateLimits = (raw) => {
|
|
191
|
+
for (const n of Object.values(exact(raw, [], [
|
|
192
|
+
"fuelPerRun",
|
|
193
|
+
"allocPerRun",
|
|
194
|
+
"maxWaitMs",
|
|
195
|
+
"maxJoin"
|
|
196
|
+
]))) nonnegative(n);
|
|
197
|
+
};
|
|
198
|
+
const validateFailure = (raw) => {
|
|
199
|
+
const f = exact(raw, [
|
|
200
|
+
"code",
|
|
201
|
+
"message",
|
|
202
|
+
"data"
|
|
203
|
+
]);
|
|
204
|
+
string(f.code);
|
|
205
|
+
string(f.message);
|
|
206
|
+
};
|
|
207
|
+
const actionFields = {
|
|
208
|
+
"set-parent": [[
|
|
209
|
+
"kind",
|
|
210
|
+
"object",
|
|
211
|
+
"parent"
|
|
212
|
+
]],
|
|
213
|
+
dispose: [["kind", "object"]],
|
|
214
|
+
deliver: [[
|
|
215
|
+
"kind",
|
|
216
|
+
"to",
|
|
217
|
+
"message"
|
|
218
|
+
]],
|
|
219
|
+
request: [[
|
|
220
|
+
"kind",
|
|
221
|
+
"to",
|
|
222
|
+
"message"
|
|
223
|
+
]],
|
|
224
|
+
"cancel-delivery": [["kind", "delivery"]],
|
|
225
|
+
broadcast: [["kind", "message"]],
|
|
226
|
+
call: [[
|
|
227
|
+
"kind",
|
|
228
|
+
"fn",
|
|
229
|
+
"args"
|
|
230
|
+
], ["limits"]],
|
|
231
|
+
decide: [["kind", "message"], ["to", "broadcast"]],
|
|
232
|
+
answer: [[
|
|
233
|
+
"kind",
|
|
234
|
+
"call",
|
|
235
|
+
"value"
|
|
236
|
+
], ["fuel"]],
|
|
237
|
+
fail: [[
|
|
238
|
+
"kind",
|
|
239
|
+
"call",
|
|
240
|
+
"error"
|
|
241
|
+
]],
|
|
242
|
+
settle: [[
|
|
243
|
+
"kind",
|
|
244
|
+
"call",
|
|
245
|
+
"settlement"
|
|
246
|
+
]],
|
|
247
|
+
stop: [[
|
|
248
|
+
"kind",
|
|
249
|
+
"script",
|
|
250
|
+
"reason"
|
|
251
|
+
]],
|
|
252
|
+
"cancel-run": [[
|
|
253
|
+
"kind",
|
|
254
|
+
"script",
|
|
255
|
+
"run"
|
|
256
|
+
]],
|
|
257
|
+
revoke: [[
|
|
258
|
+
"kind",
|
|
259
|
+
"script",
|
|
260
|
+
"grant"
|
|
261
|
+
]]
|
|
262
|
+
};
|
|
263
|
+
const validateRequest = (raw) => {
|
|
264
|
+
const request = recordObject(raw), kind = string(request.kind), fields = actionFields[kind];
|
|
265
|
+
if (!fields) return malformed("forbidden Host action");
|
|
266
|
+
exact(request, fields[0], fields[1]);
|
|
267
|
+
if ("object" in request) ref(request.object);
|
|
268
|
+
if ("parent" in request && request.parent !== null) ref(request.parent);
|
|
269
|
+
if ("to" in request) {
|
|
270
|
+
const to = recordObject(request.to);
|
|
271
|
+
if (Object.keys(to).length !== 1) malformed("invalid target");
|
|
272
|
+
if ("script" in to) string(to.script);
|
|
273
|
+
else ref(exact(to, ["object"]).object);
|
|
274
|
+
}
|
|
275
|
+
if (kind === "decide" && ("to" in request === "broadcast" in request || "broadcast" in request && request.broadcast !== true)) malformed("invalid decision target");
|
|
276
|
+
if ("message" in request) {
|
|
277
|
+
const m = exact(request.message, ["name"], ["args", "limits"]);
|
|
278
|
+
string(m.name);
|
|
279
|
+
if ("args" in m && !Array.isArray(m.args)) malformed("invalid message arguments");
|
|
280
|
+
if ("limits" in m) validateLimits(m.limits);
|
|
281
|
+
}
|
|
282
|
+
if ("args" in request && !Array.isArray(request.args)) malformed("invalid arguments");
|
|
283
|
+
if ("limits" in request) validateLimits(request.limits);
|
|
284
|
+
if ("fuel" in request) nonnegative(request.fuel);
|
|
285
|
+
for (const k of [
|
|
286
|
+
"script",
|
|
287
|
+
"run",
|
|
288
|
+
"grant",
|
|
289
|
+
"delivery",
|
|
290
|
+
"call",
|
|
291
|
+
"reason"
|
|
292
|
+
]) if (k in request) string(request[k]);
|
|
293
|
+
if ("error" in request) validateFailure(request.error);
|
|
294
|
+
if ("settlement" in request) {
|
|
295
|
+
const s = recordObject(request.settlement);
|
|
296
|
+
if (Object.keys(s).length !== 1) malformed("invalid settlement");
|
|
297
|
+
const k = Object.keys(s)[0];
|
|
298
|
+
if (![
|
|
299
|
+
"answer",
|
|
300
|
+
"fail",
|
|
301
|
+
"reissue",
|
|
302
|
+
"adopt"
|
|
303
|
+
].includes(k)) malformed("invalid settlement");
|
|
304
|
+
if (k === "fail") validateFailure(s.fail);
|
|
305
|
+
if ((k === "adopt" || k === "reissue") && s[k] !== true) malformed("invalid settlement flag");
|
|
306
|
+
}
|
|
307
|
+
return request;
|
|
308
|
+
};
|
|
309
|
+
const decodeShape = (raw) => {
|
|
310
|
+
if (typeof raw === "string") {
|
|
311
|
+
if (raw === "any") return shape.any;
|
|
312
|
+
if (raw === "value") return shape.value;
|
|
313
|
+
if (![
|
|
314
|
+
"nothing",
|
|
315
|
+
"boolean",
|
|
316
|
+
"number",
|
|
317
|
+
"text",
|
|
318
|
+
"bytes",
|
|
319
|
+
"instant",
|
|
320
|
+
"civil date",
|
|
321
|
+
"range",
|
|
322
|
+
"pattern",
|
|
323
|
+
"function"
|
|
324
|
+
].includes(raw)) return malformed("invalid scalar Shape");
|
|
325
|
+
return {
|
|
326
|
+
k: "kind",
|
|
327
|
+
kind: raw
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
const obj = recordObject(raw);
|
|
331
|
+
const keys = Object.keys(obj);
|
|
332
|
+
if (keys.length === 1) {
|
|
333
|
+
const k = keys[0];
|
|
334
|
+
const v = obj[k];
|
|
335
|
+
if (k === "list" || k === "optional") return {
|
|
336
|
+
k,
|
|
337
|
+
of: decodeShape(v)
|
|
338
|
+
};
|
|
339
|
+
if (k === "oneOf" && Array.isArray(v)) return {
|
|
340
|
+
k,
|
|
341
|
+
of: v.map(decodeShape)
|
|
342
|
+
};
|
|
343
|
+
if (k === "object") return {
|
|
344
|
+
k,
|
|
345
|
+
kind: string(v)
|
|
346
|
+
};
|
|
347
|
+
if (k === "quantity") return {
|
|
348
|
+
k,
|
|
349
|
+
unit: string(v)
|
|
350
|
+
};
|
|
351
|
+
if (k === "unitKind") return {
|
|
352
|
+
k,
|
|
353
|
+
kind: string(v)
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
exact(obj, ["map"], ["open"]);
|
|
357
|
+
if (!Array.isArray(obj.map) || "open" in obj && obj.open !== true) return malformed("invalid map Shape");
|
|
358
|
+
const fields = obj.map.map((raw) => {
|
|
359
|
+
const f = exact(raw, ["key", "shape"], ["optional"]);
|
|
360
|
+
if ("optional" in f && f.optional !== true) malformed("invalid optional field");
|
|
361
|
+
return {
|
|
362
|
+
key: string(f.key),
|
|
363
|
+
shape: decodeShape(f.shape),
|
|
364
|
+
optional: f.optional === true
|
|
365
|
+
};
|
|
366
|
+
});
|
|
367
|
+
if (new Set(fields.map((f) => f.key)).size !== fields.length) malformed("duplicate Shape field");
|
|
368
|
+
return {
|
|
369
|
+
k: "map",
|
|
370
|
+
fields,
|
|
371
|
+
open: obj.open === true
|
|
372
|
+
};
|
|
373
|
+
};
|
|
374
|
+
/** Host adapters use this context for object registration and external actions. */
|
|
375
|
+
var SessionObjects = class {
|
|
376
|
+
record;
|
|
377
|
+
recorded;
|
|
378
|
+
enabled;
|
|
379
|
+
group;
|
|
380
|
+
reply;
|
|
381
|
+
items = [];
|
|
382
|
+
kinds = /* @__PURE__ */ new Map();
|
|
383
|
+
declarations = /* @__PURE__ */ new Map();
|
|
384
|
+
objects = /* @__PURE__ */ new Map();
|
|
385
|
+
crossing = 0n;
|
|
386
|
+
exposure = 0n;
|
|
387
|
+
handle = 0n;
|
|
388
|
+
handles = /* @__PURE__ */ new Map();
|
|
389
|
+
supplied = /* @__PURE__ */ new WeakMap();
|
|
390
|
+
replay;
|
|
391
|
+
active = false;
|
|
392
|
+
failure = null;
|
|
393
|
+
traceSaves = /* @__PURE__ */ new Map();
|
|
394
|
+
queuedTraceActions = [];
|
|
395
|
+
constructor(record, recorded, enabled = true) {
|
|
396
|
+
this.record = record;
|
|
397
|
+
this.recorded = recorded;
|
|
398
|
+
this.enabled = enabled;
|
|
399
|
+
this.replay = recorded ? recorded.filter((i) => i.k === "envelope").map((item) => ({
|
|
400
|
+
item,
|
|
401
|
+
index: recorded.indexOf(item),
|
|
402
|
+
envelope: parseEnvelope(item.json),
|
|
403
|
+
consumed: false
|
|
404
|
+
})) : null;
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* A port to build or restore the next Group with. Its controls only count
|
|
408
|
+
* once `attach` adopts the Group, since a restore can still fail after the
|
|
409
|
+
* Core connects it.
|
|
410
|
+
*/
|
|
411
|
+
port(runs) {
|
|
412
|
+
const port = {
|
|
413
|
+
controls: null,
|
|
414
|
+
connect: (c) => {
|
|
415
|
+
port.controls = c;
|
|
416
|
+
},
|
|
417
|
+
runs: (e) => runs?.(e),
|
|
418
|
+
values: (tree) => this.expose(tree)
|
|
419
|
+
};
|
|
420
|
+
return port;
|
|
421
|
+
}
|
|
422
|
+
attach(group, port) {
|
|
423
|
+
this.group = group;
|
|
424
|
+
this.reply = port.controls.reply;
|
|
425
|
+
for (const [key, o] of this.objects) {
|
|
426
|
+
const restored = group.objectById(o.kind.name, o.id);
|
|
427
|
+
if (restored) this.objects.set(key, restored);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
next() {
|
|
431
|
+
const next = this.replay?.find((r) => !r.consumed);
|
|
432
|
+
if (!next) return malformed("missing envelope");
|
|
433
|
+
return next.envelope;
|
|
434
|
+
}
|
|
435
|
+
consume(type) {
|
|
436
|
+
const r = this.replay?.find((r) => !r.consumed);
|
|
437
|
+
if (!r || r.envelope.type !== type) return malformed(`expected ${type}`);
|
|
438
|
+
r.consumed = true;
|
|
439
|
+
this.items.push(r.item);
|
|
440
|
+
this.record(r.item);
|
|
441
|
+
return r.envelope;
|
|
442
|
+
}
|
|
443
|
+
emit(e) {
|
|
444
|
+
const item = {
|
|
445
|
+
k: "envelope",
|
|
446
|
+
json: serialize(e)
|
|
447
|
+
};
|
|
448
|
+
this.items.push(item);
|
|
449
|
+
this.record(item);
|
|
450
|
+
}
|
|
451
|
+
commandCursor = 0;
|
|
452
|
+
beforeCommand(name) {
|
|
453
|
+
const index = this.recorded?.findIndex((item, i) => i >= this.commandCursor && item.k === "input" && (item.source === `:${name}` || item.source.startsWith(`:${name} `) || name === "vars" && this.describeSnapshot(i)));
|
|
454
|
+
if (index === void 0 || index < 0) return;
|
|
455
|
+
this.commandCursor = index + 1;
|
|
456
|
+
while (true) {
|
|
457
|
+
const row = this.replay?.find((r) => !r.consumed);
|
|
458
|
+
if (!row || row.index >= index) break;
|
|
459
|
+
if (row.envelope.type === "input") this.replayInput(true);
|
|
460
|
+
else if (row.envelope.type === "kind") this.registerKind(row.envelope);
|
|
461
|
+
else if (row.envelope.type === "object") this.registerObject(row.envelope);
|
|
462
|
+
else malformed("unmatched crossing before command");
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
describeSnapshot(index) {
|
|
466
|
+
const item = this.recorded?.[index];
|
|
467
|
+
if (item?.k !== "input" || !item.source.startsWith(":describe ")) return false;
|
|
468
|
+
for (const row of this.recorded.slice(index + 1)) {
|
|
469
|
+
if (row.k === "input") break;
|
|
470
|
+
if (row.k === "output" && row.text.startsWith("value ")) return true;
|
|
471
|
+
}
|
|
472
|
+
return false;
|
|
473
|
+
}
|
|
474
|
+
traceInput(name, ids = []) {
|
|
475
|
+
if ([
|
|
476
|
+
"save",
|
|
477
|
+
"restore",
|
|
478
|
+
"vars"
|
|
479
|
+
].includes(name)) this.beforeCommand(name);
|
|
480
|
+
this.registrations();
|
|
481
|
+
const operation = name === "call-value" ? "call" : name === "decide-broadcast" ? "decide" : name;
|
|
482
|
+
const queued = this.queuedTraceActions.findIndex((a) => a.kind === operation && (!a.id || a.id === ids[0]));
|
|
483
|
+
if (queued >= 0) {
|
|
484
|
+
this.queuedTraceActions.splice(queued, 1);
|
|
485
|
+
return true;
|
|
486
|
+
}
|
|
487
|
+
if (this.nextType() !== "input" || recordObject(this.next().request).kind !== operation) return false;
|
|
488
|
+
this.replayInput();
|
|
489
|
+
return true;
|
|
490
|
+
}
|
|
491
|
+
traceObjects() {
|
|
492
|
+
return [...this.objects.values()];
|
|
493
|
+
}
|
|
494
|
+
registrations() {
|
|
495
|
+
while (this.replay && ["kind", "object"].includes(this.nextType() ?? "")) {
|
|
496
|
+
const e = this.next();
|
|
497
|
+
if (e.type === "kind") this.registerKind(e);
|
|
498
|
+
else this.registerObject(e);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
nextType() {
|
|
502
|
+
return this.replay?.find((r) => !r.consumed)?.envelope.type;
|
|
503
|
+
}
|
|
504
|
+
preload() {
|
|
505
|
+
this.registrations();
|
|
506
|
+
if (this.nextType() !== "setup") {
|
|
507
|
+
if (this.replay?.length) malformed("missing setup");
|
|
508
|
+
return {};
|
|
509
|
+
}
|
|
510
|
+
const e = this.consume("setup");
|
|
511
|
+
return Object.fromEntries(Object.entries(recordObject(e.objects)).map(([name, o]) => [name, this.objectRef(o)]));
|
|
512
|
+
}
|
|
513
|
+
initial(bindings) {
|
|
514
|
+
if (this.replay) return;
|
|
515
|
+
if (!this.enabled) return;
|
|
516
|
+
this.emit({
|
|
517
|
+
type: "setup",
|
|
518
|
+
objects: Object.fromEntries(Object.entries(bindings).map(([k, o]) => [k, {
|
|
519
|
+
kind: o.kind.name,
|
|
520
|
+
id: o.id
|
|
521
|
+
}]))
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
defineKind(definition) {
|
|
525
|
+
const props = Object.entries(definition.props).sort(([a], [b]) => compareText(a, b)).map(([name, p]) => ({
|
|
526
|
+
name,
|
|
527
|
+
shape: p.shape ? shapeData(p.shape) : "any",
|
|
528
|
+
readOnly: !p.set,
|
|
529
|
+
getCost: {
|
|
530
|
+
fuel: p.getCost?.fuel ?? 0,
|
|
531
|
+
alloc: p.getCost?.alloc ?? 0
|
|
532
|
+
},
|
|
533
|
+
...p.set ? { setCost: {
|
|
534
|
+
fuel: p.setCost?.fuel ?? 0,
|
|
535
|
+
alloc: p.setCost?.alloc ?? 0
|
|
536
|
+
} } : {}
|
|
537
|
+
}));
|
|
538
|
+
const elements = definition.elements;
|
|
539
|
+
const declaration = {
|
|
540
|
+
type: "kind",
|
|
541
|
+
name: definition.name,
|
|
542
|
+
props,
|
|
543
|
+
parentKinds: definition.parentKinds ?? [],
|
|
544
|
+
...elements ? { elements: {
|
|
545
|
+
shape: shapeData(elements.shape),
|
|
546
|
+
countCost: costFrame(elements.countCost),
|
|
547
|
+
atCost: costFrame(elements.atCost),
|
|
548
|
+
findCost: costFrame(elements.findCost)
|
|
549
|
+
} } : {}
|
|
550
|
+
};
|
|
551
|
+
const encoded = serialize(declaration);
|
|
552
|
+
const old = this.declarations.get(definition.name);
|
|
553
|
+
if (old) {
|
|
554
|
+
if (old !== encoded) malformed("conflicting kind registration");
|
|
555
|
+
return this.kinds.get(definition.name);
|
|
556
|
+
}
|
|
557
|
+
const wrapped = Object.fromEntries(Object.entries(definition.props).map(([name, p]) => [name, {
|
|
558
|
+
...p,
|
|
559
|
+
get: (o) => this.property(o, name, "get", () => p.get(o)),
|
|
560
|
+
...p.set ? { set: (o, v) => {
|
|
561
|
+
this.property(o, name, "set", () => {
|
|
562
|
+
p.set(o, v);
|
|
563
|
+
}, v);
|
|
564
|
+
} } : {}
|
|
565
|
+
}]));
|
|
566
|
+
const kind = defineObjectKind({
|
|
567
|
+
...definition,
|
|
568
|
+
props: wrapped,
|
|
569
|
+
...elements ? { elements: {
|
|
570
|
+
...elements,
|
|
571
|
+
count: (o) => this.property(o, "elements", "count", () => elements.count(o)),
|
|
572
|
+
at: (o, index) => this.property(o, "elements", "at", () => elements.at(o, index), void 0, num(index)),
|
|
573
|
+
find: (o, name) => this.property(o, "elements", "find", () => elements.find(o, name), void 0, text(name))
|
|
574
|
+
} } : {}
|
|
575
|
+
});
|
|
576
|
+
this.kinds.set(kind.name, kind);
|
|
577
|
+
this.declarations.set(kind.name, encoded);
|
|
578
|
+
if (!this.replay) this.emit(declaration);
|
|
579
|
+
return kind;
|
|
580
|
+
}
|
|
581
|
+
object(kind, id, native) {
|
|
582
|
+
if (this.kinds.get(kind.name) !== kind) malformed("kind must be registered through SessionObjects");
|
|
583
|
+
const key = identity({
|
|
584
|
+
kind: kind.name,
|
|
585
|
+
id
|
|
586
|
+
});
|
|
587
|
+
const old = this.objects.get(key);
|
|
588
|
+
if (old) {
|
|
589
|
+
if (old.kind !== kind) malformed("conflicting object");
|
|
590
|
+
return old;
|
|
591
|
+
}
|
|
592
|
+
const o = this.group.object(kind, id, native);
|
|
593
|
+
this.objects.set(key, o);
|
|
594
|
+
if (!this.replay) this.emit({
|
|
595
|
+
type: "object",
|
|
596
|
+
object: {
|
|
597
|
+
kind: kind.name,
|
|
598
|
+
id
|
|
599
|
+
}
|
|
600
|
+
});
|
|
601
|
+
return o;
|
|
602
|
+
}
|
|
603
|
+
registerKind(e) {
|
|
604
|
+
this.consume("kind");
|
|
605
|
+
const name = string(e.name);
|
|
606
|
+
if (this.kinds.has(name)) return malformed("duplicate kind registration");
|
|
607
|
+
const props = Object.fromEntries(e.props.map((p) => [string(p.name), {
|
|
608
|
+
shape: decodeShape(p.shape),
|
|
609
|
+
getCost: validateCost(p.getCost),
|
|
610
|
+
get: () => {
|
|
611
|
+
throw new Error("external getter in replay");
|
|
612
|
+
},
|
|
613
|
+
...!p.readOnly ? {
|
|
614
|
+
setCost: validateCost(p.setCost),
|
|
615
|
+
set: () => {}
|
|
616
|
+
} : {}
|
|
617
|
+
}]));
|
|
618
|
+
const elements = e.elements === void 0 ? void 0 : (() => {
|
|
619
|
+
const d = exact(e.elements, [
|
|
620
|
+
"shape",
|
|
621
|
+
"countCost",
|
|
622
|
+
"atCost",
|
|
623
|
+
"findCost"
|
|
624
|
+
]);
|
|
625
|
+
return {
|
|
626
|
+
shape: decodeShape(d.shape),
|
|
627
|
+
countCost: validateCost(d.countCost),
|
|
628
|
+
atCost: validateCost(d.atCost),
|
|
629
|
+
findCost: validateCost(d.findCost),
|
|
630
|
+
count: externalCollection,
|
|
631
|
+
at: externalCollection,
|
|
632
|
+
find: externalCollection
|
|
633
|
+
};
|
|
634
|
+
})();
|
|
635
|
+
this.defineKind({
|
|
636
|
+
name,
|
|
637
|
+
parentKinds: e.parentKinds,
|
|
638
|
+
props,
|
|
639
|
+
...elements ? { elements } : {}
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
registerObject(e) {
|
|
643
|
+
this.consume("object");
|
|
644
|
+
const r = ref(e.object);
|
|
645
|
+
if (this.objects.has(identity(r))) malformed("duplicate object registration");
|
|
646
|
+
const kind = this.kinds.get(r.kind);
|
|
647
|
+
if (!kind) return malformed("unknown kind");
|
|
648
|
+
this.object(kind, r.id, {});
|
|
649
|
+
}
|
|
650
|
+
objectRef(raw) {
|
|
651
|
+
const r = ref(raw);
|
|
652
|
+
return this.objects.get(identity(r)) ?? malformed("unknown object");
|
|
653
|
+
}
|
|
654
|
+
property(o, name, operation, callback, value, selector) {
|
|
655
|
+
try {
|
|
656
|
+
return this.propertyCrossing(o, name, operation, callback, value, selector);
|
|
657
|
+
} catch (error) {
|
|
658
|
+
if (this.replay && error instanceof TranscriptError) this.failure = error;
|
|
659
|
+
throw error;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
propertyCrossing(o, name, operation, callback, value, selector) {
|
|
663
|
+
if (this.active) return malformed("reentrant property callback");
|
|
664
|
+
if (operation === "set") this.expose(listValues([value]));
|
|
665
|
+
const crossing = ++this.crossing;
|
|
666
|
+
const begin = {
|
|
667
|
+
type: "property-begin",
|
|
668
|
+
crossing: integer(crossing),
|
|
669
|
+
object: {
|
|
670
|
+
kind: o.kind.name,
|
|
671
|
+
id: o.id
|
|
672
|
+
},
|
|
673
|
+
property: name,
|
|
674
|
+
operation,
|
|
675
|
+
...value ? { value: encoded(this.encode(value)) } : {},
|
|
676
|
+
...selector ? { selector: encoded(this.encode(selector)) } : {}
|
|
677
|
+
};
|
|
678
|
+
if (this.replay) {
|
|
679
|
+
const e = this.consume("property-begin");
|
|
680
|
+
if (serialize({
|
|
681
|
+
...e,
|
|
682
|
+
...value ? { value: encoded(jsonSource(nodeAt(e, "value"))) } : {},
|
|
683
|
+
...selector ? { selector: encoded(jsonSource(nodeAt(e, "selector"))) } : {}
|
|
684
|
+
}) !== serialize(begin)) malformed("unmatched property crossing");
|
|
685
|
+
this.active = true;
|
|
686
|
+
try {
|
|
687
|
+
while ([
|
|
688
|
+
"kind",
|
|
689
|
+
"object",
|
|
690
|
+
"input"
|
|
691
|
+
].includes(this.nextType() ?? "")) if (this.nextType() === "input") this.replayInput();
|
|
692
|
+
else this.registrations();
|
|
693
|
+
const end = this.consume("property-end");
|
|
694
|
+
if (counter(end.crossing) !== crossing) malformed("out-of-order property end");
|
|
695
|
+
const reply = recordObject(end.reply);
|
|
696
|
+
if ("value" in reply) {
|
|
697
|
+
if (operation === "set") malformed("value for setter");
|
|
698
|
+
return this.decode(nodeAt(end, "reply", "value"));
|
|
699
|
+
}
|
|
700
|
+
if ("ok" in reply) {
|
|
701
|
+
if (operation !== "set" || reply.ok !== true) malformed("invalid ok");
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
if ("fail" in reply) {
|
|
705
|
+
const f = exact(reply.fail, [
|
|
706
|
+
"code",
|
|
707
|
+
"message",
|
|
708
|
+
"data"
|
|
709
|
+
]);
|
|
710
|
+
throw new ScriptError(string(f.code), string(f.message), this.decode(nodeAt(end, "reply", "fail", "data")));
|
|
711
|
+
}
|
|
712
|
+
throw new Error("Recorded Host property failure");
|
|
713
|
+
} catch (error) {
|
|
714
|
+
if (error instanceof TranscriptError) this.failure = error;
|
|
715
|
+
throw error;
|
|
716
|
+
} finally {
|
|
717
|
+
this.active = false;
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
this.emit(begin);
|
|
721
|
+
this.active = true;
|
|
722
|
+
try {
|
|
723
|
+
const result = callback();
|
|
724
|
+
this.emit({
|
|
725
|
+
type: "property-end",
|
|
726
|
+
crossing: integer(crossing),
|
|
727
|
+
reply: operation === "set" ? { ok: true } : { value: encoded(this.encode(result)) }
|
|
728
|
+
});
|
|
729
|
+
return result;
|
|
730
|
+
} catch (error) {
|
|
731
|
+
this.emit({
|
|
732
|
+
type: "property-end",
|
|
733
|
+
crossing: integer(crossing),
|
|
734
|
+
reply: error instanceof ScriptError ? { fail: {
|
|
735
|
+
code: error.code,
|
|
736
|
+
message: error.message,
|
|
737
|
+
data: encoded(this.encode(error.data))
|
|
738
|
+
} } : { hostError: true }
|
|
739
|
+
});
|
|
740
|
+
throw error;
|
|
741
|
+
} finally {
|
|
742
|
+
this.active = false;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
encode(value) {
|
|
746
|
+
if (value.kind === "object") {
|
|
747
|
+
const o = value.asObjectRef();
|
|
748
|
+
if (!this.objects.has(identity(o))) malformed("object must be registered through SessionObjects");
|
|
749
|
+
}
|
|
750
|
+
if (value.kind === "function") {
|
|
751
|
+
const handle = this.supplied.get(value);
|
|
752
|
+
if (!handle || !this.handles.has(handle)) return malformed("unexposed or invalidated function");
|
|
753
|
+
return `{"$sessionFunction":${quoteJSON(handle)}}`;
|
|
754
|
+
}
|
|
755
|
+
if (value.kind === "list") return `[${Array.from({ length: value.length }, (_, i) => this.encode(value.index(i + 1))).join(",")}]`;
|
|
756
|
+
if (value.kind === "map") {
|
|
757
|
+
const ps = value.entries();
|
|
758
|
+
return ps.some(([k]) => k.startsWith("$")) ? `{"$map":[${ps.map(([k, v]) => `[${quoteJSON(k)},${this.encode(v)}]`).join(",")}]}` : `{${ps.map(([k, v]) => `${quoteJSON(k)}:${this.encode(v)}`).join(",")}}`;
|
|
759
|
+
}
|
|
760
|
+
return encodeValue(value);
|
|
761
|
+
}
|
|
762
|
+
decode(raw) {
|
|
763
|
+
try {
|
|
764
|
+
return decodeValue(jsonSource(raw), (kind, id) => this.objectRef({
|
|
765
|
+
kind,
|
|
766
|
+
id
|
|
767
|
+
}).value, (h) => this.handles.get(h) ?? malformed("unresolved function handle"));
|
|
768
|
+
} catch (error) {
|
|
769
|
+
return malformed(`invalid crossing Value: ${error instanceof Error ? error.message : String(error)}`);
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
expose(tree) {
|
|
773
|
+
const exposure = ++this.exposure;
|
|
774
|
+
if (!this.enabled) return;
|
|
775
|
+
const walk = (raw, path) => {
|
|
776
|
+
if (Value.isValue(raw)) {
|
|
777
|
+
if (raw.kind === "function") {
|
|
778
|
+
const handle = `f${++this.handle}`;
|
|
779
|
+
if (this.replay) {
|
|
780
|
+
const e = this.consume("function");
|
|
781
|
+
if (e.handle !== handle || counter(e.exposure) !== exposure || serialize(e.path) !== serialize(path)) malformed("invalid function exposure/path");
|
|
782
|
+
} else this.emit({
|
|
783
|
+
type: "function",
|
|
784
|
+
handle,
|
|
785
|
+
exposure: integer(exposure),
|
|
786
|
+
path
|
|
787
|
+
});
|
|
788
|
+
this.handles.set(handle, raw);
|
|
789
|
+
this.supplied.set(raw, handle);
|
|
790
|
+
} else if (raw.kind === "list") for (let i = 0; i < raw.length; i++) walk(raw.index(i + 1), [...path, i]);
|
|
791
|
+
else if (raw.kind === "map") for (const [k, v] of raw.entries()) walk(v, [...path, k]);
|
|
792
|
+
return;
|
|
793
|
+
}
|
|
794
|
+
if (Array.isArray(raw)) raw.forEach((v, i) => walk(v, [...path, i]));
|
|
795
|
+
else if (raw && typeof raw === "object") for (const [k, v] of Object.entries(raw)) walk(v, [...path, k]);
|
|
796
|
+
};
|
|
797
|
+
walk(tree, []);
|
|
798
|
+
if (this.nextType() === "function" && counter(this.next().exposure) <= exposure) malformed("path is not a Function Value");
|
|
799
|
+
}
|
|
800
|
+
reports(reports) {
|
|
801
|
+
if (this.failure) throw this.failure;
|
|
802
|
+
for (const report of reports) this.expose(report);
|
|
803
|
+
}
|
|
804
|
+
snapshot(scripts) {
|
|
805
|
+
this.expose(Object.fromEntries(scripts.map((s) => [s.name, Object.fromEntries(s.vars)])));
|
|
806
|
+
}
|
|
807
|
+
resolve(kind, id, resolve) {
|
|
808
|
+
const object = {
|
|
809
|
+
kind,
|
|
810
|
+
id
|
|
811
|
+
};
|
|
812
|
+
if (this.replay) {
|
|
813
|
+
if (!this.resolving.length) {
|
|
814
|
+
const e = this.consume("resolve");
|
|
815
|
+
this.resolving = [...e.objects];
|
|
816
|
+
}
|
|
817
|
+
const index = this.resolving.findIndex((r) => identity(r.object) === identity(object));
|
|
818
|
+
const row = index < 0 ? void 0 : this.resolving.splice(index, 1)[0];
|
|
819
|
+
if (!row || identity(row.object) !== identity(object)) malformed("resolver order mismatch");
|
|
820
|
+
return row.resolved ? { native: {} } : void 0;
|
|
821
|
+
}
|
|
822
|
+
const result = resolve?.(kind, id);
|
|
823
|
+
this.outcomes.push({
|
|
824
|
+
object,
|
|
825
|
+
resolved: !!result
|
|
826
|
+
});
|
|
827
|
+
return result;
|
|
828
|
+
}
|
|
829
|
+
resolving = [];
|
|
830
|
+
outcomes = [];
|
|
831
|
+
crossesHandles() {
|
|
832
|
+
const contains = (raw) => {
|
|
833
|
+
if (isJsonObject(raw)) {
|
|
834
|
+
if (raw.pairs.length === 1 && raw.pairs[0][0] === "$sessionFunction" && typeof raw.pairs[0][1] === "string") return this.handles.has(raw.pairs[0][1]);
|
|
835
|
+
return raw.pairs.some(([, v]) => contains(v));
|
|
836
|
+
}
|
|
837
|
+
return Array.isArray(raw) && raw.some(contains);
|
|
838
|
+
};
|
|
839
|
+
return !!this.replay?.some((r) => !r.consumed && contains(readOrderedJSON(r.item.json)));
|
|
840
|
+
}
|
|
841
|
+
saved(name) {
|
|
842
|
+
this.traceSaves.set(name, [...this.queuedTraceActions]);
|
|
843
|
+
}
|
|
844
|
+
restored(name) {
|
|
845
|
+
if (name) this.queuedTraceActions = [...this.traceSaves.get(name) ?? []];
|
|
846
|
+
if (this.replay && this.resolving.length) malformed("leftover resolver outcomes");
|
|
847
|
+
if (this.outcomes.length) {
|
|
848
|
+
this.outcomes.sort((a, b) => compareText(a.object.kind, b.object.kind) || compareText(a.object.id, b.object.id));
|
|
849
|
+
this.emit({
|
|
850
|
+
type: "resolve",
|
|
851
|
+
objects: this.outcomes
|
|
852
|
+
});
|
|
853
|
+
this.outcomes = [];
|
|
854
|
+
}
|
|
855
|
+
this.handles.clear();
|
|
856
|
+
this.supplied = /* @__PURE__ */ new WeakMap();
|
|
857
|
+
}
|
|
858
|
+
action(request) {
|
|
859
|
+
const convert = (raw) => Value.isValue(raw) ? encoded(this.encode(raw)) : Array.isArray(raw) ? raw.map(convert) : raw && typeof raw === "object" ? Object.fromEntries(Object.entries(raw).map(([k, v]) => [k, convert(v)])) : raw;
|
|
860
|
+
request = convert(request);
|
|
861
|
+
const result = this.perform(request);
|
|
862
|
+
if (!this.replay) this.emit({
|
|
863
|
+
type: "input",
|
|
864
|
+
request,
|
|
865
|
+
reply: result
|
|
866
|
+
});
|
|
867
|
+
return result;
|
|
868
|
+
}
|
|
869
|
+
replayInput(track = false) {
|
|
870
|
+
const e = this.consume("input");
|
|
871
|
+
const request = recordObject(e.request);
|
|
872
|
+
const actual = this.perform(request, e);
|
|
873
|
+
if (this.active || track) {
|
|
874
|
+
const ok = actual.ok;
|
|
875
|
+
this.queuedTraceActions.push({
|
|
876
|
+
kind: string(request.kind),
|
|
877
|
+
id: ok?.delivery ?? ok?.broadcast
|
|
878
|
+
});
|
|
879
|
+
}
|
|
880
|
+
if (serialize(actual) !== serialize(e.reply)) malformed(`Host action reply mismatch: actual ${serialize(actual)} expected ${serialize(e.reply)}`);
|
|
881
|
+
}
|
|
882
|
+
drain(item) {
|
|
883
|
+
const row = this.replay?.find((r) => r.item === item);
|
|
884
|
+
if (!row || row.consumed) return;
|
|
885
|
+
if (row.envelope.type !== "input" && !["kind", "object"].includes(row.envelope.type)) malformed("unmatched envelope");
|
|
886
|
+
if (row.envelope.type === "input") this.replayInput();
|
|
887
|
+
else this.registrations();
|
|
888
|
+
}
|
|
889
|
+
finish() {
|
|
890
|
+
if (this.replay?.some((r) => !r.consumed)) malformed("leftover envelopes");
|
|
891
|
+
this.replay = null;
|
|
892
|
+
}
|
|
893
|
+
perform(request, e) {
|
|
894
|
+
const kind = string(request.kind);
|
|
895
|
+
validateRequest(request);
|
|
896
|
+
const val = (...path) => e ? this.decode(nodeAt(e, "request", ...path)) : this.decode(readOrderedJSON(serialize(path.reduce((o, k) => Array.isArray(o) && typeof k === "number" ? o[k] : recordObject(o)[k], request))));
|
|
897
|
+
const message = () => {
|
|
898
|
+
const m = exact(request.message, ["name"], ["args", "limits"]);
|
|
899
|
+
return {
|
|
900
|
+
name: string(m.name),
|
|
901
|
+
...m.args ? { args: Array.from({ length: m.args.length }, (_, i) => val("message", "args", i)) } : {},
|
|
902
|
+
...m.limits ? { limits: m.limits } : {}
|
|
903
|
+
};
|
|
904
|
+
};
|
|
905
|
+
const target = () => {
|
|
906
|
+
const to = recordObject(request.to);
|
|
907
|
+
if (Object.keys(to).length !== 1) malformed("invalid target");
|
|
908
|
+
return "script" in to ? this.group.script(string(to.script)) ?? malformed("unknown script") : this.objectRef(to.object);
|
|
909
|
+
};
|
|
910
|
+
const script = () => this.group.script(string(request.script)) ?? malformed("unknown script");
|
|
911
|
+
try {
|
|
912
|
+
switch (kind) {
|
|
913
|
+
case "set-parent":
|
|
914
|
+
this.group.setParent(this.objectRef(request.object), request.parent === null ? void 0 : this.objectRef(request.parent));
|
|
915
|
+
break;
|
|
916
|
+
case "dispose":
|
|
917
|
+
this.group.dispose(this.objectRef(request.object));
|
|
918
|
+
break;
|
|
919
|
+
case "deliver":
|
|
920
|
+
case "request":
|
|
921
|
+
case "decide": {
|
|
922
|
+
if (kind === "decide" && request.broadcast === true) return { ok: { broadcast: this.group.decideBroadcast(message()).id } };
|
|
923
|
+
const t = target(), m = message();
|
|
924
|
+
const result = "name" in t ? t[kind](m) : kind === "deliver" ? this.group.deliver(t, m) : kind === "request" ? this.group.request(t, m) : this.group.decide(t, m);
|
|
925
|
+
return { ok: { delivery: typeof result === "string" ? result : result.id } };
|
|
926
|
+
}
|
|
927
|
+
case "broadcast": return { ok: { broadcast: this.group.broadcast(message()) } };
|
|
928
|
+
case "call": return { ok: { delivery: this.group.call(val("fn"), request.args.map((_, i) => val("args", i)), { limits: request.limits }).id } };
|
|
929
|
+
case "cancel-delivery":
|
|
930
|
+
this.group.cancelDelivery(string(request.delivery));
|
|
931
|
+
break;
|
|
932
|
+
case "stop":
|
|
933
|
+
script().stop(string(request.reason));
|
|
934
|
+
break;
|
|
935
|
+
case "cancel-run":
|
|
936
|
+
script().cancelRun(string(request.run));
|
|
937
|
+
break;
|
|
938
|
+
case "revoke":
|
|
939
|
+
script().revoke(string(request.grant));
|
|
940
|
+
break;
|
|
941
|
+
case "answer":
|
|
942
|
+
this.reply(string(request.call), {
|
|
943
|
+
k: "answer",
|
|
944
|
+
value: val("value"),
|
|
945
|
+
fuel: Number(request.fuel ?? 0)
|
|
946
|
+
});
|
|
947
|
+
break;
|
|
948
|
+
case "fail": {
|
|
949
|
+
const f = exact(request.error, [
|
|
950
|
+
"code",
|
|
951
|
+
"message",
|
|
952
|
+
"data"
|
|
953
|
+
]);
|
|
954
|
+
this.reply(string(request.call), {
|
|
955
|
+
k: "fail",
|
|
956
|
+
error: new ScriptError(string(f.code), string(f.message), val("error", "data"))
|
|
957
|
+
});
|
|
958
|
+
break;
|
|
959
|
+
}
|
|
960
|
+
case "settle": {
|
|
961
|
+
const s = recordObject(request.settlement);
|
|
962
|
+
if (Object.keys(s).length !== 1) malformed("invalid settlement");
|
|
963
|
+
this.group.settle(string(request.call), "answer" in s ? { answer: val("settlement", "answer") } : "reissue" in s ? { reissue: true } : "adopt" in s ? { adopt: true } : { fail: new ScriptError(string(recordObject(s.fail).code), string(recordObject(s.fail).message), val("settlement", "fail", "data")) });
|
|
964
|
+
break;
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
return { ok: {} };
|
|
968
|
+
} catch (error) {
|
|
969
|
+
if (error instanceof HostError) return { error: error.code };
|
|
970
|
+
throw error;
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
//#endregion
|
|
975
|
+
//#region src/generated/builtin-docs.ts
|
|
976
|
+
const builtinDocs = {
|
|
977
|
+
"min": {
|
|
978
|
+
"call": "min(x, …)",
|
|
979
|
+
"gives": "The least of its arguments under `<`, the first of equal ones; a lone list argument gives the least of its items"
|
|
980
|
+
},
|
|
981
|
+
"max": {
|
|
982
|
+
"call": "max(x, …)",
|
|
983
|
+
"gives": "The greatest of its arguments under `<`, the first of equal ones; a lone list argument gives the greatest of its items"
|
|
984
|
+
},
|
|
985
|
+
"codePoint": {
|
|
986
|
+
"call": "codePoint(c)",
|
|
987
|
+
"gives": "The code point of `c`, a text of exactly one code point, as a number"
|
|
988
|
+
},
|
|
989
|
+
"fromCodePoint": {
|
|
990
|
+
"call": "fromCodePoint(n)",
|
|
991
|
+
"gives": "The text of the code point `n`, normalised to NFC"
|
|
992
|
+
},
|
|
993
|
+
"upper": {
|
|
994
|
+
"call": "upper(s)",
|
|
995
|
+
"gives": "`s` under Unicode full default uppercase mapping, then NFC"
|
|
996
|
+
},
|
|
997
|
+
"lower": {
|
|
998
|
+
"call": "lower(s)",
|
|
999
|
+
"gives": "`s` under Unicode full default lowercase mapping, then NFC"
|
|
1000
|
+
},
|
|
1001
|
+
"offset": {
|
|
1002
|
+
"call": "offset(needle, s)",
|
|
1003
|
+
"gives": "The Character position where the leftmost match of `needle`, a text or a Text Pattern, starts in `s`, or 0 if there is none"
|
|
1004
|
+
},
|
|
1005
|
+
"isDisposed": {
|
|
1006
|
+
"call": "isDisposed(o)",
|
|
1007
|
+
"gives": "Whether the Host Object `o` has been disposed"
|
|
1008
|
+
},
|
|
1009
|
+
"objectKind": {
|
|
1010
|
+
"call": "objectKind(o)",
|
|
1011
|
+
"gives": "The name of the Object Kind of the Host Object `o`, as text"
|
|
1012
|
+
},
|
|
1013
|
+
"rangeStart": {
|
|
1014
|
+
"call": "rangeStart(r)",
|
|
1015
|
+
"gives": "The first end of the range `r`, as written"
|
|
1016
|
+
},
|
|
1017
|
+
"rangeEnd": {
|
|
1018
|
+
"call": "rangeEnd(r)",
|
|
1019
|
+
"gives": "The second end of the range `r`, as written"
|
|
1020
|
+
},
|
|
1021
|
+
"kindOf": {
|
|
1022
|
+
"call": "kindOf(x)",
|
|
1023
|
+
"gives": "The name of the kind of `x`, as text, such as `\"number\"` or `\"civil date\"`"
|
|
1024
|
+
},
|
|
1025
|
+
"conforms": {
|
|
1026
|
+
"call": "conforms(value, shape)",
|
|
1027
|
+
"gives": "Whether `value` fits the Shape `shape`"
|
|
1028
|
+
},
|
|
1029
|
+
"check": {
|
|
1030
|
+
"call": "check(value, shape)",
|
|
1031
|
+
"gives": "`value` unchanged, if it fits the Shape `shape`; raises the first mismatch otherwise"
|
|
1032
|
+
},
|
|
1033
|
+
"explain": {
|
|
1034
|
+
"call": "explain(value, shape)",
|
|
1035
|
+
"gives": "The list of every mismatch of `value` against the Shape `shape`, empty if it fits"
|
|
1036
|
+
},
|
|
1037
|
+
"functionArity": {
|
|
1038
|
+
"call": "functionArity(f)",
|
|
1039
|
+
"gives": "The range of argument counts the Function Value `f` accepts, from its required parameters to all of them"
|
|
1040
|
+
},
|
|
1041
|
+
"functionName": {
|
|
1042
|
+
"call": "functionName(f)",
|
|
1043
|
+
"gives": "The name of the function the Function Value `f` was made from, as defined, or Nothing for a Lambda"
|
|
1044
|
+
},
|
|
1045
|
+
"abs": {
|
|
1046
|
+
"call": "abs(x)",
|
|
1047
|
+
"gives": "`x` without its sign"
|
|
1048
|
+
},
|
|
1049
|
+
"floor": {
|
|
1050
|
+
"call": "floor(x)",
|
|
1051
|
+
"gives": "The greatest integer at or below `x`"
|
|
1052
|
+
},
|
|
1053
|
+
"ceiling": {
|
|
1054
|
+
"call": "ceiling(x)",
|
|
1055
|
+
"gives": "The least integer at or above `x`"
|
|
1056
|
+
},
|
|
1057
|
+
"truncate": {
|
|
1058
|
+
"call": "truncate(x)",
|
|
1059
|
+
"gives": "`x` with its fraction dropped, toward zero"
|
|
1060
|
+
},
|
|
1061
|
+
"round": {
|
|
1062
|
+
"call": "round(x, places = 0, mode = \"half up\")",
|
|
1063
|
+
"gives": "`x` rounded to `places` digits after the point, by `mode`"
|
|
1064
|
+
},
|
|
1065
|
+
"sqrt": {
|
|
1066
|
+
"call": "sqrt(x)",
|
|
1067
|
+
"gives": "The square root of `x`"
|
|
1068
|
+
},
|
|
1069
|
+
"exp": {
|
|
1070
|
+
"call": "exp(x)",
|
|
1071
|
+
"gives": "e to the power `x`"
|
|
1072
|
+
},
|
|
1073
|
+
"ln": {
|
|
1074
|
+
"call": "ln(x)",
|
|
1075
|
+
"gives": "The natural logarithm of `x`"
|
|
1076
|
+
},
|
|
1077
|
+
"log10": {
|
|
1078
|
+
"call": "log10(x)",
|
|
1079
|
+
"gives": "The base-10 logarithm of `x`"
|
|
1080
|
+
},
|
|
1081
|
+
"power": {
|
|
1082
|
+
"call": "power(x, y)",
|
|
1083
|
+
"gives": "`x` to the power `y`"
|
|
1084
|
+
},
|
|
1085
|
+
"sin": {
|
|
1086
|
+
"call": "sin(x)",
|
|
1087
|
+
"gives": "The sine of `x` radians"
|
|
1088
|
+
},
|
|
1089
|
+
"cos": {
|
|
1090
|
+
"call": "cos(x)",
|
|
1091
|
+
"gives": "The cosine of `x` radians"
|
|
1092
|
+
},
|
|
1093
|
+
"tan": {
|
|
1094
|
+
"call": "tan(x)",
|
|
1095
|
+
"gives": "The tangent of `x` radians"
|
|
1096
|
+
},
|
|
1097
|
+
"asin": {
|
|
1098
|
+
"call": "asin(x)",
|
|
1099
|
+
"gives": "The arcsine of `x`, in radians from -pi/2 to pi/2"
|
|
1100
|
+
},
|
|
1101
|
+
"acos": {
|
|
1102
|
+
"call": "acos(x)",
|
|
1103
|
+
"gives": "The arccosine of `x`, in radians from 0 to pi"
|
|
1104
|
+
},
|
|
1105
|
+
"atan": {
|
|
1106
|
+
"call": "atan(x)",
|
|
1107
|
+
"gives": "The arctangent of `x`, in radians between -pi/2 and pi/2"
|
|
1108
|
+
},
|
|
1109
|
+
"atan2": {
|
|
1110
|
+
"call": "atan2(y, x)",
|
|
1111
|
+
"gives": "The angle of the point (`x`, `y`) from the positive x-axis, in radians above -pi and at most pi"
|
|
1112
|
+
},
|
|
1113
|
+
"degrees": {
|
|
1114
|
+
"call": "degrees(x)",
|
|
1115
|
+
"gives": "`x` radians in degrees"
|
|
1116
|
+
},
|
|
1117
|
+
"radians": {
|
|
1118
|
+
"call": "radians(x)",
|
|
1119
|
+
"gives": "`x` degrees in radians"
|
|
1120
|
+
},
|
|
1121
|
+
"random": {
|
|
1122
|
+
"call": "random(n)",
|
|
1123
|
+
"gives": "A whole number from 1 to `n`, the next from the Script Group's generator"
|
|
1124
|
+
},
|
|
1125
|
+
"fromFloat64": {
|
|
1126
|
+
"call": "fromFloat64(b, order = \"big\")",
|
|
1127
|
+
"gives": "The number an IEEE 754 binary64 float in the 8 Bytes `b` holds, as its shortest round-trip decimal"
|
|
1128
|
+
},
|
|
1129
|
+
"fromFloat32": {
|
|
1130
|
+
"call": "fromFloat32(b, order = \"big\")",
|
|
1131
|
+
"gives": "The number an IEEE 754 binary32 float in the 4 Bytes `b` holds, as its shortest round-trip decimal"
|
|
1132
|
+
},
|
|
1133
|
+
"toFloat64": {
|
|
1134
|
+
"call": "toFloat64(n, order = \"big\")",
|
|
1135
|
+
"gives": "The 8 Bytes of the binary64 float nearest `n`, ties to even"
|
|
1136
|
+
},
|
|
1137
|
+
"toFloat32": {
|
|
1138
|
+
"call": "toFloat32(n, order = \"big\")",
|
|
1139
|
+
"gives": "The 4 Bytes of the binary32 float nearest `n`, ties to even"
|
|
1140
|
+
},
|
|
1141
|
+
"year": {
|
|
1142
|
+
"call": "year(d)",
|
|
1143
|
+
"gives": "The year of the Civil Date `d`, from 1 to 9999"
|
|
1144
|
+
},
|
|
1145
|
+
"month": {
|
|
1146
|
+
"call": "month(d)",
|
|
1147
|
+
"gives": "The month of `d`, from 1 to 12"
|
|
1148
|
+
},
|
|
1149
|
+
"day": {
|
|
1150
|
+
"call": "day(d)",
|
|
1151
|
+
"gives": "The day of the month of `d`, from 1 to 31"
|
|
1152
|
+
},
|
|
1153
|
+
"hour": {
|
|
1154
|
+
"call": "hour(d)",
|
|
1155
|
+
"gives": "The hour of the date-time `d`, from 0 to 23"
|
|
1156
|
+
},
|
|
1157
|
+
"minute": {
|
|
1158
|
+
"call": "minute(d)",
|
|
1159
|
+
"gives": "The minute of the date-time `d`, from 0 to 59"
|
|
1160
|
+
},
|
|
1161
|
+
"second": {
|
|
1162
|
+
"call": "second(d)",
|
|
1163
|
+
"gives": "The whole seconds of the date-time `d`, from 0 to 59"
|
|
1164
|
+
},
|
|
1165
|
+
"microsecond": {
|
|
1166
|
+
"call": "microsecond(d)",
|
|
1167
|
+
"gives": "The fraction of a second of the date-time `d`, in whole microseconds from 0 to 999999"
|
|
1168
|
+
},
|
|
1169
|
+
"weekday": {
|
|
1170
|
+
"call": "weekday(d)",
|
|
1171
|
+
"gives": "The ISO 8601 day of the week of `d`, 1 for Monday to 7 for Sunday"
|
|
1172
|
+
},
|
|
1173
|
+
"dayOfYear": {
|
|
1174
|
+
"call": "dayOfYear(d)",
|
|
1175
|
+
"gives": "The day of the year of `d`, from 1 to 366"
|
|
1176
|
+
},
|
|
1177
|
+
"isoWeek": {
|
|
1178
|
+
"call": "isoWeek(d)",
|
|
1179
|
+
"gives": "The ISO 8601 week number of `d`, from 1 to 53"
|
|
1180
|
+
},
|
|
1181
|
+
"isoWeekYear": {
|
|
1182
|
+
"call": "isoWeekYear(d)",
|
|
1183
|
+
"gives": "The ISO 8601 week-numbering year of `d`"
|
|
1184
|
+
},
|
|
1185
|
+
"hasTime": {
|
|
1186
|
+
"call": "hasTime(d)",
|
|
1187
|
+
"gives": "Whether the Civil Date `d` has a time of day"
|
|
1188
|
+
},
|
|
1189
|
+
"toCivil": {
|
|
1190
|
+
"call": "toCivil(i, offset)",
|
|
1191
|
+
"gives": "The date-time on the wall clock at `offset` from UTC at the Instant `i`"
|
|
1192
|
+
},
|
|
1193
|
+
"toInstant": {
|
|
1194
|
+
"call": "toInstant(c, offset)",
|
|
1195
|
+
"gives": "The Instant at which the wall clock at `offset` from UTC reads the date-time `c`"
|
|
1196
|
+
},
|
|
1197
|
+
"pi": {
|
|
1198
|
+
"call": "3.141592653589793238462643383279503",
|
|
1199
|
+
"gives": "pi, rounded half-even to 34 digits"
|
|
1200
|
+
},
|
|
1201
|
+
"newline": {
|
|
1202
|
+
"call": "U+000A",
|
|
1203
|
+
"gives": "A line feed, as text"
|
|
1204
|
+
},
|
|
1205
|
+
"tab": {
|
|
1206
|
+
"call": "U+0009",
|
|
1207
|
+
"gives": "A tab, as text"
|
|
1208
|
+
},
|
|
1209
|
+
"quote": {
|
|
1210
|
+
"call": "U+0022",
|
|
1211
|
+
"gives": "A double quote, as text"
|
|
1212
|
+
},
|
|
1213
|
+
"offerAvailable": {
|
|
1214
|
+
"call": "offerAvailable(textName)",
|
|
1215
|
+
"gives": "Whether the current recovery's retained failure chain has an eligible offer with this Name; false outside recovery or for a malformed or unknown Name"
|
|
1216
|
+
}
|
|
1217
|
+
};
|
|
1218
|
+
//#endregion
|
|
1219
|
+
//#region src/session/observe.ts
|
|
1220
|
+
const settled = (m) => m.counted && m.live === 0 && m.queued === 0;
|
|
1221
|
+
const row = (fields) => `{${fields.map(([k, v]) => `${k}: ${v}`).join(", ")}}`;
|
|
1222
|
+
const textForm = (s) => text(s).toString();
|
|
1223
|
+
const fuelRow = (m) => {
|
|
1224
|
+
const fuel = [...m.fuel.values()].reduce((a, b) => a + b, 0);
|
|
1225
|
+
const state = !settled(m) ? "pending" : m.interrupted ? "interrupted" : "complete";
|
|
1226
|
+
return `fuel ${row([
|
|
1227
|
+
["entry", textForm(`entry${m.entry}`)],
|
|
1228
|
+
["fuel", String(fuel)],
|
|
1229
|
+
["state", textForm(state)],
|
|
1230
|
+
["interrupted", String(m.interrupted)],
|
|
1231
|
+
["runs", String(m.live)],
|
|
1232
|
+
["queued", String(m.queued)]
|
|
1233
|
+
])}`;
|
|
1234
|
+
};
|
|
1235
|
+
const selectorText = (s) => validComputedMessageName(s, s.includes(":") ? s.split(":").length - 1 : 0);
|
|
1236
|
+
var Observation = class Observation {
|
|
1237
|
+
filters = /* @__PURE__ */ new Set();
|
|
1238
|
+
traced = /* @__PURE__ */ new Map();
|
|
1239
|
+
measurements = [];
|
|
1240
|
+
lines = [];
|
|
1241
|
+
clone() {
|
|
1242
|
+
const c = new Observation();
|
|
1243
|
+
c.filters = new Set(this.filters);
|
|
1244
|
+
c.traced = new Map(this.traced);
|
|
1245
|
+
c.measurements = this.measurements.map((m) => ({
|
|
1246
|
+
...m,
|
|
1247
|
+
fuel: new Map(m.fuel)
|
|
1248
|
+
}));
|
|
1249
|
+
return c;
|
|
1250
|
+
}
|
|
1251
|
+
/** `:trace` and `:untrace`. */
|
|
1252
|
+
trace(name, rest) {
|
|
1253
|
+
const selector = rest.trim();
|
|
1254
|
+
if (selector && !selectorText(selector)) return null;
|
|
1255
|
+
if (name === "untrace") {
|
|
1256
|
+
if (selector) this.filters.delete(selector);
|
|
1257
|
+
else this.filters.clear();
|
|
1258
|
+
} else if (selector) this.filters.add(selector);
|
|
1259
|
+
else return [...this.filters].sort((a, b) => {
|
|
1260
|
+
const x = [...a].map((c) => c.codePointAt(0));
|
|
1261
|
+
const y = [...b].map((c) => c.codePointAt(0));
|
|
1262
|
+
for (let i = 0; i < Math.min(x.length, y.length); i++) if (x[i] !== y[i]) return x[i] - y[i];
|
|
1263
|
+
return x.length - y.length;
|
|
1264
|
+
}).map((s) => `trace ${textForm(s)}`);
|
|
1265
|
+
return [];
|
|
1266
|
+
}
|
|
1267
|
+
/** Starts measuring the Entry whose Request made this root Delivery. */
|
|
1268
|
+
measure(entry, root) {
|
|
1269
|
+
this.measurements.push({
|
|
1270
|
+
announced: false,
|
|
1271
|
+
closed: false,
|
|
1272
|
+
counted: false,
|
|
1273
|
+
entry,
|
|
1274
|
+
fuel: /* @__PURE__ */ new Map(),
|
|
1275
|
+
interrupted: false,
|
|
1276
|
+
live: 0,
|
|
1277
|
+
queued: 0,
|
|
1278
|
+
root
|
|
1279
|
+
});
|
|
1280
|
+
}
|
|
1281
|
+
/** Bare `:fuel`: every measurement's current row, in Entry order. */
|
|
1282
|
+
rows() {
|
|
1283
|
+
return this.measurements.map(fuelRow);
|
|
1284
|
+
}
|
|
1285
|
+
/** The Entry names of measurements still pending, which a restore abandons. */
|
|
1286
|
+
pending() {
|
|
1287
|
+
return this.measurements.filter((m) => !settled(m)).map((m) => `entry${m.entry}`);
|
|
1288
|
+
}
|
|
1289
|
+
end(script, run, fields) {
|
|
1290
|
+
const selector = this.traced.get(run);
|
|
1291
|
+
if (selector === void 0) return;
|
|
1292
|
+
this.traced.delete(run);
|
|
1293
|
+
this.lines.push(`trace end ${row([
|
|
1294
|
+
["script", textForm(script)],
|
|
1295
|
+
["run", textForm(run)],
|
|
1296
|
+
["selector", textForm(selector)],
|
|
1297
|
+
...fields
|
|
1298
|
+
])}`);
|
|
1299
|
+
}
|
|
1300
|
+
measured(root) {
|
|
1301
|
+
return this.measurements.find((m) => m.root === root);
|
|
1302
|
+
}
|
|
1303
|
+
/**
|
|
1304
|
+
* Follows one Host call's reports, in order. `errors` holds each errored
|
|
1305
|
+
* Run's projected error, as its `! error` row shows it.
|
|
1306
|
+
*/
|
|
1307
|
+
observe(reports, errors) {
|
|
1308
|
+
for (const r of reports) if (r.kind === "run started") {
|
|
1309
|
+
if (r.selector !== void 0 && this.filters.has(r.selector)) {
|
|
1310
|
+
this.traced.set(r.run, r.selector);
|
|
1311
|
+
this.lines.push(`trace start ${row([
|
|
1312
|
+
["script", textForm(r.script)],
|
|
1313
|
+
["run", textForm(r.run)],
|
|
1314
|
+
["selector", textForm(r.selector)],
|
|
1315
|
+
["args", traceValue(listValues(r.args))]
|
|
1316
|
+
])}`);
|
|
1317
|
+
}
|
|
1318
|
+
} else if (r.kind === "run end") {
|
|
1319
|
+
const fields = [["outcome", textForm(r.outcome)]];
|
|
1320
|
+
if (r.outcome === "completed") fields.push(["result", traceValue(r.result ?? nothing)]);
|
|
1321
|
+
else if (r.outcome === "errored") fields.push(["error", errors?.get(r.run ?? "") ?? ""]);
|
|
1322
|
+
else if (r.outcome === "limit fault") fields.push(["limit", textForm(r.limit ?? "")]);
|
|
1323
|
+
else if (r.outcome === "effect failed" && r.effect) {
|
|
1324
|
+
const e = r.effect;
|
|
1325
|
+
fields.push(["effect", row([
|
|
1326
|
+
["script", textForm(e.script)],
|
|
1327
|
+
["run", textForm(e.run)],
|
|
1328
|
+
["grant", textForm(e.grant)],
|
|
1329
|
+
["segment", textForm(e.segment)],
|
|
1330
|
+
["phase", textForm(e.phase)],
|
|
1331
|
+
["status", textForm(e.status)],
|
|
1332
|
+
...e.scope ? [["scope", textForm(e.scope)]] : []
|
|
1333
|
+
])]);
|
|
1334
|
+
}
|
|
1335
|
+
if (r.run) this.end(r.script, r.run, fields);
|
|
1336
|
+
} else if (r.kind === "run discarded") this.end(r.script, r.run, [["outcome", textForm("discarded")], ["reason", textForm(r.reason)]]);
|
|
1337
|
+
else if (r.kind === "run accounting") {
|
|
1338
|
+
const m = this.measured(r.rootDelivery);
|
|
1339
|
+
if (m) {
|
|
1340
|
+
m.fuel.set(r.run, r.fuel);
|
|
1341
|
+
m.interrupted ||= r.state === "discarded";
|
|
1342
|
+
}
|
|
1343
|
+
} else if (r.kind === "causal work") {
|
|
1344
|
+
const m = this.measured(r.rootDelivery);
|
|
1345
|
+
if (m) {
|
|
1346
|
+
m.counted = true;
|
|
1347
|
+
m.live = r.liveRuns;
|
|
1348
|
+
m.queued = r.queuedMessages;
|
|
1349
|
+
m.interrupted ||= r.discardedMessages > 0;
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
/**
|
|
1354
|
+
* This Host call's trace rows, then its Fuel milestones: a new
|
|
1355
|
+
* measurement's first row, and the final row of each one that has settled.
|
|
1356
|
+
*/
|
|
1357
|
+
observed() {
|
|
1358
|
+
const out = this.lines;
|
|
1359
|
+
this.lines = [];
|
|
1360
|
+
for (const m of this.measurements) {
|
|
1361
|
+
if (m.closed || m.announced && !settled(m)) continue;
|
|
1362
|
+
m.announced = true;
|
|
1363
|
+
m.closed = settled(m);
|
|
1364
|
+
out.push(fuelRow(m));
|
|
1365
|
+
}
|
|
1366
|
+
return out;
|
|
1367
|
+
}
|
|
1368
|
+
};
|
|
1369
|
+
//#endregion
|
|
1370
|
+
//#region src/session/inspect.ts
|
|
1371
|
+
const declarationValue = (data) => {
|
|
1372
|
+
if (data === null || data === void 0) return nothing;
|
|
1373
|
+
if (typeof data === "string") return text(data);
|
|
1374
|
+
if (typeof data === "boolean") return bool(data);
|
|
1375
|
+
if (typeof data === "number") return integerValue(BigInt(data));
|
|
1376
|
+
if (Array.isArray(data)) return listValues(data.map(declarationValue));
|
|
1377
|
+
return map(Object.entries(data).map(([k, v]) => [k, declarationValue(v)]));
|
|
1378
|
+
};
|
|
1379
|
+
const propertyNames = (value) => [...stateOf(value)?.handle.kind.props.keys() ?? []].sort(compareText);
|
|
1380
|
+
const cost = (c) => declarationValue({
|
|
1381
|
+
fuel: c?.fuel ?? 0,
|
|
1382
|
+
alloc: c?.alloc ?? 0
|
|
1383
|
+
});
|
|
1384
|
+
const valueRows = (value) => {
|
|
1385
|
+
const out = [`value ${map([["kind", text(value.kind)], ["value", value]])}`];
|
|
1386
|
+
const size = value.kind === "text" ? characterBoundaries(value.asText()).length - 1 : value.kind === "bytes" ? value.asBytes().length : value.kind === "list" ? value.length : value.kind === "map" ? value.entries().length : null;
|
|
1387
|
+
if (size !== null) out.push(`size ${size}`);
|
|
1388
|
+
if (value.kind === "map") for (const [key, field] of value.entries().sort(([a], [b]) => compareText(a, b))) out.push(`field ${text(key)} = ${field}`);
|
|
1389
|
+
if (value.kind === "function") {
|
|
1390
|
+
const fn = value.asFunction();
|
|
1391
|
+
const head = functionHead(fn.code);
|
|
1392
|
+
out.push(`function ${map([
|
|
1393
|
+
["name", head?.name == null ? nothing : text(head.name)],
|
|
1394
|
+
["arity", head ? range(integerValue(BigInt(head.min)), integerValue(BigInt(head.max))) : nothing],
|
|
1395
|
+
["home", text(fn.home)]
|
|
1396
|
+
])}`, `doc ${text(functionDoc(value) ?? "")}`);
|
|
1397
|
+
}
|
|
1398
|
+
if (value.kind === "object") {
|
|
1399
|
+
const state = stateOf(value);
|
|
1400
|
+
const object = state.handle;
|
|
1401
|
+
out.push(`object ${map([
|
|
1402
|
+
["kind", text(object.kind.name)],
|
|
1403
|
+
["id", text(object.id)],
|
|
1404
|
+
["disposed", bool(state.disposed)]
|
|
1405
|
+
])}`);
|
|
1406
|
+
for (const name of propertyNames(value)) {
|
|
1407
|
+
const p = object.kind.props.get(name);
|
|
1408
|
+
out.push(`property ${map([
|
|
1409
|
+
["name", text(name)],
|
|
1410
|
+
["shape", declarationValue(p.shape ? shapeData(p.shape) : "any")],
|
|
1411
|
+
["readOnly", bool(!p.set)],
|
|
1412
|
+
["getCost", cost(p.getCost)],
|
|
1413
|
+
["setCost", p.set ? cost(p.setCost) : nothing]
|
|
1414
|
+
])}`);
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
return out;
|
|
1418
|
+
};
|
|
1419
|
+
//#endregion
|
|
1420
|
+
//#region src/session/describe.ts
|
|
1421
|
+
const ORIGINS = [
|
|
1422
|
+
"session",
|
|
1423
|
+
"builtin",
|
|
1424
|
+
"library"
|
|
1425
|
+
];
|
|
1426
|
+
const show = (s) => text(s).toString();
|
|
1427
|
+
const targetText = (t) => t.origin === "library" ? `{library: ${show(t.library)}, name: ${show(t.name)}, origin: "library"}` : `{name: ${show(t.name)}, origin: ${show(t.origin)}}`;
|
|
1428
|
+
const byCodePoint = (a, b) => {
|
|
1429
|
+
const x = Array.from(a, (c) => c.codePointAt(0));
|
|
1430
|
+
const y = Array.from(b, (c) => c.codePointAt(0));
|
|
1431
|
+
for (let i = 0; i < Math.min(x.length, y.length); i++) if (x[i] !== y[i]) return x[i] - y[i];
|
|
1432
|
+
return x.length - y.length;
|
|
1433
|
+
};
|
|
1434
|
+
const tokens = (node) => node.children.flatMap((c) => c.kind === "node" ? tokens(c) : [c]);
|
|
1435
|
+
const signature = (source, node, kind) => {
|
|
1436
|
+
const all = tokens(node);
|
|
1437
|
+
let last = all.findIndex((t) => t.t === "nl") - 1;
|
|
1438
|
+
if (kind === "constant" || kind === "variable") last = all.findIndex((t) => t.v === "constant" || t.v === "variable") + 1;
|
|
1439
|
+
return source.slice(all[0].pos, all[last].end);
|
|
1440
|
+
};
|
|
1441
|
+
const declaredIn = (source, origin, includePrivate = false) => {
|
|
1442
|
+
const out = /* @__PURE__ */ new Map();
|
|
1443
|
+
const tree = parseSource(source).tree;
|
|
1444
|
+
const checked = checkSource(source).tree;
|
|
1445
|
+
if (!tree || !checked) return out;
|
|
1446
|
+
const docs = declarationDocs(tree);
|
|
1447
|
+
const nodes = tree.children.filter((c) => c.kind === "node" && c.rule === "Declaration");
|
|
1448
|
+
viewSource(checked.root).forEach((decl, at) => {
|
|
1449
|
+
if (decl.k === "use" || "private" in decl && decl.private && !includePrivate) return;
|
|
1450
|
+
const name = decl.k === "constant" || decl.k === "variable" ? decl.name.text : decl.name;
|
|
1451
|
+
const named = out.get(name) ?? [];
|
|
1452
|
+
out.set(name, named);
|
|
1453
|
+
const node = nodes[at];
|
|
1454
|
+
const d = {
|
|
1455
|
+
origin,
|
|
1456
|
+
declaration: decl.k,
|
|
1457
|
+
clause: decl.k === "handler" ? named.length + 1 : 0,
|
|
1458
|
+
doc: docs.get(node) ?? "",
|
|
1459
|
+
signature: signature(source, node, decl.k)
|
|
1460
|
+
};
|
|
1461
|
+
if (decl.k === "function") d.arity = [decl.params.filter((p) => p.default === null).length, decl.params.length];
|
|
1462
|
+
named.push(d);
|
|
1463
|
+
});
|
|
1464
|
+
return out;
|
|
1465
|
+
};
|
|
1466
|
+
const librarySource$1 = (names, library) => names.libraries.get(library) ?? stdlibSources[library];
|
|
1467
|
+
/** A public Library export, from the Library's source, imported or not. */
|
|
1468
|
+
const libraryDeclared = (names, library, name) => {
|
|
1469
|
+
const source = librarySource$1(names, library);
|
|
1470
|
+
return source === void 0 ? [] : declaredIn(source, library).get(name) ?? [];
|
|
1471
|
+
};
|
|
1472
|
+
/**
|
|
1473
|
+
* A current session name or Selector, as binding precedence resolves it. An
|
|
1474
|
+
* Import resolves to its defining Library declaration.
|
|
1475
|
+
*/
|
|
1476
|
+
const sessionDeclared = (names, name) => {
|
|
1477
|
+
const out = [];
|
|
1478
|
+
for (const d of names.declarations) {
|
|
1479
|
+
if (d.kind === "use") {
|
|
1480
|
+
const imported = d.uses.find((u) => u.local === name);
|
|
1481
|
+
if (imported) return libraryDeclared(names, d.library, imported.name);
|
|
1482
|
+
continue;
|
|
1483
|
+
}
|
|
1484
|
+
if (d.names[0] !== name) continue;
|
|
1485
|
+
const [m] = [...declaredIn(d.source, "session", true).values()][0] ?? [];
|
|
1486
|
+
if (!m) continue;
|
|
1487
|
+
if (d.kind === "variable") m.variable = name;
|
|
1488
|
+
if (d.kind !== "handler") return [m];
|
|
1489
|
+
m.clause = out.length + 1;
|
|
1490
|
+
out.push(m);
|
|
1491
|
+
}
|
|
1492
|
+
return out;
|
|
1493
|
+
};
|
|
1494
|
+
const builtinDeclared = (name) => {
|
|
1495
|
+
const b = Object.hasOwn(builtinDocs, name) ? builtinDocs[name] : void 0;
|
|
1496
|
+
return b ? [{
|
|
1497
|
+
origin: "builtin",
|
|
1498
|
+
declaration: "builtin",
|
|
1499
|
+
clause: 0,
|
|
1500
|
+
doc: b.gives,
|
|
1501
|
+
signature: b.call
|
|
1502
|
+
}] : [];
|
|
1503
|
+
};
|
|
1504
|
+
const describeTarget = (names, rest) => {
|
|
1505
|
+
if (!rest.startsWith("{")) {
|
|
1506
|
+
if (!selectorText(rest)) names.refuse("bad arguments");
|
|
1507
|
+
return {
|
|
1508
|
+
plain: true,
|
|
1509
|
+
target: {
|
|
1510
|
+
name: rest,
|
|
1511
|
+
origin: "session"
|
|
1512
|
+
}
|
|
1513
|
+
};
|
|
1514
|
+
}
|
|
1515
|
+
let v;
|
|
1516
|
+
try {
|
|
1517
|
+
v = readDisplay(rest);
|
|
1518
|
+
} catch {
|
|
1519
|
+
names.refuse("bad arguments");
|
|
1520
|
+
}
|
|
1521
|
+
const fields = new Map(v.entries());
|
|
1522
|
+
const field = (key) => fields.get(key)?.asText();
|
|
1523
|
+
const origin = field("origin");
|
|
1524
|
+
const keys = origin === "library" ? 3 : 2;
|
|
1525
|
+
if (v.kind !== "map" || [...fields.values()].some((f) => f.kind !== "text") || !ORIGINS.includes(origin ?? "") || field("name") === void 0 || origin === "library" && field("library") === void 0 || fields.size !== keys) names.refuse("bad arguments");
|
|
1526
|
+
const target = {
|
|
1527
|
+
name: field("name"),
|
|
1528
|
+
origin
|
|
1529
|
+
};
|
|
1530
|
+
if (origin === "library") target.library = field("library");
|
|
1531
|
+
return {
|
|
1532
|
+
plain: false,
|
|
1533
|
+
target
|
|
1534
|
+
};
|
|
1535
|
+
};
|
|
1536
|
+
/** `:describe <target>`'s rows. */
|
|
1537
|
+
const describe$1 = (names, rest) => {
|
|
1538
|
+
const { plain, target } = describeTarget(names, rest);
|
|
1539
|
+
let found = [];
|
|
1540
|
+
if (target.origin === "session") {
|
|
1541
|
+
found = sessionDeclared(names, target.name);
|
|
1542
|
+
if (!found.length && plain) {
|
|
1543
|
+
target.origin = "builtin";
|
|
1544
|
+
found = builtinDeclared(target.name);
|
|
1545
|
+
}
|
|
1546
|
+
} else if (target.origin === "builtin") found = builtinDeclared(target.name);
|
|
1547
|
+
else found = libraryDeclared(names, target.library, target.name);
|
|
1548
|
+
if (!found.length) names.refuse("no such name");
|
|
1549
|
+
const out = [];
|
|
1550
|
+
for (const d of found) {
|
|
1551
|
+
const clause = d.declaration === "handler" ? `, clause: ${d.clause}` : "";
|
|
1552
|
+
out.push(`describe {target: ${targetText(target)}, origin: ${show(d.origin)}, declaration: ${show(d.declaration)}, signature: ${show(d.signature)}${clause}}`, `doc ${show(d.doc)}`);
|
|
1553
|
+
if (d.arity) out.push(`arity ${d.arity[0]}..${d.arity[1]}`);
|
|
1554
|
+
if (d.variable !== void 0) {
|
|
1555
|
+
const value = names.variable(d.variable);
|
|
1556
|
+
if (value) out.push(...valueRows(value));
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
return out;
|
|
1560
|
+
};
|
|
1561
|
+
/** `:apropos [query]`'s rows. */
|
|
1562
|
+
const apropos = (names, rest) => {
|
|
1563
|
+
let query = rest;
|
|
1564
|
+
if (rest.startsWith("\"")) {
|
|
1565
|
+
let v;
|
|
1566
|
+
try {
|
|
1567
|
+
v = readDisplay(rest);
|
|
1568
|
+
} catch {
|
|
1569
|
+
names.refuse("bad arguments");
|
|
1570
|
+
}
|
|
1571
|
+
if (v.kind !== "text") names.refuse("bad arguments");
|
|
1572
|
+
query = v.asText();
|
|
1573
|
+
}
|
|
1574
|
+
query = lower(query);
|
|
1575
|
+
const all = [];
|
|
1576
|
+
const add = (f) => {
|
|
1577
|
+
if (f.docs.length && lower(f.target.name).includes(query)) all.push(f);
|
|
1578
|
+
};
|
|
1579
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1580
|
+
for (const d of names.declarations) for (const name of d.names) {
|
|
1581
|
+
if (seen.has(name)) continue;
|
|
1582
|
+
seen.add(name);
|
|
1583
|
+
const docs = sessionDeclared(names, name);
|
|
1584
|
+
if (docs.length) add({
|
|
1585
|
+
target: {
|
|
1586
|
+
name,
|
|
1587
|
+
origin: "session"
|
|
1588
|
+
},
|
|
1589
|
+
origin: docs[0].origin,
|
|
1590
|
+
available: true,
|
|
1591
|
+
import: null,
|
|
1592
|
+
docs
|
|
1593
|
+
});
|
|
1594
|
+
}
|
|
1595
|
+
for (const b of builtins) add({
|
|
1596
|
+
target: {
|
|
1597
|
+
name: b.name,
|
|
1598
|
+
origin: "builtin"
|
|
1599
|
+
},
|
|
1600
|
+
origin: "builtin",
|
|
1601
|
+
available: !names.has(b.name),
|
|
1602
|
+
import: null,
|
|
1603
|
+
docs: builtinDeclared(b.name)
|
|
1604
|
+
});
|
|
1605
|
+
const libraries = [...Object.keys(stdlibSources).sort(byCodePoint), ...names.libraries.keys()];
|
|
1606
|
+
for (const library of libraries) {
|
|
1607
|
+
const source = librarySource$1(names, library);
|
|
1608
|
+
for (const [name, docs] of declaredIn(source, library)) {
|
|
1609
|
+
if (docs[0].declaration === "variable") continue;
|
|
1610
|
+
const available = names.declarations.some((d) => d.kind === "use" && d.library === library && d.uses.some((u) => u.name === name && u.local === name));
|
|
1611
|
+
add({
|
|
1612
|
+
target: {
|
|
1613
|
+
library,
|
|
1614
|
+
name,
|
|
1615
|
+
origin: "library"
|
|
1616
|
+
},
|
|
1617
|
+
origin: library,
|
|
1618
|
+
available,
|
|
1619
|
+
import: available ? null : `use ${name} from ${library}`,
|
|
1620
|
+
docs
|
|
1621
|
+
});
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
all.sort((a, b) => byCodePoint(a.target.name, b.target.name) || ORIGINS.indexOf(a.target.origin) - ORIGINS.indexOf(b.target.origin) || byCodePoint(a.target.library ?? "", b.target.library ?? ""));
|
|
1625
|
+
const out = [];
|
|
1626
|
+
for (const f of all) {
|
|
1627
|
+
out.push(`name {target: ${targetText(f.target)}, origin: ${show(f.origin)}, available: ${f.available}, import: ${f.import === null ? "nothing" : show(f.import)}}`);
|
|
1628
|
+
for (const d of f.docs) out.push(d.declaration === "handler" ? `doc ${d.clause} ${show(d.doc)}` : `doc ${show(d.doc)}`);
|
|
1629
|
+
}
|
|
1630
|
+
return out;
|
|
1631
|
+
};
|
|
1632
|
+
//#endregion
|
|
1633
|
+
//#region src/generated/session.ts
|
|
1634
|
+
const inspectReader = "on entry0 entry0Object to entry0Names\n repeat for each entry0Name in entry0Names\n try\n put {name: entry0Name, value: the (entry0Name) of entry0Object} into entry0Row\n catch entry0Error\n put {} into entry0Clean\n repeat for each entry0Key in the keys of entry0Error\n if entry0Key is not in [\"message\", \"at\"] then\n put the (entry0Key) of entry0Error into the (entry0Key) of entry0Clean\n end if\n end repeat\n put {name: entry0Name, error: entry0Clean} into entry0Row\n end try\n say \"read \" & entry0Row\n end repeat\nend entry0\n";
|
|
1635
|
+
//#endregion
|
|
1636
|
+
//#region src/session/stubs.ts
|
|
1637
|
+
/** An error map as a Host function fails with it, its code and message apart. */
|
|
1638
|
+
const hostFailure = (error) => new ScriptError(error.get("code").asText() ?? "", error.get("message").asText() ?? "", map(error.entries().filter(([k]) => k !== "code" && k !== "message")));
|
|
1639
|
+
/** The `stub` line a runner writes into the Trace for a Stub it queues. */
|
|
1640
|
+
const stubLine = (operation, stub) => recordLine("stub", [operation], [
|
|
1641
|
+
["value", stub.value ? traceValue(stub.value) : null],
|
|
1642
|
+
["error", stub.error ? traceValue(stub.error) : null],
|
|
1643
|
+
["charge", stub.charge ? String(stub.charge) : null]
|
|
1644
|
+
], true);
|
|
1645
|
+
/** The Stubs queued for each Operation, named `<capability>.<operation>`. */
|
|
1646
|
+
var Stubs = class Stubs {
|
|
1647
|
+
queues = /* @__PURE__ */ new Map();
|
|
1648
|
+
effects = /* @__PURE__ */ new Map();
|
|
1649
|
+
clone() {
|
|
1650
|
+
const copy = new Stubs();
|
|
1651
|
+
for (const [operation, queue] of this.queues) copy.queues.set(operation, [...queue]);
|
|
1652
|
+
for (const [key, queue] of this.effects) copy.effects.set(key, [...queue]);
|
|
1653
|
+
return copy;
|
|
1654
|
+
}
|
|
1655
|
+
add(operation, stub) {
|
|
1656
|
+
this.queues.set(operation, [...this.queues.get(operation) ?? [], stub]);
|
|
1657
|
+
}
|
|
1658
|
+
addEffect(grant, phase, result) {
|
|
1659
|
+
const key = `${grant}.${phase}`;
|
|
1660
|
+
this.effects.set(key, [...this.effects.get(key) ?? [], result]);
|
|
1661
|
+
}
|
|
1662
|
+
/** Whether a Stub is queued for the Operation. */
|
|
1663
|
+
queued(operation) {
|
|
1664
|
+
return (this.queues.get(operation)?.length ?? 0) > 0;
|
|
1665
|
+
}
|
|
1666
|
+
takeEffect(grant, phase) {
|
|
1667
|
+
return this.effects.get(`${grant}.${phase}`)?.shift();
|
|
1668
|
+
}
|
|
1669
|
+
/**
|
|
1670
|
+
* An immediate or fire-and-forget call: the next Stub's value, or its
|
|
1671
|
+
* failure, after its charge. With none, a `needed` call fails, and the
|
|
1672
|
+
* Script sees `host error`.
|
|
1673
|
+
*/
|
|
1674
|
+
take(operation, call, needed, recorded) {
|
|
1675
|
+
const stub = this.queues.get(operation)?.shift() ?? recorded;
|
|
1676
|
+
if (!stub) {
|
|
1677
|
+
if (needed) throw new Error(`No Stub for ${operation}`);
|
|
1678
|
+
return nothing;
|
|
1679
|
+
}
|
|
1680
|
+
if (stub.charge) call.charge(stub.charge);
|
|
1681
|
+
if (stub.malformed) return null;
|
|
1682
|
+
if (stub.error) {
|
|
1683
|
+
if (!stub.error.entries().length) throw new Error(`The Stub for ${operation} fails`);
|
|
1684
|
+
throw hostFailure(stub.error);
|
|
1685
|
+
}
|
|
1686
|
+
return stub.value ?? nothing;
|
|
1687
|
+
}
|
|
1688
|
+
/** A suspending call takes a Stub for its charge, and for an error that fails it at once. */
|
|
1689
|
+
start(operation, call, recorded) {
|
|
1690
|
+
const queued = this.queues.get(operation)?.shift();
|
|
1691
|
+
const stub = queued ?? recorded;
|
|
1692
|
+
if (stub?.charge) call.charge(stub.charge);
|
|
1693
|
+
if (stub?.error) {
|
|
1694
|
+
if (!stub.error.entries().length) throw new Error(queued ? `The Stub for ${operation} fails` : `The recorded call of ${operation} fails`);
|
|
1695
|
+
throw hostFailure(stub.error);
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
};
|
|
1699
|
+
//#endregion
|
|
1700
|
+
//#region src/session/host.ts
|
|
1701
|
+
const NAME = "session";
|
|
1702
|
+
/** How many arguments a mock Operation takes, each an Optional `any`. */
|
|
1703
|
+
const MOCK_ARGUMENTS = 8;
|
|
1704
|
+
const MODES = /* @__PURE__ */ new Set([
|
|
1705
|
+
"immediate",
|
|
1706
|
+
"suspending",
|
|
1707
|
+
"fire-and-forget"
|
|
1708
|
+
]);
|
|
1709
|
+
const BUILT_IN = /* @__PURE__ */ new Set([
|
|
1710
|
+
"clock",
|
|
1711
|
+
"calendar",
|
|
1712
|
+
"locale",
|
|
1713
|
+
"store",
|
|
1714
|
+
"user"
|
|
1715
|
+
]);
|
|
1716
|
+
const DEFAULT_BINDING = {
|
|
1717
|
+
calendar: "UTC",
|
|
1718
|
+
locale: "und",
|
|
1719
|
+
store: "default"
|
|
1720
|
+
};
|
|
1721
|
+
const STORE_COSTS = {
|
|
1722
|
+
watch: { fuel: 4 },
|
|
1723
|
+
unwatch: { fuel: 2 },
|
|
1724
|
+
get: { fuel: 2 },
|
|
1725
|
+
keys: { fuel: 2 },
|
|
1726
|
+
set: { fuel: 4 },
|
|
1727
|
+
delete: { fuel: 4 },
|
|
1728
|
+
increment: { fuel: 4 },
|
|
1729
|
+
swap: { fuel: 4 }
|
|
1730
|
+
};
|
|
1731
|
+
const OPERATIONS = {
|
|
1732
|
+
calendar: [
|
|
1733
|
+
"today",
|
|
1734
|
+
"now",
|
|
1735
|
+
"toCivil",
|
|
1736
|
+
"toInstant",
|
|
1737
|
+
"offset",
|
|
1738
|
+
"zone"
|
|
1739
|
+
],
|
|
1740
|
+
user: [
|
|
1741
|
+
"confirm",
|
|
1742
|
+
"choose",
|
|
1743
|
+
"enter",
|
|
1744
|
+
"notify"
|
|
1745
|
+
],
|
|
1746
|
+
locale: [
|
|
1747
|
+
"compare",
|
|
1748
|
+
"rank",
|
|
1749
|
+
"upper",
|
|
1750
|
+
"lower",
|
|
1751
|
+
"numberSymbols",
|
|
1752
|
+
"monthNames",
|
|
1753
|
+
"dayNames",
|
|
1754
|
+
"tag"
|
|
1755
|
+
]
|
|
1756
|
+
};
|
|
1757
|
+
const promptOf = (operation, args) => {
|
|
1758
|
+
const option = (key) => {
|
|
1759
|
+
const v = args[1]?.kind === "map" ? args[1].get(key) : void 0;
|
|
1760
|
+
return v?.kind === "nothing" ? void 0 : v;
|
|
1761
|
+
};
|
|
1762
|
+
const message = args[0].asText() ?? "";
|
|
1763
|
+
return operation === "confirm" ? {
|
|
1764
|
+
k: "confirm",
|
|
1765
|
+
message
|
|
1766
|
+
} : operation === "enter" ? {
|
|
1767
|
+
k: "enter",
|
|
1768
|
+
message,
|
|
1769
|
+
fallback: option("default")?.asText() ?? ""
|
|
1770
|
+
} : {
|
|
1771
|
+
k: "choose",
|
|
1772
|
+
items: Array.from({ length: args[0].length }, (_, i) => args[0].index(i + 1).asText()),
|
|
1773
|
+
prompt: option("prompt")?.asText() ?? "",
|
|
1774
|
+
multiple: option("multiple")?.asBool() === true
|
|
1775
|
+
};
|
|
1776
|
+
};
|
|
1777
|
+
const free = (operations) => Object.fromEntries(operations.map((op) => [op, { fuel: 0 }]));
|
|
1778
|
+
const LIBRARY_VERSION = "1";
|
|
1779
|
+
const terminalEffects = (reports) => reports.some((r) => r.kind === "stop" && r.reason === "effect state unknown");
|
|
1780
|
+
const effectFailureText = (r) => `! effect failure grant=${r.grant} segment=${r.segment} phase=${r.phase} status=${r.status}${r.scope ? ` scope=${r.scope}` : ""}`;
|
|
1781
|
+
const OVERRIDABLE = [
|
|
1782
|
+
"fuelPerRun",
|
|
1783
|
+
"allocPerRun",
|
|
1784
|
+
"maxWaitMs",
|
|
1785
|
+
"maxJoin"
|
|
1786
|
+
];
|
|
1787
|
+
const NAME_TEXT = /^[\p{L}_][\p{L}\p{N}_]*$/u;
|
|
1788
|
+
const librarySource = (file) => file.endsWith("\n") ? file : `${file}\n`;
|
|
1789
|
+
var RefusedError = class extends Error {};
|
|
1790
|
+
const refuse = (reason) => {
|
|
1791
|
+
throw new RefusedError(reason);
|
|
1792
|
+
};
|
|
1793
|
+
const lineCount = (source) => source.split("\n").length;
|
|
1794
|
+
const lines = (t) => t.split(/\r\n|\n|\r/);
|
|
1795
|
+
const nodes = (node) => node.children.filter((c) => c.kind === "node");
|
|
1796
|
+
/** A Session Host for one session (chapter 12). */
|
|
1797
|
+
var SessionHost = class {
|
|
1798
|
+
env;
|
|
1799
|
+
group = null;
|
|
1800
|
+
controls = null;
|
|
1801
|
+
objectSession = null;
|
|
1802
|
+
objectBindings = {};
|
|
1803
|
+
script = null;
|
|
1804
|
+
declarations = [];
|
|
1805
|
+
implicit = /* @__PURE__ */ new Set();
|
|
1806
|
+
lastEntry = 0;
|
|
1807
|
+
lastClock = null;
|
|
1808
|
+
placements = /* @__PURE__ */ new Map();
|
|
1809
|
+
expressions = /* @__PURE__ */ new Set();
|
|
1810
|
+
inspections = /* @__PURE__ */ new Set();
|
|
1811
|
+
inspecting = false;
|
|
1812
|
+
reader = null;
|
|
1813
|
+
foreground = null;
|
|
1814
|
+
lastSeg = /* @__PURE__ */ new Map();
|
|
1815
|
+
writes = /* @__PURE__ */ new Map();
|
|
1816
|
+
reads = /* @__PURE__ */ new Map();
|
|
1817
|
+
prompts = /* @__PURE__ */ new Map();
|
|
1818
|
+
notes = /* @__PURE__ */ new Map();
|
|
1819
|
+
events = [];
|
|
1820
|
+
state = { k: "prompt" };
|
|
1821
|
+
units = 1;
|
|
1822
|
+
deadline;
|
|
1823
|
+
setup0 = immutableSetup({
|
|
1824
|
+
scripts: [{
|
|
1825
|
+
name: NAME,
|
|
1826
|
+
source: "(empty)",
|
|
1827
|
+
text: "",
|
|
1828
|
+
grants: { console: { ops: "all" } }
|
|
1829
|
+
}],
|
|
1830
|
+
operations: [],
|
|
1831
|
+
libraries: [],
|
|
1832
|
+
standard: [{
|
|
1833
|
+
capability: "console",
|
|
1834
|
+
costs: {
|
|
1835
|
+
write: { fuel: 0 },
|
|
1836
|
+
read: { fuel: 0 }
|
|
1837
|
+
}
|
|
1838
|
+
}]
|
|
1839
|
+
});
|
|
1840
|
+
stubs = new Stubs();
|
|
1841
|
+
mockCalls = /* @__PURE__ */ new Map();
|
|
1842
|
+
pending = /* @__PURE__ */ new Map();
|
|
1843
|
+
virtual = null;
|
|
1844
|
+
limits = {};
|
|
1845
|
+
latest = null;
|
|
1846
|
+
grantsByName = {};
|
|
1847
|
+
declarations0 = {};
|
|
1848
|
+
libraries = /* @__PURE__ */ new Map();
|
|
1849
|
+
saves = /* @__PURE__ */ new Map();
|
|
1850
|
+
stores;
|
|
1851
|
+
notified = false;
|
|
1852
|
+
admitted = () => {
|
|
1853
|
+
this.notified = true;
|
|
1854
|
+
};
|
|
1855
|
+
observation = new Observation();
|
|
1856
|
+
measuring = false;
|
|
1857
|
+
extensions;
|
|
1858
|
+
constructor(env) {
|
|
1859
|
+
this.env = env;
|
|
1860
|
+
this.stores = memoryStores(sessionQuotas, this.admitted);
|
|
1861
|
+
const definitions = env.capabilities?.() ?? [];
|
|
1862
|
+
this.extensions = new Map(definitions.map((def) => [def.name, def]));
|
|
1863
|
+
if (this.extensions.size !== definitions.length || definitions.some((def) => def.name === "console" || BUILT_IN.has(def.name) || def.lifecycle || def.coordinator || [...def.operations.values()].some((op) => op.mode !== "immediate" || op.scope || op.segmentBound))) throw new Error("Session extensions must be distinct deterministic immediate capabilities");
|
|
1864
|
+
}
|
|
1865
|
+
/** What the Host waits for before returning the prompt. */
|
|
1866
|
+
get waiting() {
|
|
1867
|
+
return this.state;
|
|
1868
|
+
}
|
|
1869
|
+
/** The session source: its declarations, in the order entered. */
|
|
1870
|
+
get source() {
|
|
1871
|
+
return this.sessionSource(this.declarations);
|
|
1872
|
+
}
|
|
1873
|
+
/** The latest Entry's Run, once it has started; its background lines carry `[<run>] `. */
|
|
1874
|
+
get latestRun() {
|
|
1875
|
+
return this.latest?.run;
|
|
1876
|
+
}
|
|
1877
|
+
/** Whether the session has started, so its Grants are fixed. */
|
|
1878
|
+
get started() {
|
|
1879
|
+
return this.group !== null;
|
|
1880
|
+
}
|
|
1881
|
+
/** Whether the Clock is virtual, so only `:clock` commands move it. */
|
|
1882
|
+
get virtualClock() {
|
|
1883
|
+
return this.virtual !== null;
|
|
1884
|
+
}
|
|
1885
|
+
/** The next deadline a background Pump is due at, if any. */
|
|
1886
|
+
get nextDeadline() {
|
|
1887
|
+
return this.deadline;
|
|
1888
|
+
}
|
|
1889
|
+
/** The immutable declaration of the live Group, also consumed by Trace replay. */
|
|
1890
|
+
get setup() {
|
|
1891
|
+
if (!this.objectSession?.items.length) return this.setup0;
|
|
1892
|
+
return immutableSetup({
|
|
1893
|
+
...this.setup0,
|
|
1894
|
+
sessionObjects: structuredClone(this.recordedItems.slice(0, this.transcriptEnd ?? this.recordedItems.length))
|
|
1895
|
+
});
|
|
1896
|
+
}
|
|
1897
|
+
/** The Host Manifest derived from the Session Setup, without starting it. */
|
|
1898
|
+
exportManifest() {
|
|
1899
|
+
const built = buildSetupGroup(this.setup0, this.capabilities(), { name: NAME });
|
|
1900
|
+
built.load(built.group, NAME);
|
|
1901
|
+
return exportManifest({
|
|
1902
|
+
kind: "session",
|
|
1903
|
+
version: "1",
|
|
1904
|
+
grants: built.grants.get(NAME)
|
|
1905
|
+
});
|
|
1906
|
+
}
|
|
1907
|
+
/** Where each declaration of the session source is in the loaded code. */
|
|
1908
|
+
get placementsOfSource() {
|
|
1909
|
+
const out = [];
|
|
1910
|
+
let line = 1;
|
|
1911
|
+
for (const d of this.declarations) {
|
|
1912
|
+
const lines = lineCount(d.source);
|
|
1913
|
+
if (d.unit !== void 0) out.push({
|
|
1914
|
+
sourceLine: line,
|
|
1915
|
+
lines,
|
|
1916
|
+
unit: d.unit,
|
|
1917
|
+
unitLine: d.unitLine
|
|
1918
|
+
});
|
|
1919
|
+
line += lines;
|
|
1920
|
+
}
|
|
1921
|
+
return out;
|
|
1922
|
+
}
|
|
1923
|
+
/**
|
|
1924
|
+
* TS tooling only: the debug controller of the session's Group, once the
|
|
1925
|
+
* session has started. A Pump it pauses waits as `paused` until
|
|
1926
|
+
* `continueDebug`; `:restore` replaces the Group and its controller.
|
|
1927
|
+
*/
|
|
1928
|
+
debugController() {
|
|
1929
|
+
if (!this.group) return null;
|
|
1930
|
+
return this.controller ??= this.group.debug();
|
|
1931
|
+
}
|
|
1932
|
+
/**
|
|
1933
|
+
* Continues a debug-paused Pump. Returns the lines the Pump printed once it
|
|
1934
|
+
* completes, as it would have printed them without the pause.
|
|
1935
|
+
*/
|
|
1936
|
+
continueDebug(action) {
|
|
1937
|
+
const controller = this.controller;
|
|
1938
|
+
if (this.state.k !== "paused" || !controller?.isPaused) throw new Error("The session is not debug-paused");
|
|
1939
|
+
const result = controller[action]();
|
|
1940
|
+
if (controller.isPaused) return [];
|
|
1941
|
+
return this.finished([...this.pumped(result), ...this.notifications()]);
|
|
1942
|
+
}
|
|
1943
|
+
/**
|
|
1944
|
+
* TS tooling only: a `:fix` landed at a debugger pause, which a Transcript
|
|
1945
|
+
* can't replay, so it records nothing from the Host call whose Pump paused
|
|
1946
|
+
* (ADR 0072).
|
|
1947
|
+
*/
|
|
1948
|
+
get transcriptEnded() {
|
|
1949
|
+
return this.transcriptEnd !== null;
|
|
1950
|
+
}
|
|
1951
|
+
transcriptEnd = null;
|
|
1952
|
+
unrecorded = false;
|
|
1953
|
+
callStart = 0;
|
|
1954
|
+
entryHandlers = /* @__PURE__ */ new Map();
|
|
1955
|
+
rewound = false;
|
|
1956
|
+
controller = null;
|
|
1957
|
+
paused() {
|
|
1958
|
+
if (this.state.k === "paused") throw new Error("The session is debug-paused");
|
|
1959
|
+
}
|
|
1960
|
+
/**
|
|
1961
|
+
* Tooling's line prompt uses the same Entry classification as input(). A
|
|
1962
|
+
* leading doc block waits for the declaration it documents.
|
|
1963
|
+
*/
|
|
1964
|
+
incomplete(source) {
|
|
1965
|
+
const fuel = /^\s*:(?:fuel|inspect)\s+(\S.*)$/su.exec(source);
|
|
1966
|
+
if (fuel) source = fuel[1];
|
|
1967
|
+
else if (source.startsWith(":")) return false;
|
|
1968
|
+
const parsed = parseEntry(source, (name) => this.isHandler(name));
|
|
1969
|
+
return parsed.error ? parsed.incomplete : leadingDoc(parsed.tree) === "pending";
|
|
1970
|
+
}
|
|
1971
|
+
/**
|
|
1972
|
+
* The Declaration Documentation of a current name or Handler Selector, as
|
|
1973
|
+
* binding precedence resolves it: the session's own declarations and
|
|
1974
|
+
* Imports, then the Built-ins. An Import resolves to its defining Library
|
|
1975
|
+
* declaration. It executes nothing.
|
|
1976
|
+
*/
|
|
1977
|
+
documentation(name) {
|
|
1978
|
+
const found = sessionDeclared(this.names, name);
|
|
1979
|
+
return docsOf(found.length ? found : builtinDeclared(name));
|
|
1980
|
+
}
|
|
1981
|
+
/**
|
|
1982
|
+
* A public Library export's Declaration Documentation, from the Library's
|
|
1983
|
+
* source, whether or not it is imported.
|
|
1984
|
+
*/
|
|
1985
|
+
libraryDocumentation(library, name) {
|
|
1986
|
+
return docsOf(libraryDeclared(this.names, library, name));
|
|
1987
|
+
}
|
|
1988
|
+
get names() {
|
|
1989
|
+
return {
|
|
1990
|
+
declarations: this.declarations,
|
|
1991
|
+
has: (name) => this.has(name),
|
|
1992
|
+
refuse,
|
|
1993
|
+
libraries: new Map([...this.libraries].map(([name, l]) => [name, l.library.source])),
|
|
1994
|
+
variable: (name) => this.inspect().scripts.find((s) => s.name === NAME).vars.find(([n]) => n === name)?.[1]
|
|
1995
|
+
};
|
|
1996
|
+
}
|
|
1997
|
+
/**
|
|
1998
|
+
* The Declaration Documentation of a Function Value's defining code, even
|
|
1999
|
+
* when calling it would raise `function gone`. A Lambda's is empty; null
|
|
2000
|
+
* means the value is not a Function Value.
|
|
2001
|
+
*/
|
|
2002
|
+
functionDocumentation(value) {
|
|
2003
|
+
return functionDoc(value);
|
|
2004
|
+
}
|
|
2005
|
+
/**
|
|
2006
|
+
* An Entry or a Session Command. Returns the lines it printed. At a
|
|
2007
|
+
* debugger pause, only `:fix` of the paused Run.
|
|
2008
|
+
*/
|
|
2009
|
+
input(source) {
|
|
2010
|
+
if (this.state.k === "paused") {
|
|
2011
|
+
if (!/^:fix\b/u.test(source)) this.paused();
|
|
2012
|
+
this.unrecorded = true;
|
|
2013
|
+
try {
|
|
2014
|
+
return this.printed(this.entry(source));
|
|
2015
|
+
} finally {
|
|
2016
|
+
this.unrecorded = false;
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
this.callStart = this.recordedItems.length;
|
|
2020
|
+
this.recording = source.replace(/\n+$/, "");
|
|
2021
|
+
const out = this.entry(source);
|
|
2022
|
+
this.recorded();
|
|
2023
|
+
return this.finished(out);
|
|
2024
|
+
}
|
|
2025
|
+
recording = null;
|
|
2026
|
+
recordedItems = [];
|
|
2027
|
+
record(item) {
|
|
2028
|
+
if (this.unrecorded) return;
|
|
2029
|
+
this.recordedItems.push(item);
|
|
2030
|
+
this.env.record?.(item);
|
|
2031
|
+
}
|
|
2032
|
+
recorded() {
|
|
2033
|
+
if (this.recording !== null) {
|
|
2034
|
+
this.record({
|
|
2035
|
+
k: "input",
|
|
2036
|
+
source: this.recording
|
|
2037
|
+
});
|
|
2038
|
+
this.recording = null;
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
printed(lines) {
|
|
2042
|
+
const out = [...lines, ...this.observation.observed()];
|
|
2043
|
+
for (const text of out) this.record({
|
|
2044
|
+
k: "output",
|
|
2045
|
+
text
|
|
2046
|
+
});
|
|
2047
|
+
return out;
|
|
2048
|
+
}
|
|
2049
|
+
finished(lines) {
|
|
2050
|
+
const out = this.printed(lines);
|
|
2051
|
+
if (!this.group || this.state.k === "paused" || !this.controls.queuedInputs()) return out;
|
|
2052
|
+
this.callStart = this.recordedItems.length;
|
|
2053
|
+
return [...out, ...this.printed(this.pump())];
|
|
2054
|
+
}
|
|
2055
|
+
entry(source) {
|
|
2056
|
+
if (source.startsWith(":")) try {
|
|
2057
|
+
return this.command(source);
|
|
2058
|
+
} catch (error) {
|
|
2059
|
+
if (error instanceof RefusedError) return [`! ${error.message}`];
|
|
2060
|
+
throw error;
|
|
2061
|
+
}
|
|
2062
|
+
this.start();
|
|
2063
|
+
const parsed = parseEntry(source, (name) => this.isHandler(name));
|
|
2064
|
+
if (parsed.error) {
|
|
2065
|
+
const t = parsed.error.tok;
|
|
2066
|
+
return [`! ${parsed.error.code} at ${t.line}:${t.col}`];
|
|
2067
|
+
}
|
|
2068
|
+
if (!documentable(parsed.tree, parsed.kind)) return ["! bad arguments"];
|
|
2069
|
+
if (parsed.kind === null) return [];
|
|
2070
|
+
if (parsed.kind === "declaration") return this.declare(source.replace(/\n+$/, ""));
|
|
2071
|
+
return this.run(source.replace(/\n+$/, ""), parsed.kind === "expression").out;
|
|
2072
|
+
}
|
|
2073
|
+
/** Answers the Foreground Run's `read` with a line the user typed. */
|
|
2074
|
+
read(line) {
|
|
2075
|
+
this.paused();
|
|
2076
|
+
this.callStart = this.recordedItems.length;
|
|
2077
|
+
const pending = [...this.reads].find(([, r]) => r.run !== void 0 && r.run === this.foreground?.run);
|
|
2078
|
+
if (!pending) return [];
|
|
2079
|
+
this.reads.delete(pending[0]);
|
|
2080
|
+
this.record({
|
|
2081
|
+
k: "read",
|
|
2082
|
+
line
|
|
2083
|
+
});
|
|
2084
|
+
pending[1].call.answer(text(line));
|
|
2085
|
+
return this.finished(this.pump());
|
|
2086
|
+
}
|
|
2087
|
+
/**
|
|
2088
|
+
* Answers the Foreground Run's `user` prompt with what the person gave:
|
|
2089
|
+
* a boolean, the chosen item or items, the entered text, or Nothing.
|
|
2090
|
+
*/
|
|
2091
|
+
answerPrompt(answer) {
|
|
2092
|
+
this.paused();
|
|
2093
|
+
this.callStart = this.recordedItems.length;
|
|
2094
|
+
const pending = [...this.prompts].find(([, p]) => p.run !== void 0 && p.run === this.foreground?.run);
|
|
2095
|
+
if (!pending) return [];
|
|
2096
|
+
this.prompts.delete(pending[0]);
|
|
2097
|
+
this.record({
|
|
2098
|
+
k: "answer",
|
|
2099
|
+
call: pending[0],
|
|
2100
|
+
answer: answer.toString()
|
|
2101
|
+
});
|
|
2102
|
+
pending[1].call.answer(answer);
|
|
2103
|
+
return this.finished(this.pump());
|
|
2104
|
+
}
|
|
2105
|
+
/** `Inspect()`, which is the Host Input `vars`; null before the session starts. */
|
|
2106
|
+
inspect() {
|
|
2107
|
+
this.recorded();
|
|
2108
|
+
const view = this.group?.inspect() ?? null;
|
|
2109
|
+
if (view) this.objectSession?.snapshot(view.scripts);
|
|
2110
|
+
return view;
|
|
2111
|
+
}
|
|
2112
|
+
/** Replay an external action at its recorded position. */
|
|
2113
|
+
replayObjectItem(item) {
|
|
2114
|
+
this.start();
|
|
2115
|
+
this.objectSession.drain(item);
|
|
2116
|
+
}
|
|
2117
|
+
finishObjectReplay() {
|
|
2118
|
+
this.objectSession?.finish();
|
|
2119
|
+
}
|
|
2120
|
+
/** Pumps at a deadline, under a real Clock. */
|
|
2121
|
+
tick() {
|
|
2122
|
+
if (!this.group || this.state.k === "paused") return [];
|
|
2123
|
+
this.callStart = this.recordedItems.length;
|
|
2124
|
+
return this.finished(this.pump());
|
|
2125
|
+
}
|
|
2126
|
+
start(setup = this.setup0) {
|
|
2127
|
+
if (this.group) return;
|
|
2128
|
+
const capabilities = this.capabilities(setup);
|
|
2129
|
+
this.objectSession = new SessionObjects((item) => this.record(item), this.env.objectTranscript, this.env.objectTranscript === void 0 || !!this.env.objectTranscript?.some((i) => i.k === "envelope"));
|
|
2130
|
+
const port = this.objectSession.port((e) => this.events.push(e));
|
|
2131
|
+
const built = buildSetupGroup(setup, capabilities, {
|
|
2132
|
+
name: NAME,
|
|
2133
|
+
session: port,
|
|
2134
|
+
trace: (line) => this.env.trace?.(line)
|
|
2135
|
+
});
|
|
2136
|
+
const { group } = built;
|
|
2137
|
+
this.declarations0 = Object.fromEntries(capabilities);
|
|
2138
|
+
this.group = group;
|
|
2139
|
+
this.controls = port.controls;
|
|
2140
|
+
this.objectSession.attach(group, port);
|
|
2141
|
+
this.objectBindings = this.env.objectTranscript ? this.objectSession.preload() : this.env.objects?.(this.objectSession) ?? {};
|
|
2142
|
+
this.objectSession.initial(this.objectBindings);
|
|
2143
|
+
this.script = built.load(group, NAME, this.objectBindings);
|
|
2144
|
+
this.grantsByName = built.grants.get(NAME);
|
|
2145
|
+
}
|
|
2146
|
+
capabilities(setup = this.setup0) {
|
|
2147
|
+
const costs = new Map(setup.standard.map((s) => [s.capability, Object.fromEntries(Object.entries(s.costs).map(([name, cost]) => [name, {
|
|
2148
|
+
...cost,
|
|
2149
|
+
fuel: cost.fuel ?? 0
|
|
2150
|
+
}]))]));
|
|
2151
|
+
const console = consoleCapability({
|
|
2152
|
+
write: (call, value) => {
|
|
2153
|
+
this.writes.set(call.id, value);
|
|
2154
|
+
},
|
|
2155
|
+
read: (call) => {
|
|
2156
|
+
this.reads.set(call.id, { call });
|
|
2157
|
+
}
|
|
2158
|
+
}, costs.get("console"));
|
|
2159
|
+
const capabilities = this.mockCapabilities();
|
|
2160
|
+
capabilities.set("console", console);
|
|
2161
|
+
const granted = new Set(Object.entries(setup.scripts[0].grants).map(([name, g]) => g.capability ?? name));
|
|
2162
|
+
if (granted.has("clock")) capabilities.set("clock", clockCapability(costs.get("clock")));
|
|
2163
|
+
const { calendar, locale } = this.env.builtIns ?? {};
|
|
2164
|
+
if (granted.has("calendar") && calendar) capabilities.set("calendar", calendarCapability(this.answered(calendar, OPERATIONS.calendar), costs.get("calendar")));
|
|
2165
|
+
if (granted.has("locale") && locale) capabilities.set("locale", localeCapability(this.answered(locale, OPERATIONS.locale), costs.get("locale")));
|
|
2166
|
+
if (granted.has("user")) capabilities.set("user", userCapability(this.userHost(), costs.get("user")));
|
|
2167
|
+
if (granted.has("store")) capabilities.set("store", storeCapability(this.stores, costs.get("store")));
|
|
2168
|
+
for (const name of granted) {
|
|
2169
|
+
const extension = this.extensions.get(name);
|
|
2170
|
+
if (extension) capabilities.set(name, extension);
|
|
2171
|
+
}
|
|
2172
|
+
return capabilities;
|
|
2173
|
+
}
|
|
2174
|
+
ask(call, prompt) {
|
|
2175
|
+
if (this.prompts.size) {
|
|
2176
|
+
const busy = new ScriptError("user busy", "Another prompt is waiting for an answer");
|
|
2177
|
+
this.record({
|
|
2178
|
+
k: "answer",
|
|
2179
|
+
call: call.id,
|
|
2180
|
+
answer: `fail ${map([["code", text(busy.code)], ["message", text(busy.message)]]).toString()}`
|
|
2181
|
+
});
|
|
2182
|
+
throw busy;
|
|
2183
|
+
}
|
|
2184
|
+
this.prompts.set(call.id, {
|
|
2185
|
+
call,
|
|
2186
|
+
prompt
|
|
2187
|
+
});
|
|
2188
|
+
call.signal.addEventListener("abort", () => this.prompts.delete(call.id));
|
|
2189
|
+
}
|
|
2190
|
+
userHost() {
|
|
2191
|
+
return {
|
|
2192
|
+
confirm: (call, message) => this.ask(call, {
|
|
2193
|
+
k: "confirm",
|
|
2194
|
+
message
|
|
2195
|
+
}),
|
|
2196
|
+
choose: (call, items, prompt, multiple) => this.ask(call, {
|
|
2197
|
+
k: "choose",
|
|
2198
|
+
items,
|
|
2199
|
+
prompt,
|
|
2200
|
+
multiple
|
|
2201
|
+
}),
|
|
2202
|
+
enter: (call, message, fallback) => this.ask(call, {
|
|
2203
|
+
k: "enter",
|
|
2204
|
+
message,
|
|
2205
|
+
fallback
|
|
2206
|
+
}),
|
|
2207
|
+
notify: (call, message, title) => {
|
|
2208
|
+
this.notes.set(call.id, `* ${title ? `${title}: ` : ""}${message}`);
|
|
2209
|
+
}
|
|
2210
|
+
};
|
|
2211
|
+
}
|
|
2212
|
+
answered(impl, operations) {
|
|
2213
|
+
const wrapped = {};
|
|
2214
|
+
for (const op of operations) {
|
|
2215
|
+
const host = impl[op];
|
|
2216
|
+
wrapped[op] = (call, ...args) => {
|
|
2217
|
+
let value;
|
|
2218
|
+
try {
|
|
2219
|
+
value = host.call(impl, call, ...args);
|
|
2220
|
+
} catch (error) {
|
|
2221
|
+
this.record({
|
|
2222
|
+
k: "answer",
|
|
2223
|
+
call: call.id,
|
|
2224
|
+
answer: `fail ${error instanceof ScriptError ? map([
|
|
2225
|
+
["code", text(error.code)],
|
|
2226
|
+
["message", text(error.message)],
|
|
2227
|
+
...error.data.kind === "map" ? error.data.entries() : []
|
|
2228
|
+
]).toString() : "{}"}`
|
|
2229
|
+
});
|
|
2230
|
+
throw error;
|
|
2231
|
+
}
|
|
2232
|
+
this.record({
|
|
2233
|
+
k: "answer",
|
|
2234
|
+
call: call.id,
|
|
2235
|
+
answer: value.toString()
|
|
2236
|
+
});
|
|
2237
|
+
return value;
|
|
2238
|
+
};
|
|
2239
|
+
}
|
|
2240
|
+
return wrapped;
|
|
2241
|
+
}
|
|
2242
|
+
libraryDeclarations() {
|
|
2243
|
+
return operationDeclarations(new Map(Object.entries(this.declarations0)));
|
|
2244
|
+
}
|
|
2245
|
+
mockCapabilities() {
|
|
2246
|
+
const operations = /* @__PURE__ */ new Map();
|
|
2247
|
+
for (const spec of this.setup0.operations ?? []) {
|
|
2248
|
+
if (this.extensions.has(spec.capability)) continue;
|
|
2249
|
+
const { capability, name: operation, mode } = spec;
|
|
2250
|
+
const key = `${capability}.${operation}`;
|
|
2251
|
+
const base = {
|
|
2252
|
+
args: (spec.args ?? []).map(shapeOf),
|
|
2253
|
+
cost: {
|
|
2254
|
+
...spec.cost,
|
|
2255
|
+
fuel: spec.cost?.fuel ?? 0
|
|
2256
|
+
},
|
|
2257
|
+
...spec.command === void 0 ? {} : { command: spec.command },
|
|
2258
|
+
...spec.labels === void 0 ? {} : { labels: spec.labels }
|
|
2259
|
+
};
|
|
2260
|
+
const op = mode === "immediate" ? {
|
|
2261
|
+
...base,
|
|
2262
|
+
mode,
|
|
2263
|
+
result: shapeOf(spec.result),
|
|
2264
|
+
do: (call, ...args) => {
|
|
2265
|
+
this.mockCalls.set(call.id, {
|
|
2266
|
+
operation: key,
|
|
2267
|
+
args
|
|
2268
|
+
});
|
|
2269
|
+
return this.stubs.take(key, call, true);
|
|
2270
|
+
}
|
|
2271
|
+
} : mode === "suspending" ? {
|
|
2272
|
+
...base,
|
|
2273
|
+
mode,
|
|
2274
|
+
result: shapeOf(spec.result),
|
|
2275
|
+
start: (call, ...args) => {
|
|
2276
|
+
this.mockCalls.set(call.id, {
|
|
2277
|
+
operation: key,
|
|
2278
|
+
args
|
|
2279
|
+
});
|
|
2280
|
+
this.pending.set(call.id, call);
|
|
2281
|
+
}
|
|
2282
|
+
} : {
|
|
2283
|
+
...base,
|
|
2284
|
+
mode,
|
|
2285
|
+
fire: (call, ...args) => {
|
|
2286
|
+
this.mockCalls.set(call.id, {
|
|
2287
|
+
operation: key,
|
|
2288
|
+
args
|
|
2289
|
+
});
|
|
2290
|
+
}
|
|
2291
|
+
};
|
|
2292
|
+
operations.set(capability, {
|
|
2293
|
+
...operations.get(capability),
|
|
2294
|
+
[operation]: op
|
|
2295
|
+
});
|
|
2296
|
+
}
|
|
2297
|
+
return new Map([...operations].map(([name, ops]) => [name, defineValueCapability(name, ops)]));
|
|
2298
|
+
}
|
|
2299
|
+
command(source) {
|
|
2300
|
+
const [, name = "", rest = ""] = /^:(\S*)\s*(.*)$/su.exec(source) ?? [];
|
|
2301
|
+
switch (name) {
|
|
2302
|
+
case "grant": {
|
|
2303
|
+
const w = rest.trim().split(/\s+/u).filter(Boolean);
|
|
2304
|
+
return this.grant(w.length === 3 ? w : words(rest, 2));
|
|
2305
|
+
}
|
|
2306
|
+
case "mock": return this.mock(words(rest, 2));
|
|
2307
|
+
case "stub":
|
|
2308
|
+
this.start();
|
|
2309
|
+
return this.stub(rest);
|
|
2310
|
+
case "answer":
|
|
2311
|
+
case "fail":
|
|
2312
|
+
this.start();
|
|
2313
|
+
return this.settle(name, rest);
|
|
2314
|
+
case "clock":
|
|
2315
|
+
this.start();
|
|
2316
|
+
return this.clock(rest);
|
|
2317
|
+
case "limits":
|
|
2318
|
+
this.start();
|
|
2319
|
+
return this.limit(rest);
|
|
2320
|
+
case "cancel":
|
|
2321
|
+
this.start();
|
|
2322
|
+
return this.cancel(rest);
|
|
2323
|
+
case "fix":
|
|
2324
|
+
this.start();
|
|
2325
|
+
return this.fix(rest);
|
|
2326
|
+
case "save":
|
|
2327
|
+
this.start();
|
|
2328
|
+
return this.save(words(rest, rest.trim() ? 1 : 0)[0] ?? "default");
|
|
2329
|
+
case "restore":
|
|
2330
|
+
this.start();
|
|
2331
|
+
return this.restore(words(rest, rest.trim() ? 1 : 0)[0] ?? "default");
|
|
2332
|
+
case "library":
|
|
2333
|
+
this.start();
|
|
2334
|
+
return this.library(rest);
|
|
2335
|
+
case "export":
|
|
2336
|
+
this.start();
|
|
2337
|
+
return this.export(words(rest, rest.trim() ? 1 : 0)[0]);
|
|
2338
|
+
case "store": return this.store(rest);
|
|
2339
|
+
case "trace":
|
|
2340
|
+
case "untrace": return this.observation.trace(name, rest) ?? refuse("bad arguments");
|
|
2341
|
+
case "inspect": return this.inspectExpression(rest);
|
|
2342
|
+
case "fuel": return this.fuel(rest);
|
|
2343
|
+
case "describe":
|
|
2344
|
+
case "apropos":
|
|
2345
|
+
this.start();
|
|
2346
|
+
return (name === "describe" ? describe$1 : apropos)(this.names, rest.trim());
|
|
2347
|
+
case "runs":
|
|
2348
|
+
case "mailbox":
|
|
2349
|
+
case "vars":
|
|
2350
|
+
if (rest.trim()) refuse("bad arguments");
|
|
2351
|
+
this.start();
|
|
2352
|
+
return this.inspected(name);
|
|
2353
|
+
default: return refuse("unknown command");
|
|
2354
|
+
}
|
|
2355
|
+
}
|
|
2356
|
+
beforeStart() {
|
|
2357
|
+
if (this.group) refuse("session started");
|
|
2358
|
+
}
|
|
2359
|
+
grant([name, capability, binding]) {
|
|
2360
|
+
this.beforeStart();
|
|
2361
|
+
if (!NAME_TEXT.test(name) || name === "console" || !(this.builtIn(capability) || this.setup0.operations?.some((m) => m.capability === capability)) || binding !== void 0 && !(capability in DEFAULT_BINDING)) refuse("bad arguments");
|
|
2362
|
+
const script = this.setup0.scripts[0];
|
|
2363
|
+
const standard = this.setup0.standard;
|
|
2364
|
+
const costs = capability === "clock" ? { now: { fuel: 0 } } : capability === "store" ? STORE_COSTS : OPERATIONS[capability] ? free(OPERATIONS[capability]) : void 0;
|
|
2365
|
+
this.setup0 = immutableSetup({
|
|
2366
|
+
...this.setup0,
|
|
2367
|
+
scripts: [{
|
|
2368
|
+
...script,
|
|
2369
|
+
grants: {
|
|
2370
|
+
...script.grants,
|
|
2371
|
+
[name]: {
|
|
2372
|
+
capability,
|
|
2373
|
+
ops: "all",
|
|
2374
|
+
...(binding ?? DEFAULT_BINDING[capability]) === void 0 ? {} : { binding: binding ?? DEFAULT_BINDING[capability] }
|
|
2375
|
+
}
|
|
2376
|
+
}
|
|
2377
|
+
}],
|
|
2378
|
+
standard: costs && !standard.some((s) => s.capability === capability) ? [...standard, {
|
|
2379
|
+
capability,
|
|
2380
|
+
costs
|
|
2381
|
+
}] : standard,
|
|
2382
|
+
operations: this.extensions.has(capability) && !this.setup0.operations.some((op) => op.capability === capability) ? [...this.setup0.operations, ...capabilityOperations([this.extensions.get(capability)])] : this.setup0.operations
|
|
2383
|
+
});
|
|
2384
|
+
return [];
|
|
2385
|
+
}
|
|
2386
|
+
builtIn(capability) {
|
|
2387
|
+
return this.extensions.has(capability) || capability === "clock" || capability === "store" || capability === "user" || capability === "calendar" && Boolean(this.env.builtIns?.calendar) || capability === "locale" && Boolean(this.env.builtIns?.locale);
|
|
2388
|
+
}
|
|
2389
|
+
mock([target, mode]) {
|
|
2390
|
+
this.beforeStart();
|
|
2391
|
+
const [capability, operation, more] = target.split(".");
|
|
2392
|
+
if (more !== void 0 || !NAME_TEXT.test(capability ?? "") || !NAME_TEXT.test(operation ?? "") || capability === "console" || BUILT_IN.has(capability) || this.extensions.has(capability) || !MODES.has(mode)) refuse("bad arguments");
|
|
2393
|
+
const spec = {
|
|
2394
|
+
capability,
|
|
2395
|
+
name: operation,
|
|
2396
|
+
mode,
|
|
2397
|
+
args: Array.from({ length: 8 }, () => ({ optional: "any" })),
|
|
2398
|
+
...mode === "fire-and-forget" ? {} : { result: "any" },
|
|
2399
|
+
cost: { fuel: 0 }
|
|
2400
|
+
};
|
|
2401
|
+
const operations = this.setup0.operations;
|
|
2402
|
+
const i = operations.findIndex((m) => m.capability === capability && m.name === operation);
|
|
2403
|
+
const script = this.setup0.scripts[0];
|
|
2404
|
+
this.setup0 = immutableSetup({
|
|
2405
|
+
...this.setup0,
|
|
2406
|
+
operations: i < 0 ? [...operations, spec] : operations.map((m, at) => at === i ? spec : m),
|
|
2407
|
+
scripts: [{
|
|
2408
|
+
...script,
|
|
2409
|
+
grants: {
|
|
2410
|
+
...script.grants,
|
|
2411
|
+
[capability]: {
|
|
2412
|
+
capability,
|
|
2413
|
+
ops: "all"
|
|
2414
|
+
}
|
|
2415
|
+
}
|
|
2416
|
+
}]
|
|
2417
|
+
});
|
|
2418
|
+
return [];
|
|
2419
|
+
}
|
|
2420
|
+
stub(rest) {
|
|
2421
|
+
const [target = "", after = ""] = split(rest);
|
|
2422
|
+
const mock = this.setup0.operations?.find((m) => `${m.capability}.${m.name}` === target);
|
|
2423
|
+
if (mock?.mode !== "immediate" || this.extensions.has(mock.capability)) refuse("bad arguments");
|
|
2424
|
+
const [word, error] = split(after);
|
|
2425
|
+
const stub = word === "fail" ? {
|
|
2426
|
+
charge: 0,
|
|
2427
|
+
error: errorMap(error)
|
|
2428
|
+
} : {
|
|
2429
|
+
charge: 0,
|
|
2430
|
+
value: display(after)
|
|
2431
|
+
};
|
|
2432
|
+
this.stubs.add(target, stub);
|
|
2433
|
+
this.env.trace?.(stubLine(target, stub));
|
|
2434
|
+
return [];
|
|
2435
|
+
}
|
|
2436
|
+
settle(how, rest) {
|
|
2437
|
+
const [id = "", value = ""] = split(rest);
|
|
2438
|
+
const call = this.pending.get(id);
|
|
2439
|
+
const settled = how === "answer" ? display(value) : hostFailure(errorMap(value));
|
|
2440
|
+
if (!call || call.signal.aborted) return refuse("no such call");
|
|
2441
|
+
this.pending.delete(id);
|
|
2442
|
+
if (settled instanceof Error) call.fail(settled);
|
|
2443
|
+
else call.answer(settled);
|
|
2444
|
+
return this.pump();
|
|
2445
|
+
}
|
|
2446
|
+
isHandler(name) {
|
|
2447
|
+
return this.implicit.has(name) || this.declarations.some((d) => d.kind === "handler" && d.names[0]?.split(":")[0] === name);
|
|
2448
|
+
}
|
|
2449
|
+
has(name) {
|
|
2450
|
+
return Object.hasOwn(this.objectBindings, name) || this.implicit.has(name) || this.declarations.some((d) => d.names.includes(name));
|
|
2451
|
+
}
|
|
2452
|
+
sessionSource(declarations) {
|
|
2453
|
+
return declarations.map((d) => `${d.source}\n`).join("");
|
|
2454
|
+
}
|
|
2455
|
+
declare(source) {
|
|
2456
|
+
const decl = describe(source);
|
|
2457
|
+
if (!decl.names.some((n) => this.has(n))) {
|
|
2458
|
+
try {
|
|
2459
|
+
this.script.extend(source);
|
|
2460
|
+
} catch (error) {
|
|
2461
|
+
return this.refused(error, {
|
|
2462
|
+
line: 0,
|
|
2463
|
+
col: 0
|
|
2464
|
+
});
|
|
2465
|
+
}
|
|
2466
|
+
this.declarations.push({
|
|
2467
|
+
...decl,
|
|
2468
|
+
unit: `${NAME}+${this.units++}`,
|
|
2469
|
+
unitLine: 1
|
|
2470
|
+
});
|
|
2471
|
+
return [];
|
|
2472
|
+
}
|
|
2473
|
+
if (decl.kind === "variable" && this.declarations.some((d) => d.kind === "variable" && d.names[0] === decl.names[0])) return this.redeclareVariable(source, decl);
|
|
2474
|
+
return this.redefine(decl);
|
|
2475
|
+
}
|
|
2476
|
+
redeclareVariable(source, decl) {
|
|
2477
|
+
const name = decl.names[0];
|
|
2478
|
+
const tree = parseSource(source).tree;
|
|
2479
|
+
const declaration = nodes(tree)[0];
|
|
2480
|
+
const init = nodes(declaration).find((n) => n.rule === "Expression");
|
|
2481
|
+
const statement = init ? `put ${source.slice(init.start, init.end)} into ${name}` : `put nothing into ${name}`;
|
|
2482
|
+
const index = this.declarations.findIndex((d) => d.kind === "variable" && d.names[0] === name);
|
|
2483
|
+
const before = this.declarations;
|
|
2484
|
+
this.declarations = before.map((d, i) => i === index ? {
|
|
2485
|
+
...decl,
|
|
2486
|
+
unit: d.unit,
|
|
2487
|
+
unitLine: d.unitLine
|
|
2488
|
+
} : d);
|
|
2489
|
+
const { loaded, out } = this.run(statement, false);
|
|
2490
|
+
if (!loaded) this.declarations = before;
|
|
2491
|
+
return out;
|
|
2492
|
+
}
|
|
2493
|
+
redefine(decl) {
|
|
2494
|
+
const next = placed(this.declarations, decl);
|
|
2495
|
+
const start = next.indexOf(decl);
|
|
2496
|
+
const line = next.slice(0, start).reduce((n, d) => n + lineCount(d.source), 0);
|
|
2497
|
+
try {
|
|
2498
|
+
return this.reloadFrom(next);
|
|
2499
|
+
} catch (error) {
|
|
2500
|
+
return this.refused(error, {
|
|
2501
|
+
line,
|
|
2502
|
+
col: 0
|
|
2503
|
+
}, lineCount(decl.source));
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
reloadFrom(next, keepMailbox = false, entry) {
|
|
2507
|
+
const handler = entry && this.entryHandlers.get(entry);
|
|
2508
|
+
const reports = this.script.reload(this.sessionSource(next) + (handler ?? ""), "carry variables", { keepMailbox });
|
|
2509
|
+
if (terminalEffects(reports)) {
|
|
2510
|
+
this.deadline = void 0;
|
|
2511
|
+
return this.discarded(reports);
|
|
2512
|
+
}
|
|
2513
|
+
let at = 1;
|
|
2514
|
+
this.declarations = next.map((d) => {
|
|
2515
|
+
const placed = {
|
|
2516
|
+
...d,
|
|
2517
|
+
unit: NAME,
|
|
2518
|
+
unitLine: at
|
|
2519
|
+
};
|
|
2520
|
+
at += lineCount(d.source);
|
|
2521
|
+
return placed;
|
|
2522
|
+
});
|
|
2523
|
+
this.implicit.clear();
|
|
2524
|
+
this.entryHandlers.clear();
|
|
2525
|
+
if (handler) {
|
|
2526
|
+
this.implicit.add(entry);
|
|
2527
|
+
this.entryHandlers.set(entry, handler);
|
|
2528
|
+
}
|
|
2529
|
+
this.placements.clear();
|
|
2530
|
+
this.units = 1;
|
|
2531
|
+
this.deadline = void 0;
|
|
2532
|
+
return this.discarded(reports);
|
|
2533
|
+
}
|
|
2534
|
+
fix(rest) {
|
|
2535
|
+
const newline = rest.indexOf("\n");
|
|
2536
|
+
const [run, path, more] = (newline < 0 ? rest : rest.slice(0, newline)).trim().split(/\s+/u);
|
|
2537
|
+
if (!run || more !== void 0 || newline < 0 === (path === void 0)) refuse("bad arguments");
|
|
2538
|
+
let source;
|
|
2539
|
+
if (newline >= 0) source = `${rest.slice(newline + 1)}\n`;
|
|
2540
|
+
else {
|
|
2541
|
+
try {
|
|
2542
|
+
source = librarySource(this.env.readFile(path));
|
|
2543
|
+
} catch {
|
|
2544
|
+
return refuse("bad arguments");
|
|
2545
|
+
}
|
|
2546
|
+
this.recording = `:fix ${run}\n${source.slice(0, -1)}`;
|
|
2547
|
+
}
|
|
2548
|
+
const parsed = parseSource(source);
|
|
2549
|
+
if (parsed.error) {
|
|
2550
|
+
const t = parsed.error.tok;
|
|
2551
|
+
return [`! ${parsed.error.code} at ${t.line}:${t.col}`];
|
|
2552
|
+
}
|
|
2553
|
+
const declarations = fixDeclarations(source, parsed.tree);
|
|
2554
|
+
if (!declarations.length) refuse("bad arguments");
|
|
2555
|
+
let entry;
|
|
2556
|
+
const controller = this.state.k === "paused" ? this.controller : null;
|
|
2557
|
+
if (controller) {
|
|
2558
|
+
const paused = controller.snapshot().scripts.find((s) => s.name === NAME).runs.find((r) => r.id === run);
|
|
2559
|
+
if (!paused) refuse("no such run");
|
|
2560
|
+
if (controller.current.run !== run) throw new Error(`At a pause, :fix rewinds only ${controller.current.run}`);
|
|
2561
|
+
if (!paused.rewindable) refuse("not rewindable");
|
|
2562
|
+
entry = paused.handler;
|
|
2563
|
+
} else if (!this.lastSeg.has(run)) refuse("no such run");
|
|
2564
|
+
this.script.rewindRun(run);
|
|
2565
|
+
const held = this.foreground;
|
|
2566
|
+
let out;
|
|
2567
|
+
if (controller) {
|
|
2568
|
+
this.transcriptEnd ??= this.callStart;
|
|
2569
|
+
this.env.transcriptEnds?.(this.recordedItems.length - this.callStart);
|
|
2570
|
+
this.unrecorded = false;
|
|
2571
|
+
const landed = controller.resume();
|
|
2572
|
+
this.rewound = landed.state === "rewound";
|
|
2573
|
+
out = [...this.pumped(landed), ...this.notifications()];
|
|
2574
|
+
} else out = this.pump();
|
|
2575
|
+
if (!this.rewound) return [...out, "! not rewindable"];
|
|
2576
|
+
this.lastSeg.delete(run);
|
|
2577
|
+
if (held && held.run === run) this.foreground = { delivery: held.delivery };
|
|
2578
|
+
out.push(`! rewound ${run}`);
|
|
2579
|
+
const next = declarations.reduce(placed, this.declarations);
|
|
2580
|
+
try {
|
|
2581
|
+
out.push(...this.reloadFrom(next, true, entry));
|
|
2582
|
+
} catch (error) {
|
|
2583
|
+
out.push(...this.refused(error, {
|
|
2584
|
+
line: 0,
|
|
2585
|
+
col: 0
|
|
2586
|
+
}, 0));
|
|
2587
|
+
}
|
|
2588
|
+
if (controller) controller.pauseAtNextStart(NAME);
|
|
2589
|
+
return [...out, ...this.pump()];
|
|
2590
|
+
}
|
|
2591
|
+
clock(rest) {
|
|
2592
|
+
const [word = "", arg = ""] = split(rest);
|
|
2593
|
+
if (word === "") return [this.virtual === null ? `real${this.lastClock === null ? "" : ` ${formatInstant(this.lastClock)}`}` : `virtual ${formatInstant(this.virtual)}`];
|
|
2594
|
+
if (word === "real" && !arg) {
|
|
2595
|
+
this.virtual = null;
|
|
2596
|
+
return [];
|
|
2597
|
+
}
|
|
2598
|
+
if (word === "virtual") {
|
|
2599
|
+
let at;
|
|
2600
|
+
try {
|
|
2601
|
+
at = arg ? parseInstant(arg) : this.lastClock ?? this.env.now();
|
|
2602
|
+
this.recording = `:clock virtual ${formatInstant(at)}`;
|
|
2603
|
+
} catch {
|
|
2604
|
+
return refuse("bad arguments");
|
|
2605
|
+
}
|
|
2606
|
+
if (this.lastClock !== null && at < this.lastClock) refuse("clock backwards");
|
|
2607
|
+
this.virtual = at;
|
|
2608
|
+
return [];
|
|
2609
|
+
}
|
|
2610
|
+
if (word === "advance") {
|
|
2611
|
+
if (this.virtual === null) refuse("clock is real");
|
|
2612
|
+
let us;
|
|
2613
|
+
try {
|
|
2614
|
+
us = waitUs(display(arg));
|
|
2615
|
+
} catch {
|
|
2616
|
+
return refuse("bad arguments");
|
|
2617
|
+
}
|
|
2618
|
+
if (us < 0n) refuse("bad arguments");
|
|
2619
|
+
this.virtual += us;
|
|
2620
|
+
return this.pump();
|
|
2621
|
+
}
|
|
2622
|
+
return refuse("bad arguments");
|
|
2623
|
+
}
|
|
2624
|
+
limit(rest) {
|
|
2625
|
+
const w = rest.trim().split(/\s+/u).filter(Boolean);
|
|
2626
|
+
if (!w.length) return OVERRIDABLE.map((name) => `${name} ${this.limits[name] ?? defaultLimits[name]}`);
|
|
2627
|
+
if (w.length === 1 && w[0] === "reset") {
|
|
2628
|
+
this.limits = {};
|
|
2629
|
+
return [];
|
|
2630
|
+
}
|
|
2631
|
+
const [name, value] = w;
|
|
2632
|
+
if (w.length !== 2 || !OVERRIDABLE.includes(name) || !/^\d+$/u.test(value)) refuse("bad arguments");
|
|
2633
|
+
const n = Number(value);
|
|
2634
|
+
if (!Number.isSafeInteger(n) || n > defaultLimits[name]) refuse("invalid value");
|
|
2635
|
+
this.limits = {
|
|
2636
|
+
...this.limits,
|
|
2637
|
+
[name]: n
|
|
2638
|
+
};
|
|
2639
|
+
return [];
|
|
2640
|
+
}
|
|
2641
|
+
cancel(rest) {
|
|
2642
|
+
const run = words(rest, rest.trim() ? 1 : 0)[0] ?? this.latest?.run;
|
|
2643
|
+
if (!run || !this.lastSeg.has(run)) refuse("no such run");
|
|
2644
|
+
this.script.cancelRun(run);
|
|
2645
|
+
return this.pump();
|
|
2646
|
+
}
|
|
2647
|
+
fuel(rest) {
|
|
2648
|
+
if (!rest.trim()) return this.observation.rows();
|
|
2649
|
+
if (rest.startsWith(":")) refuse("bad arguments");
|
|
2650
|
+
this.start();
|
|
2651
|
+
const parsed = parseEntry(rest, (name) => this.isHandler(name));
|
|
2652
|
+
if (parsed.error) {
|
|
2653
|
+
const t = parsed.error.tok;
|
|
2654
|
+
return [`! ${parsed.error.code} at ${t.line}:${t.col}`];
|
|
2655
|
+
}
|
|
2656
|
+
if (!documentable(parsed.tree, parsed.kind) || parsed.kind !== "statement" && parsed.kind !== "expression") refuse("bad arguments");
|
|
2657
|
+
this.measuring = true;
|
|
2658
|
+
try {
|
|
2659
|
+
return this.run(rest.replace(/\n+$/, ""), parsed.kind === "expression").out;
|
|
2660
|
+
} finally {
|
|
2661
|
+
this.measuring = false;
|
|
2662
|
+
}
|
|
2663
|
+
}
|
|
2664
|
+
save(name) {
|
|
2665
|
+
const checkpoint = this.stores.router.save(this.group);
|
|
2666
|
+
this.saves.set(name, {
|
|
2667
|
+
checkpoint,
|
|
2668
|
+
declarations: [...this.declarations],
|
|
2669
|
+
implicit: new Set(this.implicit),
|
|
2670
|
+
lastEntry: this.lastEntry,
|
|
2671
|
+
units: this.units,
|
|
2672
|
+
placements: new Map(this.placements),
|
|
2673
|
+
expressions: new Set(this.expressions),
|
|
2674
|
+
inspections: new Set(this.inspections),
|
|
2675
|
+
lastSeg: new Map(this.lastSeg),
|
|
2676
|
+
latest: this.latest && { ...this.latest },
|
|
2677
|
+
limits: { ...this.limits },
|
|
2678
|
+
virtual: this.virtual,
|
|
2679
|
+
lastClock: this.lastClock,
|
|
2680
|
+
deadline: this.deadline,
|
|
2681
|
+
stubs: this.stubs.clone(),
|
|
2682
|
+
observation: this.observation.clone()
|
|
2683
|
+
});
|
|
2684
|
+
return [`saved ${name}`];
|
|
2685
|
+
}
|
|
2686
|
+
restore(name) {
|
|
2687
|
+
const saved = this.saves.get(name);
|
|
2688
|
+
if (!saved) return refuse("no such save");
|
|
2689
|
+
this.recorded();
|
|
2690
|
+
let restored;
|
|
2691
|
+
const port = this.objectSession.port((e) => this.events.push(e));
|
|
2692
|
+
this.notified = false;
|
|
2693
|
+
try {
|
|
2694
|
+
restored = this.stores.router.restore({ restore }, saved.checkpoint, {
|
|
2695
|
+
name: NAME,
|
|
2696
|
+
session: port,
|
|
2697
|
+
trace: (line) => this.env.trace?.(line),
|
|
2698
|
+
libraries: [...this.libraries.values()].map((l) => l.library),
|
|
2699
|
+
grants: (_, grant) => this.grantsByName[grant],
|
|
2700
|
+
resolve: (kind, id) => this.objectSession.resolve(kind, id, this.env.resolveObject),
|
|
2701
|
+
onMismatch: "reject"
|
|
2702
|
+
});
|
|
2703
|
+
} catch (error) {
|
|
2704
|
+
if (error instanceof HostError) return refuse(error.code);
|
|
2705
|
+
throw error;
|
|
2706
|
+
}
|
|
2707
|
+
const { group, result } = restored;
|
|
2708
|
+
this.stores.router.detach(this.group);
|
|
2709
|
+
this.group = group;
|
|
2710
|
+
this.controls = port.controls;
|
|
2711
|
+
this.objectSession.restored();
|
|
2712
|
+
this.objectSession.attach(group, port);
|
|
2713
|
+
this.objectSession.reports(result.reports);
|
|
2714
|
+
this.controller = null;
|
|
2715
|
+
this.script = group.script(NAME);
|
|
2716
|
+
this.declarations = [...saved.declarations];
|
|
2717
|
+
this.implicit = new Set(saved.implicit);
|
|
2718
|
+
this.lastEntry = saved.lastEntry;
|
|
2719
|
+
this.units = saved.units;
|
|
2720
|
+
this.placements = new Map(saved.placements);
|
|
2721
|
+
this.expressions = new Set(saved.expressions);
|
|
2722
|
+
this.inspections = new Set(saved.inspections);
|
|
2723
|
+
this.lastSeg = new Map(saved.lastSeg);
|
|
2724
|
+
this.latest = saved.latest && { ...saved.latest };
|
|
2725
|
+
this.limits = { ...saved.limits };
|
|
2726
|
+
this.virtual = saved.virtual;
|
|
2727
|
+
this.lastClock = saved.lastClock;
|
|
2728
|
+
this.deadline = saved.deadline;
|
|
2729
|
+
this.stubs = saved.stubs.clone();
|
|
2730
|
+
const abandoned = this.observation.pending();
|
|
2731
|
+
this.observation = saved.observation.clone();
|
|
2732
|
+
this.observation.observe(result.reports);
|
|
2733
|
+
this.foreground = null;
|
|
2734
|
+
this.state = { k: "prompt" };
|
|
2735
|
+
this.writes.clear();
|
|
2736
|
+
this.reads.clear();
|
|
2737
|
+
this.prompts.clear();
|
|
2738
|
+
this.notes.clear();
|
|
2739
|
+
this.pending.clear();
|
|
2740
|
+
this.mockCalls.clear();
|
|
2741
|
+
for (const call of result.pending) {
|
|
2742
|
+
const adopted = group.settle(call.id, { adopt: true });
|
|
2743
|
+
const run = call.id.slice(0, call.id.lastIndexOf("."));
|
|
2744
|
+
if (call.grant === "console") this.reads.set(call.id, {
|
|
2745
|
+
call: adopted,
|
|
2746
|
+
run
|
|
2747
|
+
});
|
|
2748
|
+
else if (call.operation.capability === "user") {
|
|
2749
|
+
this.prompts.set(call.id, {
|
|
2750
|
+
call: adopted,
|
|
2751
|
+
prompt: promptOf(call.operation.operation, call.args),
|
|
2752
|
+
run
|
|
2753
|
+
});
|
|
2754
|
+
adopted.signal.addEventListener("abort", () => this.prompts.delete(call.id));
|
|
2755
|
+
} else this.pending.set(call.id, adopted);
|
|
2756
|
+
}
|
|
2757
|
+
for (const run of result.discardedRuns) this.lastSeg.delete(run);
|
|
2758
|
+
return [
|
|
2759
|
+
`restored ${name}`,
|
|
2760
|
+
...result.discardedRuns.map((run) => `! discarded ${run}`),
|
|
2761
|
+
...abandoned.map((entry) => `fuel abandoned ${text(entry).toString()}`),
|
|
2762
|
+
...this.notifiedPump()
|
|
2763
|
+
];
|
|
2764
|
+
}
|
|
2765
|
+
library(rest) {
|
|
2766
|
+
const newline = rest.indexOf("\n");
|
|
2767
|
+
const [how, name, path, more] = (newline < 0 ? rest : rest.slice(0, newline)).trim().split(/\s+/u);
|
|
2768
|
+
if (how !== "add" && how !== "replace" || !NAME_TEXT.test(name ?? "") || more !== void 0 || newline < 0 === (path === void 0)) refuse("bad arguments");
|
|
2769
|
+
let source;
|
|
2770
|
+
if (newline >= 0) source = `${rest.slice(newline + 1)}\n`;
|
|
2771
|
+
else {
|
|
2772
|
+
try {
|
|
2773
|
+
source = librarySource(this.env.readFile(path));
|
|
2774
|
+
} catch {
|
|
2775
|
+
return refuse("bad arguments");
|
|
2776
|
+
}
|
|
2777
|
+
this.recording = `:library ${how} ${name}\n${source.slice(0, -1)}`;
|
|
2778
|
+
}
|
|
2779
|
+
const held = this.libraries.get(name);
|
|
2780
|
+
if (how === "add" && held) refuse("name reused");
|
|
2781
|
+
if (how === "replace" && !held) refuse("library mismatch");
|
|
2782
|
+
let library;
|
|
2783
|
+
try {
|
|
2784
|
+
library = compileLibrary({
|
|
2785
|
+
name,
|
|
2786
|
+
version: LIBRARY_VERSION,
|
|
2787
|
+
source
|
|
2788
|
+
}, [...this.libraries.values()].filter((l) => l.library.name !== name).map((l) => l.library), this.libraryDeclarations());
|
|
2789
|
+
} catch (error) {
|
|
2790
|
+
if (error instanceof LoadError) return error.diagnostics.map((d) => `! ${d.code} at ${d.unit}:${d.line}:${d.col}`);
|
|
2791
|
+
throw error;
|
|
2792
|
+
}
|
|
2793
|
+
let reports = [];
|
|
2794
|
+
try {
|
|
2795
|
+
if (how === "add") this.group.addLibrary(library);
|
|
2796
|
+
else reports = this.group.replaceLibrary(library, "carry variables");
|
|
2797
|
+
} catch (error) {
|
|
2798
|
+
return this.refused(error, {
|
|
2799
|
+
line: 0,
|
|
2800
|
+
col: 0
|
|
2801
|
+
});
|
|
2802
|
+
}
|
|
2803
|
+
if (terminalEffects(reports)) {
|
|
2804
|
+
this.deadline = void 0;
|
|
2805
|
+
return this.discarded(reports);
|
|
2806
|
+
}
|
|
2807
|
+
this.libraries.set(name, { library });
|
|
2808
|
+
if (how === "add") this.setup0 = immutableSetup({
|
|
2809
|
+
...this.setup0,
|
|
2810
|
+
libraries: [...this.setup0.libraries, {
|
|
2811
|
+
name,
|
|
2812
|
+
version: LIBRARY_VERSION,
|
|
2813
|
+
source: "(inline)",
|
|
2814
|
+
text: source
|
|
2815
|
+
}]
|
|
2816
|
+
});
|
|
2817
|
+
return this.discarded(reports);
|
|
2818
|
+
}
|
|
2819
|
+
store(rest) {
|
|
2820
|
+
const newline = rest.indexOf("\n");
|
|
2821
|
+
const w = (newline < 0 ? rest : rest.slice(0, newline)).trim().split(/\s+/u).filter(Boolean);
|
|
2822
|
+
const [form] = w;
|
|
2823
|
+
if (form === "load") {
|
|
2824
|
+
const inline = newline >= 0;
|
|
2825
|
+
if (w.length > (inline ? 2 : 3) || !inline && w.length < 2) refuse("bad arguments");
|
|
2826
|
+
const name = (inline ? w[1] : w[2]) ?? "default";
|
|
2827
|
+
let contents;
|
|
2828
|
+
if (inline) contents = rest.slice(newline + 1);
|
|
2829
|
+
else {
|
|
2830
|
+
try {
|
|
2831
|
+
contents = this.env.readStoreFile(w[1]);
|
|
2832
|
+
} catch {
|
|
2833
|
+
return refuse("bad arguments");
|
|
2834
|
+
}
|
|
2835
|
+
this.recording = `:store load${w[2] ? ` ${w[2]}` : ""}\n${contents.replace(/\n$/u, "")}`;
|
|
2836
|
+
}
|
|
2837
|
+
try {
|
|
2838
|
+
this.notified = false;
|
|
2839
|
+
this.stores.replace(name, decodeContents(contents));
|
|
2840
|
+
return [`loaded ${this.stores.entries(name).length} keys`, ...this.notifiedPump()];
|
|
2841
|
+
} catch (error) {
|
|
2842
|
+
if (error instanceof HostError || error instanceof StoreContentsError) return refuse("bad arguments");
|
|
2843
|
+
throw error;
|
|
2844
|
+
}
|
|
2845
|
+
}
|
|
2846
|
+
if (newline >= 0) refuse("bad arguments");
|
|
2847
|
+
if (form === "save") {
|
|
2848
|
+
if (w.length < 2 || w.length > 3 || !this.env.writeStoreFile) refuse("bad arguments");
|
|
2849
|
+
this.env.writeStoreFile(w[1], encodeContents(this.stores.entries(w[2] ?? "default")));
|
|
2850
|
+
return [`wrote ${w[1]}`];
|
|
2851
|
+
}
|
|
2852
|
+
if (form === "clear") {
|
|
2853
|
+
if (w.length > 2) refuse("bad arguments");
|
|
2854
|
+
const name = w[1] ?? "default";
|
|
2855
|
+
this.notified = false;
|
|
2856
|
+
this.stores.clear(name);
|
|
2857
|
+
return [`cleared ${name}`, ...this.notifiedPump()];
|
|
2858
|
+
}
|
|
2859
|
+
if (w.length > 1) refuse("bad arguments");
|
|
2860
|
+
return this.stores.entries(form ?? "default").map(([key, value]) => `${text(key).toString()} = ${value.toString()}`);
|
|
2861
|
+
}
|
|
2862
|
+
export(directory) {
|
|
2863
|
+
if (directory === void 0) return lines(this.source).slice(0, -1);
|
|
2864
|
+
if (!this.env.writeFile) refuse("bad arguments");
|
|
2865
|
+
const files = [["session.talk", this.source], ...[...this.libraries].map(([name, l]) => [`${name}.talk`, l.library.source])];
|
|
2866
|
+
for (const [file, text] of files) this.env.writeFile(directory, file, text);
|
|
2867
|
+
return files.map(([file]) => `wrote ${file}`);
|
|
2868
|
+
}
|
|
2869
|
+
inspected(what) {
|
|
2870
|
+
const script = this.inspect().scripts.find((s) => s.name === NAME);
|
|
2871
|
+
if (what === "vars") return script.vars.map(([name, value]) => `${name} = ${value.toString()}`);
|
|
2872
|
+
if (what === "mailbox") return script.mailbox.map((m) => `${m.delivery ?? m.from} ${m.message.name} ${listValues(m.message.args ?? []).toString()}`);
|
|
2873
|
+
return script.runs.map((r) => [
|
|
2874
|
+
r.id,
|
|
2875
|
+
r.status,
|
|
2876
|
+
r.handler,
|
|
2877
|
+
...r.status === "suspended" ? [
|
|
2878
|
+
r.wait,
|
|
2879
|
+
...r.until === void 0 ? [] : ["until", formatInstant(r.until)],
|
|
2880
|
+
...r.calls ?? []
|
|
2881
|
+
] : []
|
|
2882
|
+
].join(" "));
|
|
2883
|
+
}
|
|
2884
|
+
discarded(reports) {
|
|
2885
|
+
this.objectSession?.reports(reports);
|
|
2886
|
+
this.observation.observe(reports);
|
|
2887
|
+
const out = [];
|
|
2888
|
+
for (const r of reports) {
|
|
2889
|
+
if (r.kind === "effect failure") out.push(this.prefix(r.run) + effectFailureText(r));
|
|
2890
|
+
if (r.kind === "stop") {
|
|
2891
|
+
if (r.reason === "effect state unknown") out.push("! effect state unknown");
|
|
2892
|
+
for (const run of r.discardedRuns) {
|
|
2893
|
+
out.push(`! discarded ${run}`);
|
|
2894
|
+
this.lastSeg.delete(run);
|
|
2895
|
+
if (this.foreground?.run === run) {
|
|
2896
|
+
this.foreground = null;
|
|
2897
|
+
this.state = { k: "prompt" };
|
|
2898
|
+
}
|
|
2899
|
+
}
|
|
2900
|
+
}
|
|
2901
|
+
}
|
|
2902
|
+
return out;
|
|
2903
|
+
}
|
|
2904
|
+
refused(error, at, length = Infinity) {
|
|
2905
|
+
if (error instanceof LoadError) return error.diagnostics.map((d) => `! ${d.code} at ${where(d, at, length)}`);
|
|
2906
|
+
if (error instanceof HostError) return [`! ${error.code}`];
|
|
2907
|
+
throw error;
|
|
2908
|
+
}
|
|
2909
|
+
inspectExpression(source) {
|
|
2910
|
+
const parsed = parseEntry(source, (name) => this.isHandler(name));
|
|
2911
|
+
if (parsed.error) {
|
|
2912
|
+
if (parsed.error.trailingEntry) return refuse("bad arguments");
|
|
2913
|
+
return [`! ${parsed.error.code} at ${parsed.error.tok.line}:${parsed.error.tok.col}`];
|
|
2914
|
+
}
|
|
2915
|
+
if (parsed.kind !== "expression" || !documentable(parsed.tree, parsed.kind)) refuse("bad arguments");
|
|
2916
|
+
this.start();
|
|
2917
|
+
this.inspecting = true;
|
|
2918
|
+
try {
|
|
2919
|
+
return this.run(source.replace(/\n+$/, ""), true).out;
|
|
2920
|
+
} finally {
|
|
2921
|
+
this.inspecting = false;
|
|
2922
|
+
}
|
|
2923
|
+
}
|
|
2924
|
+
readProperties(value) {
|
|
2925
|
+
const identifiers = [...new Set(inspectReader.match(/\bentry0\w*/g))];
|
|
2926
|
+
let n = this.lastEntry + 1;
|
|
2927
|
+
while (identifiers.some((id) => this.has(id.replace("entry0", `entry${n}`)) || this.isHandler(id.replace("entry0", `entry${n}`)))) n++;
|
|
2928
|
+
const handler = `entry${n}`;
|
|
2929
|
+
const source = inspectReader.replaceAll(/\bentry0\w*/g, (id) => id.replace("entry0", handler));
|
|
2930
|
+
try {
|
|
2931
|
+
this.script.extend(source);
|
|
2932
|
+
} catch (error) {
|
|
2933
|
+
return this.refused(error, {
|
|
2934
|
+
line: 0,
|
|
2935
|
+
col: 0
|
|
2936
|
+
});
|
|
2937
|
+
}
|
|
2938
|
+
this.lastEntry = n;
|
|
2939
|
+
this.implicit.add(handler);
|
|
2940
|
+
this.units++;
|
|
2941
|
+
const { id } = this.script.request({
|
|
2942
|
+
name: `${handler}:to:`,
|
|
2943
|
+
args: [value, listValues(propertyNames(value).map(text))],
|
|
2944
|
+
...Object.keys(this.limits).length ? { limits: this.limits } : {}
|
|
2945
|
+
});
|
|
2946
|
+
this.foreground = { delivery: id };
|
|
2947
|
+
this.latest = { delivery: id };
|
|
2948
|
+
return this.pump();
|
|
2949
|
+
}
|
|
2950
|
+
run(source, expression) {
|
|
2951
|
+
let n = this.lastEntry + 1;
|
|
2952
|
+
while (this.has(`entry${n}`)) n++;
|
|
2953
|
+
const handler = `entry${n}`;
|
|
2954
|
+
const bound = this.implicitVariables(source, handler);
|
|
2955
|
+
const body = lines(source);
|
|
2956
|
+
if (expression) body[0] = `return ${body[0]}`;
|
|
2957
|
+
const unit = [
|
|
2958
|
+
...bound.map((v) => `script variable ${v}`),
|
|
2959
|
+
`on ${handler}`,
|
|
2960
|
+
...body,
|
|
2961
|
+
`end ${handler}`
|
|
2962
|
+
].map((l) => `${l}\n`).join("");
|
|
2963
|
+
const placement = {
|
|
2964
|
+
line: bound.length + 1,
|
|
2965
|
+
col: expression ? 7 : 0
|
|
2966
|
+
};
|
|
2967
|
+
try {
|
|
2968
|
+
this.script.extend(unit);
|
|
2969
|
+
} catch (error) {
|
|
2970
|
+
return {
|
|
2971
|
+
loaded: false,
|
|
2972
|
+
out: this.refused(error, placement, body.length)
|
|
2973
|
+
};
|
|
2974
|
+
}
|
|
2975
|
+
this.lastEntry = n;
|
|
2976
|
+
this.implicit.add(handler);
|
|
2977
|
+
this.entryHandlers.set(handler, unit.split("\n").slice(bound.length).join("\n"));
|
|
2978
|
+
const extension = `${NAME}+${this.units++}`;
|
|
2979
|
+
this.placements.set(extension, placement);
|
|
2980
|
+
for (const [i, v] of bound.entries()) this.declarations.push({
|
|
2981
|
+
kind: "variable",
|
|
2982
|
+
names: [v],
|
|
2983
|
+
source: `script variable ${v}`,
|
|
2984
|
+
unit: extension,
|
|
2985
|
+
unitLine: i + 1
|
|
2986
|
+
});
|
|
2987
|
+
const { id } = this.script.request({
|
|
2988
|
+
name: handler,
|
|
2989
|
+
...Object.keys(this.limits).length ? { limits: this.limits } : {}
|
|
2990
|
+
});
|
|
2991
|
+
this.foreground = { delivery: id };
|
|
2992
|
+
this.latest = { delivery: id };
|
|
2993
|
+
if (this.measuring) this.observation.measure(n, id);
|
|
2994
|
+
if (this.inspecting) this.inspections.add(id);
|
|
2995
|
+
if (expression) this.expressions.add(id);
|
|
2996
|
+
return {
|
|
2997
|
+
loaded: true,
|
|
2998
|
+
out: this.pump()
|
|
2999
|
+
};
|
|
3000
|
+
}
|
|
3001
|
+
implicitVariables(source, handler) {
|
|
3002
|
+
const probe = `${this.source}on ${handler}\n${source}\nend ${handler}\n`;
|
|
3003
|
+
const checked = checkSource(probe);
|
|
3004
|
+
if (!checked.tree) return [];
|
|
3005
|
+
const scope = checked.tree.scopes.filter((s) => s.kind === "handler" && s.parent === 0).at(-1);
|
|
3006
|
+
const sites = /* @__PURE__ */ new Map();
|
|
3007
|
+
const pending = [checked.tree.root];
|
|
3008
|
+
while (pending.length) {
|
|
3009
|
+
const e = pending.pop();
|
|
3010
|
+
if (e.kind === "node") pending.push(...e.children);
|
|
3011
|
+
else if (e.kind === "name" && e.binding?.kind === "local" && e.binding.scope === scope?.id) {
|
|
3012
|
+
const site = sites.get(e.binding.id) ?? {
|
|
3013
|
+
first: Infinity,
|
|
3014
|
+
pattern: false
|
|
3015
|
+
};
|
|
3016
|
+
if (e.role === "binding") site.pattern = true;
|
|
3017
|
+
else if (e.role === "write" || e.role === "capture") site.first = Math.min(site.first, e.span.start);
|
|
3018
|
+
sites.set(e.binding.id, site);
|
|
3019
|
+
}
|
|
3020
|
+
}
|
|
3021
|
+
return (scope?.bindings ?? []).filter((b) => {
|
|
3022
|
+
const site = sites.get(b.id);
|
|
3023
|
+
return site && !site.pattern && site.first < Infinity && !this.has(b.name);
|
|
3024
|
+
}).sort((a, b) => sites.get(a.id).first - sites.get(b.id).first).map((b) => b.name);
|
|
3025
|
+
}
|
|
3026
|
+
pump() {
|
|
3027
|
+
this.recorded();
|
|
3028
|
+
const reading = this.virtual ?? this.env.now();
|
|
3029
|
+
if (this.virtual === null) this.record({
|
|
3030
|
+
k: "clock",
|
|
3031
|
+
at: reading
|
|
3032
|
+
});
|
|
3033
|
+
const now = this.lastClock !== null && reading < this.lastClock ? this.lastClock : reading;
|
|
3034
|
+
this.lastClock = now;
|
|
3035
|
+
return [...this.pumpAt(now), ...this.notifications()];
|
|
3036
|
+
}
|
|
3037
|
+
pumpAt(now) {
|
|
3038
|
+
this.events = [];
|
|
3039
|
+
this.notified = false;
|
|
3040
|
+
const result = this.group.pump(now);
|
|
3041
|
+
this.rewound = result.state === "rewound";
|
|
3042
|
+
if (this.controller?.isPaused) {
|
|
3043
|
+
this.state = { k: "paused" };
|
|
3044
|
+
return [];
|
|
3045
|
+
}
|
|
3046
|
+
return this.pumped(result);
|
|
3047
|
+
}
|
|
3048
|
+
notifications() {
|
|
3049
|
+
const out = [];
|
|
3050
|
+
while (this.notified && this.state.k !== "paused" && this.controls.queuedInputs()) out.push(...this.pumpAt(this.lastClock));
|
|
3051
|
+
return out;
|
|
3052
|
+
}
|
|
3053
|
+
notifiedPump() {
|
|
3054
|
+
return this.notified && this.group ? this.pump() : [];
|
|
3055
|
+
}
|
|
3056
|
+
pumped(result) {
|
|
3057
|
+
this.stores.router.pumped(this.group);
|
|
3058
|
+
this.deadline = result.nextDeadline;
|
|
3059
|
+
this.objectSession?.reports(result.reports);
|
|
3060
|
+
const out = this.print(result.reports);
|
|
3061
|
+
this.settleForeground();
|
|
3062
|
+
if (this.reader) {
|
|
3063
|
+
const value = this.reader;
|
|
3064
|
+
this.reader = null;
|
|
3065
|
+
out.push(...this.readProperties(value));
|
|
3066
|
+
}
|
|
3067
|
+
return out;
|
|
3068
|
+
}
|
|
3069
|
+
print(reports) {
|
|
3070
|
+
const ends = /* @__PURE__ */ new Map();
|
|
3071
|
+
for (const r of reports) if (r.kind === "run end" && r.run) ends.set(r.run, r);
|
|
3072
|
+
for (const e of this.events) if (e.k === "seg" && e.delivery) {
|
|
3073
|
+
if (this.foreground?.delivery === e.delivery) this.foreground.run = e.run;
|
|
3074
|
+
if (this.latest?.delivery === e.delivery) this.latest.run = e.run;
|
|
3075
|
+
}
|
|
3076
|
+
const out = [];
|
|
3077
|
+
const errors = /* @__PURE__ */ new Map();
|
|
3078
|
+
for (const report of reports) if (report.kind === "effect failure") out.push(this.prefix(report.run) + effectFailureText(report));
|
|
3079
|
+
else if (report.kind === "stop" && report.reason === "effect state unknown") out.push("! effect state unknown");
|
|
3080
|
+
for (const e of this.events) if (e.k === "seg") this.lastSeg.set(e.run, e);
|
|
3081
|
+
else if (e.k === "call") {
|
|
3082
|
+
const mock = this.mockCalls.get(e.call);
|
|
3083
|
+
if (mock) {
|
|
3084
|
+
this.mockCalls.delete(e.call);
|
|
3085
|
+
out.push(`${this.prefix(e.run)}call ${e.call} ${mock.operation} ${listValues(mock.args).toString()}`);
|
|
3086
|
+
}
|
|
3087
|
+
const written = this.writes.get(e.call);
|
|
3088
|
+
if (written) {
|
|
3089
|
+
this.writes.delete(e.call);
|
|
3090
|
+
out.push(...lines(textForm$1(written)).map((l) => this.prefix(e.run) + l));
|
|
3091
|
+
}
|
|
3092
|
+
const note = this.notes.get(e.call);
|
|
3093
|
+
if (note !== void 0) {
|
|
3094
|
+
this.notes.delete(e.call);
|
|
3095
|
+
out.push(...lines(note).map((l) => this.prefix(e.run) + l));
|
|
3096
|
+
}
|
|
3097
|
+
const read = this.reads.get(e.call);
|
|
3098
|
+
if (read) read.run = e.run;
|
|
3099
|
+
const prompt = this.prompts.get(e.call);
|
|
3100
|
+
if (prompt) prompt.run = e.run;
|
|
3101
|
+
} else if (e.k === "unhandled") out.push(`${e.run ? this.prefix(e.run) : ""}! unhandled ${e.message} ${listValues(e.args).toString()}`);
|
|
3102
|
+
else {
|
|
3103
|
+
this.lastSeg.delete(e.run);
|
|
3104
|
+
const line = this.ended(e, ends.get(e.run), errors);
|
|
3105
|
+
if (line !== null) out.push(...line.split("\n").map((l) => this.prefix(e.run) + l));
|
|
3106
|
+
if (e.delivery) {
|
|
3107
|
+
this.inspections.delete(e.delivery);
|
|
3108
|
+
this.expressions.delete(e.delivery);
|
|
3109
|
+
}
|
|
3110
|
+
}
|
|
3111
|
+
this.observation.observe(reports, errors);
|
|
3112
|
+
return out;
|
|
3113
|
+
}
|
|
3114
|
+
ended(e, report, errors) {
|
|
3115
|
+
switch (e.outcome) {
|
|
3116
|
+
case "completed":
|
|
3117
|
+
if (e.delivery && this.inspections.has(e.delivery)) {
|
|
3118
|
+
const value = report?.result;
|
|
3119
|
+
if (value) {
|
|
3120
|
+
if (value.kind === "object") this.reader = value;
|
|
3121
|
+
this.env.result?.(e.run, value);
|
|
3122
|
+
return valueRows(value).join("\n");
|
|
3123
|
+
}
|
|
3124
|
+
}
|
|
3125
|
+
if (e.delivery && this.expressions.has(e.delivery)) {
|
|
3126
|
+
const value = report?.result ?? nothing;
|
|
3127
|
+
this.env.result?.(e.run, value);
|
|
3128
|
+
return value.toString();
|
|
3129
|
+
}
|
|
3130
|
+
return null;
|
|
3131
|
+
case "errored": {
|
|
3132
|
+
const error = map(e.error.entries().filter(([k]) => k !== "message" && k !== "at"));
|
|
3133
|
+
errors.set(e.run, error.toString());
|
|
3134
|
+
return `! error ${error.toString()} at ${this.where(report?.at)}`;
|
|
3135
|
+
}
|
|
3136
|
+
case "limit-fault": return `! limit fault ${report?.limit} at ${this.where(report?.at)}`;
|
|
3137
|
+
case "cancelled": return "! cancelled";
|
|
3138
|
+
case "effect-failed": return "! effect failed";
|
|
3139
|
+
default: return null;
|
|
3140
|
+
}
|
|
3141
|
+
}
|
|
3142
|
+
where(at) {
|
|
3143
|
+
if (!at) return "?";
|
|
3144
|
+
const placement = this.placements.get(at.unit);
|
|
3145
|
+
return placement ? where(at, placement, Infinity) : `${at.unit}:${at.line}:${at.col}`;
|
|
3146
|
+
}
|
|
3147
|
+
prefix(run) {
|
|
3148
|
+
return this.foreground?.run === run ? "" : `[${run}] `;
|
|
3149
|
+
}
|
|
3150
|
+
settleForeground() {
|
|
3151
|
+
const run = this.foreground?.run;
|
|
3152
|
+
if (!run || !this.lastSeg.has(run)) {
|
|
3153
|
+
this.foreground = null;
|
|
3154
|
+
this.state = { k: "prompt" };
|
|
3155
|
+
return;
|
|
3156
|
+
}
|
|
3157
|
+
if ([...this.reads.values()].some((r) => r.run === run)) {
|
|
3158
|
+
this.state = { k: "read" };
|
|
3159
|
+
return;
|
|
3160
|
+
}
|
|
3161
|
+
const prompt = [...this.prompts].find(([, p]) => p.run === run);
|
|
3162
|
+
if (prompt) {
|
|
3163
|
+
this.state = {
|
|
3164
|
+
k: "user",
|
|
3165
|
+
call: prompt[0],
|
|
3166
|
+
prompt: prompt[1].prompt
|
|
3167
|
+
};
|
|
3168
|
+
return;
|
|
3169
|
+
}
|
|
3170
|
+
const seg = this.lastSeg.get(run);
|
|
3171
|
+
if (this.virtual === null && [
|
|
3172
|
+
"wait",
|
|
3173
|
+
"wait-for",
|
|
3174
|
+
"wait-for-any"
|
|
3175
|
+
].includes(seg.end) && seg.calls.length === 0 && seg.until !== void 0) {
|
|
3176
|
+
this.state = {
|
|
3177
|
+
k: "deadline",
|
|
3178
|
+
at: seg.until
|
|
3179
|
+
};
|
|
3180
|
+
return;
|
|
3181
|
+
}
|
|
3182
|
+
this.foreground = null;
|
|
3183
|
+
this.state = { k: "prompt" };
|
|
3184
|
+
}
|
|
3185
|
+
};
|
|
3186
|
+
const docsOf = (found) => found.map(({ origin, declaration, clause, doc }) => ({
|
|
3187
|
+
origin,
|
|
3188
|
+
declaration,
|
|
3189
|
+
clause,
|
|
3190
|
+
doc
|
|
3191
|
+
}));
|
|
3192
|
+
const documentable = (entry, kind) => {
|
|
3193
|
+
const doc = leadingDoc(entry);
|
|
3194
|
+
if (doc === "pending") return false;
|
|
3195
|
+
if (doc === "attached") return kind === "declaration" && !entry.children.some((c) => c.kind === "node" && c.rule === "Declaration" && c.children.some((u) => u.kind === "node" && u.rule === "Use"));
|
|
3196
|
+
return true;
|
|
3197
|
+
};
|
|
3198
|
+
const describe = (source) => {
|
|
3199
|
+
const checked = checkSource(source);
|
|
3200
|
+
const decl = viewSource(checked.tree.root)[0];
|
|
3201
|
+
if (decl.k === "use") {
|
|
3202
|
+
const uses = decl.imports.map((i) => ({
|
|
3203
|
+
local: i.local.text,
|
|
3204
|
+
name: i.name
|
|
3205
|
+
}));
|
|
3206
|
+
return {
|
|
3207
|
+
kind: "use",
|
|
3208
|
+
library: decl.library,
|
|
3209
|
+
names: uses.map((u) => u.local),
|
|
3210
|
+
uses,
|
|
3211
|
+
source
|
|
3212
|
+
};
|
|
3213
|
+
}
|
|
3214
|
+
if (decl.k === "handler" || decl.k === "function") return {
|
|
3215
|
+
kind: decl.k,
|
|
3216
|
+
names: [decl.name],
|
|
3217
|
+
source
|
|
3218
|
+
};
|
|
3219
|
+
return {
|
|
3220
|
+
kind: decl.k,
|
|
3221
|
+
names: [decl.name.text],
|
|
3222
|
+
source
|
|
3223
|
+
};
|
|
3224
|
+
};
|
|
3225
|
+
const fixDeclarations = (source, tree) => {
|
|
3226
|
+
const all = source.split("\n");
|
|
3227
|
+
let from = 0;
|
|
3228
|
+
return nodes(tree).filter((n) => n.rule === "Declaration").map((n) => {
|
|
3229
|
+
const last = source.slice(0, n.end).trimEnd().split("\n").length - 1;
|
|
3230
|
+
let first = from;
|
|
3231
|
+
while (first < last && /^[ \t\r]*$/u.test(all[first])) first++;
|
|
3232
|
+
from = last + 1;
|
|
3233
|
+
return describe(all.slice(first, last + 1).join("\n"));
|
|
3234
|
+
});
|
|
3235
|
+
};
|
|
3236
|
+
const placed = (declarations, decl) => {
|
|
3237
|
+
const next = [];
|
|
3238
|
+
let done = false;
|
|
3239
|
+
for (const d of declarations) {
|
|
3240
|
+
const reused = d.names.filter((n) => decl.names.includes(n));
|
|
3241
|
+
if (!reused.length) next.push(d);
|
|
3242
|
+
else if (d.kind === "use") {
|
|
3243
|
+
const left = d.uses.filter((u) => !reused.includes(u.local));
|
|
3244
|
+
if (left.length) next.push(usesDeclaration(d.library, left));
|
|
3245
|
+
} else if (!done && decl.kind !== "use") {
|
|
3246
|
+
next.push(decl);
|
|
3247
|
+
done = true;
|
|
3248
|
+
}
|
|
3249
|
+
}
|
|
3250
|
+
if (!done) next.push(decl);
|
|
3251
|
+
return next;
|
|
3252
|
+
};
|
|
3253
|
+
const usesDeclaration = (library, uses) => ({
|
|
3254
|
+
kind: "use",
|
|
3255
|
+
library,
|
|
3256
|
+
names: uses.map((u) => u.local),
|
|
3257
|
+
uses,
|
|
3258
|
+
source: uses.length === 1 && uses[0].local !== uses[0].name ? `use ${uses[0].name} from ${library} as ${uses[0].local}` : `use ${uses.map((u) => u.name).join(", ")} from ${library}`
|
|
3259
|
+
});
|
|
3260
|
+
const where = (at, placement, length) => {
|
|
3261
|
+
const line = at.line - placement.line;
|
|
3262
|
+
if (line < 1 || line > length) return `${at.unit}:${at.line}:${at.col}`;
|
|
3263
|
+
return `${line}:${line === 1 ? Math.max(1, at.col - placement.col) : at.col}`;
|
|
3264
|
+
};
|
|
3265
|
+
const words = (rest, n) => {
|
|
3266
|
+
const w = rest.trim().split(/\s+/u).filter(Boolean);
|
|
3267
|
+
return w.length === n ? w : refuse("bad arguments");
|
|
3268
|
+
};
|
|
3269
|
+
const split = (rest) => {
|
|
3270
|
+
const m = /^(\S+)\s*(.*)$/su.exec(rest.trim());
|
|
3271
|
+
return m ? [m[1], m[2]] : ["", ""];
|
|
3272
|
+
};
|
|
3273
|
+
const display = (source) => {
|
|
3274
|
+
try {
|
|
3275
|
+
return readDisplay(source);
|
|
3276
|
+
} catch {
|
|
3277
|
+
return refuse("bad arguments");
|
|
3278
|
+
}
|
|
3279
|
+
};
|
|
3280
|
+
const errorMap = (source) => {
|
|
3281
|
+
const error = display(source);
|
|
3282
|
+
if (error.kind !== "map" || error.get("code").kind !== "text") refuse("bad arguments");
|
|
3283
|
+
return error;
|
|
3284
|
+
};
|
|
3285
|
+
//#endregion
|
|
3286
|
+
//#region src/session/transcript.ts
|
|
3287
|
+
const MARKS = /* @__PURE__ */ new Set([
|
|
3288
|
+
">",
|
|
3289
|
+
"|",
|
|
3290
|
+
"<",
|
|
3291
|
+
"@",
|
|
3292
|
+
"~",
|
|
3293
|
+
"%",
|
|
3294
|
+
"#",
|
|
3295
|
+
"'"
|
|
3296
|
+
]);
|
|
3297
|
+
/** Read a Transcript's lines (chapter 12). */
|
|
3298
|
+
const parseTranscript = (source) => {
|
|
3299
|
+
const lines = source.split("\n");
|
|
3300
|
+
if (lines.at(-1) === "") lines.pop();
|
|
3301
|
+
const items = [];
|
|
3302
|
+
for (const [i, line] of lines.entries()) {
|
|
3303
|
+
const fail = (what) => {
|
|
3304
|
+
throw new Error(`Transcript line ${i + 1}: ${what}`);
|
|
3305
|
+
};
|
|
3306
|
+
const rest = (mark) => line === mark ? "" : line.startsWith(`${mark} `) ? line.slice(2) : null;
|
|
3307
|
+
const mark = line[0] ?? "";
|
|
3308
|
+
if (mark === ">") {
|
|
3309
|
+
const source = rest(">");
|
|
3310
|
+
if (!source) fail("an Entry or Session Command after `> `");
|
|
3311
|
+
items.push({
|
|
3312
|
+
k: "input",
|
|
3313
|
+
source
|
|
3314
|
+
});
|
|
3315
|
+
} else if (mark === "|") {
|
|
3316
|
+
const last = items.at(-1);
|
|
3317
|
+
const more = rest("|");
|
|
3318
|
+
if (last?.k !== "input" || more === null) fail("a `|` line continues the line before it");
|
|
3319
|
+
last.source += `\n${more}`;
|
|
3320
|
+
} else if (mark === "<") {
|
|
3321
|
+
const typed = rest("<");
|
|
3322
|
+
if (typed === null) fail("a typed line after `< `");
|
|
3323
|
+
items.push({
|
|
3324
|
+
k: "read",
|
|
3325
|
+
line: typed
|
|
3326
|
+
});
|
|
3327
|
+
} else if (mark === "@") {
|
|
3328
|
+
const at = rest("@");
|
|
3329
|
+
if (!at) fail("an instant after `@ `");
|
|
3330
|
+
items.push({
|
|
3331
|
+
k: "clock",
|
|
3332
|
+
at: parseInstant(at)
|
|
3333
|
+
});
|
|
3334
|
+
} else if (mark === "~") {
|
|
3335
|
+
const answer = rest("~");
|
|
3336
|
+
const space = answer?.indexOf(" ") ?? -1;
|
|
3337
|
+
if (!answer || space < 1) fail("a call and its answer after `~ `");
|
|
3338
|
+
items.push({
|
|
3339
|
+
k: "answer",
|
|
3340
|
+
call: answer.slice(0, space),
|
|
3341
|
+
answer: answer.slice(space + 1)
|
|
3342
|
+
});
|
|
3343
|
+
} else if (mark === "%") {
|
|
3344
|
+
const json = rest("%");
|
|
3345
|
+
if (!json) fail("an envelope after `% `");
|
|
3346
|
+
parseEnvelope(json);
|
|
3347
|
+
items.push({
|
|
3348
|
+
k: "envelope",
|
|
3349
|
+
json
|
|
3350
|
+
});
|
|
3351
|
+
} else if (mark === "#") items.push({
|
|
3352
|
+
k: "comment",
|
|
3353
|
+
text: line
|
|
3354
|
+
});
|
|
3355
|
+
else if (mark === "'") items.push({
|
|
3356
|
+
k: "output",
|
|
3357
|
+
text: line.slice(1)
|
|
3358
|
+
});
|
|
3359
|
+
else if (line === "") fail("an empty output line is written as `'`");
|
|
3360
|
+
else items.push({
|
|
3361
|
+
k: "output",
|
|
3362
|
+
text: line
|
|
3363
|
+
});
|
|
3364
|
+
}
|
|
3365
|
+
return items;
|
|
3366
|
+
};
|
|
3367
|
+
/** Write a Transcript's lines, each ended by an LF. */
|
|
3368
|
+
const writeTranscript = (items) => items.flatMap((item) => {
|
|
3369
|
+
switch (item.k) {
|
|
3370
|
+
case "input": {
|
|
3371
|
+
const [first, ...more] = item.source.split("\n");
|
|
3372
|
+
return [`> ${first}`, ...more.map((l) => l ? `| ${l}` : "|")];
|
|
3373
|
+
}
|
|
3374
|
+
case "read": return [item.line ? `< ${item.line}` : "<"];
|
|
3375
|
+
case "clock": return [`@ ${formatInstant(item.at)}`];
|
|
3376
|
+
case "answer": return [`~ ${item.call} ${item.answer}`];
|
|
3377
|
+
case "envelope":
|
|
3378
|
+
parseEnvelope(item.json);
|
|
3379
|
+
return [`% ${item.json}`];
|
|
3380
|
+
case "comment": return [item.text];
|
|
3381
|
+
case "output": return [item.text === "" || MARKS.has(item.text[0]) ? `'${item.text}` : item.text];
|
|
3382
|
+
}
|
|
3383
|
+
}).map((line) => `${line}\n`).join("");
|
|
3384
|
+
/**
|
|
3385
|
+
* Replay a Transcript through a fresh Session Host (chapter 12, Replaying):
|
|
3386
|
+
* each `@` reading is that Pump's Clock reading, each `<` line answers
|
|
3387
|
+
* `read`, and each `~` line answers its call, a `user` prompt's included. The result has the lines it printed in place of the recorded ones.
|
|
3388
|
+
*/
|
|
3389
|
+
const replayTranscript = (recorded, options = {}) => {
|
|
3390
|
+
const items = [];
|
|
3391
|
+
const answers = /* @__PURE__ */ new Map();
|
|
3392
|
+
for (const item of recorded) if (item.k === "answer") answers.set(item.call, [...answers.get(item.call) ?? [], item.answer]);
|
|
3393
|
+
const answer = (call) => {
|
|
3394
|
+
const recorded = answers.get(call.id)?.shift();
|
|
3395
|
+
if (recorded === void 0) throw new Error(`The Transcript has no \`~\` answer for ${call.id}`);
|
|
3396
|
+
if (!recorded.startsWith("fail ")) return readDisplay(recorded);
|
|
3397
|
+
const error = readDisplay(recorded.slice(5));
|
|
3398
|
+
if (!error.entries().length) throw new Error(`${call.id} fails with an error that isn't a Script error`);
|
|
3399
|
+
throw hostFailure(error);
|
|
3400
|
+
};
|
|
3401
|
+
let live = false;
|
|
3402
|
+
const builtIn = (operations, impl) => Object.fromEntries(operations.map((op) => [op, (call, ...args) => {
|
|
3403
|
+
if (!live) return answer(call);
|
|
3404
|
+
const host = impl?.[op];
|
|
3405
|
+
if (!host) throw new Error(`No live built-in answers ${op}`);
|
|
3406
|
+
return host.call(impl, call, ...args);
|
|
3407
|
+
}]));
|
|
3408
|
+
let clock = null;
|
|
3409
|
+
const host = new SessionHost({
|
|
3410
|
+
objectTranscript: recorded,
|
|
3411
|
+
...options.capabilities ?? options.live?.capabilities ? { capabilities: options.capabilities ?? options.live?.capabilities } : {},
|
|
3412
|
+
now: () => {
|
|
3413
|
+
if (live) return options.live.now();
|
|
3414
|
+
return clock();
|
|
3415
|
+
},
|
|
3416
|
+
record: (item) => {
|
|
3417
|
+
items.push(item);
|
|
3418
|
+
if (live) options.live.record?.(item);
|
|
3419
|
+
},
|
|
3420
|
+
result: (run, value) => {
|
|
3421
|
+
if (live) options.live.result?.(run, value);
|
|
3422
|
+
},
|
|
3423
|
+
transcriptEnds: (dropped) => options.live?.transcriptEnds?.(dropped),
|
|
3424
|
+
builtIns: {
|
|
3425
|
+
calendar: builtIn([
|
|
3426
|
+
"today",
|
|
3427
|
+
"now",
|
|
3428
|
+
"toCivil",
|
|
3429
|
+
"toInstant",
|
|
3430
|
+
"offset",
|
|
3431
|
+
"zone"
|
|
3432
|
+
], options.live?.builtIns?.calendar),
|
|
3433
|
+
locale: builtIn([
|
|
3434
|
+
"compare",
|
|
3435
|
+
"rank",
|
|
3436
|
+
"upper",
|
|
3437
|
+
"lower",
|
|
3438
|
+
"numberSymbols",
|
|
3439
|
+
"monthNames",
|
|
3440
|
+
"dayNames",
|
|
3441
|
+
"tag"
|
|
3442
|
+
], options.live?.builtIns?.locale)
|
|
3443
|
+
},
|
|
3444
|
+
...options.trace ? { trace: options.trace } : {},
|
|
3445
|
+
writeFile: () => {},
|
|
3446
|
+
writeStoreFile: () => {}
|
|
3447
|
+
});
|
|
3448
|
+
const consumed = /* @__PURE__ */ new Set();
|
|
3449
|
+
let readings = [];
|
|
3450
|
+
let clockStart = 0;
|
|
3451
|
+
const prepare = (i) => {
|
|
3452
|
+
clockStart = i + 1;
|
|
3453
|
+
readings = [];
|
|
3454
|
+
for (let n = i + 1; n < recorded.length; n++) {
|
|
3455
|
+
const item = recorded[n];
|
|
3456
|
+
if (item.k === "input" || item.k === "read") break;
|
|
3457
|
+
if (item.k === "clock") readings.push({
|
|
3458
|
+
index: n,
|
|
3459
|
+
at: item.at
|
|
3460
|
+
});
|
|
3461
|
+
}
|
|
3462
|
+
};
|
|
3463
|
+
clock = () => {
|
|
3464
|
+
const next = readings.shift();
|
|
3465
|
+
if (!next) throw new Error("The Transcript has no `@` reading for a Pump");
|
|
3466
|
+
for (let n = clockStart; n < next.index; n++) {
|
|
3467
|
+
const item = recorded[n];
|
|
3468
|
+
if (item.k === "envelope") host.replayObjectItem(item);
|
|
3469
|
+
}
|
|
3470
|
+
clockStart = next.index + 1;
|
|
3471
|
+
consumed.add(next.index);
|
|
3472
|
+
return next.at;
|
|
3473
|
+
};
|
|
3474
|
+
for (let i = 0; i < recorded.length; i++) {
|
|
3475
|
+
if (consumed.has(i)) continue;
|
|
3476
|
+
const item = recorded[i];
|
|
3477
|
+
switch (item.k) {
|
|
3478
|
+
case "input":
|
|
3479
|
+
prepare(i);
|
|
3480
|
+
host.input(item.source);
|
|
3481
|
+
break;
|
|
3482
|
+
case "read":
|
|
3483
|
+
prepare(i);
|
|
3484
|
+
host.read(item.line);
|
|
3485
|
+
break;
|
|
3486
|
+
case "clock":
|
|
3487
|
+
prepare(i - 1);
|
|
3488
|
+
host.tick();
|
|
3489
|
+
break;
|
|
3490
|
+
case "envelope":
|
|
3491
|
+
host.replayObjectItem(item);
|
|
3492
|
+
break;
|
|
3493
|
+
case "comment":
|
|
3494
|
+
items.push(item);
|
|
3495
|
+
break;
|
|
3496
|
+
case "answer": if (host.waiting.k === "user" && host.waiting.call === item.call) {
|
|
3497
|
+
prepare(i);
|
|
3498
|
+
host.answerPrompt(readDisplay(item.answer));
|
|
3499
|
+
}
|
|
3500
|
+
}
|
|
3501
|
+
}
|
|
3502
|
+
host.finishObjectReplay();
|
|
3503
|
+
live = options.live !== void 0;
|
|
3504
|
+
return {
|
|
3505
|
+
host,
|
|
3506
|
+
items
|
|
3507
|
+
};
|
|
3508
|
+
};
|
|
3509
|
+
//#endregion
|
|
3510
|
+
export { MOCK_ARGUMENTS, SessionHost, SessionObjects, builtinDocs, parseEnvelope, parseTranscript, replayTranscript, writeTranscript };
|