@grwnd/pi-governance 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,8 +1,16 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __commonJS = (cb, mod) => function __require() {
12
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
+ };
6
14
  var __export = (target, all) => {
7
15
  for (var name in all)
8
16
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -13,15 +21,3760 @@ var __copyProps = (to, from, except, desc) => {
13
21
  if (!__hasOwnProp.call(to, key) && key !== except)
14
22
  __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
23
  }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
24
+ return to;
25
+ };
26
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
+ // If the importer is in node compatibility mode or this is not an ESM
28
+ // file that has been converted to a CommonJS file using a Babel-
29
+ // compatible transform (i.e. "__esModule" has not been set), then set
30
+ // "default" to the CommonJS "module.exports" for node compatibility.
31
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
+ mod
33
+ ));
34
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
35
+
36
+ // node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/types.js
37
+ var require_types = __commonJS({
38
+ "node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/types.js"(exports2) {
39
+ "use strict";
40
+ Object.defineProperty(exports2, "__esModule", { value: true });
41
+ exports2.UserType = exports2.Dict = exports2.isAsyncIterable = exports2.isIterable = exports2.isIterableIterator = exports2.QueryEventKind = exports2.isPolarTerm = exports2.isPolarPattern = exports2.isPolarExpression = exports2.isPolarInstance = exports2.isPolarVariable = exports2.isPolarPredicate = exports2.isPolarDict = exports2.isPolarList = exports2.isPolarBool = exports2.isPolarNum = exports2.isPolarComparisonOperator = exports2.isPolarStr = void 0;
42
+ var helpers_1 = require_helpers();
43
+ function isPolarStr(v) {
44
+ return v.String !== void 0;
45
+ }
46
+ exports2.isPolarStr = isPolarStr;
47
+ function isPolarComparisonOperator(s) {
48
+ return s in comparisonOperators;
49
+ }
50
+ exports2.isPolarComparisonOperator = isPolarComparisonOperator;
51
+ function isPolarNum(v) {
52
+ return v.Number !== void 0;
53
+ }
54
+ exports2.isPolarNum = isPolarNum;
55
+ function isPolarBool(v) {
56
+ return v.Boolean !== void 0;
57
+ }
58
+ exports2.isPolarBool = isPolarBool;
59
+ function isPolarList(v) {
60
+ return v.List !== void 0;
61
+ }
62
+ exports2.isPolarList = isPolarList;
63
+ function isPolarDict(v) {
64
+ return v.Dictionary !== void 0;
65
+ }
66
+ exports2.isPolarDict = isPolarDict;
67
+ function isPolarPredicate(v) {
68
+ return v.Call !== void 0;
69
+ }
70
+ exports2.isPolarPredicate = isPolarPredicate;
71
+ function isPolarVariable(v) {
72
+ return v.Variable !== void 0;
73
+ }
74
+ exports2.isPolarVariable = isPolarVariable;
75
+ function isPolarInstance(v) {
76
+ return v.ExternalInstance !== void 0;
77
+ }
78
+ exports2.isPolarInstance = isPolarInstance;
79
+ function isPolarExpression(v) {
80
+ return v.Expression !== void 0;
81
+ }
82
+ exports2.isPolarExpression = isPolarExpression;
83
+ function isPolarPattern(v) {
84
+ return v.Pattern !== void 0;
85
+ }
86
+ exports2.isPolarPattern = isPolarPattern;
87
+ function isPolarValue(x) {
88
+ if (!helpers_1.isObj(x))
89
+ return false;
90
+ const v = x;
91
+ return isPolarStr(v) || isPolarNum(v) || isPolarBool(v) || isPolarList(v) || isPolarDict(v) || isPolarPredicate(v) || isPolarVariable(v) || isPolarInstance(v) || isPolarExpression(v) || isPolarPattern(v);
92
+ }
93
+ function isPolarTerm(v) {
94
+ if (!helpers_1.isObj(v))
95
+ return false;
96
+ return isPolarValue(v.value);
97
+ }
98
+ exports2.isPolarTerm = isPolarTerm;
99
+ var comparisonOperators = {
100
+ Eq: "Eq",
101
+ Geq: "Geq",
102
+ Gt: "Gt",
103
+ Leq: "Leq",
104
+ Lt: "Lt",
105
+ Neq: "Neq"
106
+ };
107
+ var operators = {
108
+ Add: "Add",
109
+ And: "And",
110
+ Assign: "Assign",
111
+ Cut: "Cut",
112
+ Debug: "Debug",
113
+ Div: "Div",
114
+ Dot: "Dot",
115
+ ForAll: "ForAll",
116
+ In: "In",
117
+ Isa: "Isa",
118
+ Mod: "Mod",
119
+ Mul: "Mul",
120
+ New: "New",
121
+ Not: "Not",
122
+ Or: "Or",
123
+ Print: "Print",
124
+ Rem: "Rem",
125
+ Sub: "Sub",
126
+ Unify: "Unify",
127
+ ...comparisonOperators
128
+ };
129
+ var QueryEventKind;
130
+ (function(QueryEventKind2) {
131
+ QueryEventKind2[QueryEventKind2["Debug"] = 0] = "Debug";
132
+ QueryEventKind2[QueryEventKind2["Done"] = 1] = "Done";
133
+ QueryEventKind2[QueryEventKind2["ExternalCall"] = 2] = "ExternalCall";
134
+ QueryEventKind2[QueryEventKind2["ExternalIsa"] = 3] = "ExternalIsa";
135
+ QueryEventKind2[QueryEventKind2["ExternalIsaWithPath"] = 4] = "ExternalIsaWithPath";
136
+ QueryEventKind2[QueryEventKind2["ExternalIsSubspecializer"] = 5] = "ExternalIsSubspecializer";
137
+ QueryEventKind2[QueryEventKind2["ExternalIsSubclass"] = 6] = "ExternalIsSubclass";
138
+ QueryEventKind2[QueryEventKind2["ExternalOp"] = 7] = "ExternalOp";
139
+ QueryEventKind2[QueryEventKind2["MakeExternal"] = 8] = "MakeExternal";
140
+ QueryEventKind2[QueryEventKind2["NextExternal"] = 9] = "NextExternal";
141
+ QueryEventKind2[QueryEventKind2["Result"] = 10] = "Result";
142
+ })(QueryEventKind = exports2.QueryEventKind || (exports2.QueryEventKind = {}));
143
+ function isIterableIterator(x) {
144
+ return typeof (x === null || x === void 0 ? void 0 : x.next) === "function" && isIterable(x);
145
+ }
146
+ exports2.isIterableIterator = isIterableIterator;
147
+ function isIterable(x) {
148
+ try {
149
+ return Symbol.iterator in x;
150
+ } catch (e) {
151
+ if (e instanceof TypeError)
152
+ return false;
153
+ throw e;
154
+ }
155
+ }
156
+ exports2.isIterable = isIterable;
157
+ function isAsyncIterable(x) {
158
+ try {
159
+ return Symbol.asyncIterator in x;
160
+ } catch (e) {
161
+ if (e instanceof TypeError)
162
+ return false;
163
+ throw e;
164
+ }
165
+ }
166
+ exports2.isAsyncIterable = isAsyncIterable;
167
+ var Dict = class extends Object {
168
+ // eslint-disable-next-line @typescript-eslint/ban-types
169
+ constructor(obj) {
170
+ super();
171
+ if (obj) {
172
+ Object.assign(this, obj);
173
+ }
174
+ }
175
+ };
176
+ exports2.Dict = Dict;
177
+ var UserType = class {
178
+ constructor({ name, cls, id, fields, isaCheck }) {
179
+ this.name = name;
180
+ this.cls = cls;
181
+ this.fields = fields;
182
+ this.id = id;
183
+ this.isaCheck = isaCheck;
184
+ }
185
+ };
186
+ exports2.UserType = UserType;
187
+ }
188
+ });
189
+
190
+ // node_modules/.pnpm/lodash.isequal@4.5.0/node_modules/lodash.isequal/index.js
191
+ var require_lodash = __commonJS({
192
+ "node_modules/.pnpm/lodash.isequal@4.5.0/node_modules/lodash.isequal/index.js"(exports2, module2) {
193
+ "use strict";
194
+ var LARGE_ARRAY_SIZE = 200;
195
+ var HASH_UNDEFINED = "__lodash_hash_undefined__";
196
+ var COMPARE_PARTIAL_FLAG = 1;
197
+ var COMPARE_UNORDERED_FLAG = 2;
198
+ var MAX_SAFE_INTEGER = 9007199254740991;
199
+ var argsTag = "[object Arguments]";
200
+ var arrayTag = "[object Array]";
201
+ var asyncTag = "[object AsyncFunction]";
202
+ var boolTag = "[object Boolean]";
203
+ var dateTag = "[object Date]";
204
+ var errorTag = "[object Error]";
205
+ var funcTag = "[object Function]";
206
+ var genTag = "[object GeneratorFunction]";
207
+ var mapTag = "[object Map]";
208
+ var numberTag = "[object Number]";
209
+ var nullTag = "[object Null]";
210
+ var objectTag = "[object Object]";
211
+ var promiseTag = "[object Promise]";
212
+ var proxyTag = "[object Proxy]";
213
+ var regexpTag = "[object RegExp]";
214
+ var setTag = "[object Set]";
215
+ var stringTag = "[object String]";
216
+ var symbolTag = "[object Symbol]";
217
+ var undefinedTag = "[object Undefined]";
218
+ var weakMapTag = "[object WeakMap]";
219
+ var arrayBufferTag = "[object ArrayBuffer]";
220
+ var dataViewTag = "[object DataView]";
221
+ var float32Tag = "[object Float32Array]";
222
+ var float64Tag = "[object Float64Array]";
223
+ var int8Tag = "[object Int8Array]";
224
+ var int16Tag = "[object Int16Array]";
225
+ var int32Tag = "[object Int32Array]";
226
+ var uint8Tag = "[object Uint8Array]";
227
+ var uint8ClampedTag = "[object Uint8ClampedArray]";
228
+ var uint16Tag = "[object Uint16Array]";
229
+ var uint32Tag = "[object Uint32Array]";
230
+ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
231
+ var reIsHostCtor = /^\[object .+?Constructor\]$/;
232
+ var reIsUint = /^(?:0|[1-9]\d*)$/;
233
+ var typedArrayTags = {};
234
+ typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
235
+ typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
236
+ var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
237
+ var freeSelf = typeof self == "object" && self && self.Object === Object && self;
238
+ var root = freeGlobal || freeSelf || Function("return this")();
239
+ var freeExports = typeof exports2 == "object" && exports2 && !exports2.nodeType && exports2;
240
+ var freeModule = freeExports && typeof module2 == "object" && module2 && !module2.nodeType && module2;
241
+ var moduleExports = freeModule && freeModule.exports === freeExports;
242
+ var freeProcess = moduleExports && freeGlobal.process;
243
+ var nodeUtil = (function() {
244
+ try {
245
+ return freeProcess && freeProcess.binding && freeProcess.binding("util");
246
+ } catch (e) {
247
+ }
248
+ })();
249
+ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
250
+ function arrayFilter(array, predicate) {
251
+ var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = [];
252
+ while (++index < length) {
253
+ var value = array[index];
254
+ if (predicate(value, index, array)) {
255
+ result[resIndex++] = value;
256
+ }
257
+ }
258
+ return result;
259
+ }
260
+ function arrayPush(array, values) {
261
+ var index = -1, length = values.length, offset = array.length;
262
+ while (++index < length) {
263
+ array[offset + index] = values[index];
264
+ }
265
+ return array;
266
+ }
267
+ function arraySome(array, predicate) {
268
+ var index = -1, length = array == null ? 0 : array.length;
269
+ while (++index < length) {
270
+ if (predicate(array[index], index, array)) {
271
+ return true;
272
+ }
273
+ }
274
+ return false;
275
+ }
276
+ function baseTimes(n, iteratee) {
277
+ var index = -1, result = Array(n);
278
+ while (++index < n) {
279
+ result[index] = iteratee(index);
280
+ }
281
+ return result;
282
+ }
283
+ function baseUnary(func) {
284
+ return function(value) {
285
+ return func(value);
286
+ };
287
+ }
288
+ function cacheHas(cache, key) {
289
+ return cache.has(key);
290
+ }
291
+ function getValue(object, key) {
292
+ return object == null ? void 0 : object[key];
293
+ }
294
+ function mapToArray(map) {
295
+ var index = -1, result = Array(map.size);
296
+ map.forEach(function(value, key) {
297
+ result[++index] = [key, value];
298
+ });
299
+ return result;
300
+ }
301
+ function overArg(func, transform) {
302
+ return function(arg) {
303
+ return func(transform(arg));
304
+ };
305
+ }
306
+ function setToArray(set) {
307
+ var index = -1, result = Array(set.size);
308
+ set.forEach(function(value) {
309
+ result[++index] = value;
310
+ });
311
+ return result;
312
+ }
313
+ var arrayProto = Array.prototype;
314
+ var funcProto = Function.prototype;
315
+ var objectProto = Object.prototype;
316
+ var coreJsData = root["__core-js_shared__"];
317
+ var funcToString = funcProto.toString;
318
+ var hasOwnProperty = objectProto.hasOwnProperty;
319
+ var maskSrcKey = (function() {
320
+ var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || "");
321
+ return uid ? "Symbol(src)_1." + uid : "";
322
+ })();
323
+ var nativeObjectToString = objectProto.toString;
324
+ var reIsNative = RegExp(
325
+ "^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"
326
+ );
327
+ var Buffer2 = moduleExports ? root.Buffer : void 0;
328
+ var Symbol2 = root.Symbol;
329
+ var Uint8Array2 = root.Uint8Array;
330
+ var propertyIsEnumerable = objectProto.propertyIsEnumerable;
331
+ var splice = arrayProto.splice;
332
+ var symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0;
333
+ var nativeGetSymbols = Object.getOwnPropertySymbols;
334
+ var nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0;
335
+ var nativeKeys = overArg(Object.keys, Object);
336
+ var DataView = getNative(root, "DataView");
337
+ var Map2 = getNative(root, "Map");
338
+ var Promise2 = getNative(root, "Promise");
339
+ var Set2 = getNative(root, "Set");
340
+ var WeakMap2 = getNative(root, "WeakMap");
341
+ var nativeCreate = getNative(Object, "create");
342
+ var dataViewCtorString = toSource(DataView);
343
+ var mapCtorString = toSource(Map2);
344
+ var promiseCtorString = toSource(Promise2);
345
+ var setCtorString = toSource(Set2);
346
+ var weakMapCtorString = toSource(WeakMap2);
347
+ var symbolProto = Symbol2 ? Symbol2.prototype : void 0;
348
+ var symbolValueOf = symbolProto ? symbolProto.valueOf : void 0;
349
+ function Hash(entries) {
350
+ var index = -1, length = entries == null ? 0 : entries.length;
351
+ this.clear();
352
+ while (++index < length) {
353
+ var entry = entries[index];
354
+ this.set(entry[0], entry[1]);
355
+ }
356
+ }
357
+ function hashClear() {
358
+ this.__data__ = nativeCreate ? nativeCreate(null) : {};
359
+ this.size = 0;
360
+ }
361
+ function hashDelete(key) {
362
+ var result = this.has(key) && delete this.__data__[key];
363
+ this.size -= result ? 1 : 0;
364
+ return result;
365
+ }
366
+ function hashGet(key) {
367
+ var data = this.__data__;
368
+ if (nativeCreate) {
369
+ var result = data[key];
370
+ return result === HASH_UNDEFINED ? void 0 : result;
371
+ }
372
+ return hasOwnProperty.call(data, key) ? data[key] : void 0;
373
+ }
374
+ function hashHas(key) {
375
+ var data = this.__data__;
376
+ return nativeCreate ? data[key] !== void 0 : hasOwnProperty.call(data, key);
377
+ }
378
+ function hashSet(key, value) {
379
+ var data = this.__data__;
380
+ this.size += this.has(key) ? 0 : 1;
381
+ data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value;
382
+ return this;
383
+ }
384
+ Hash.prototype.clear = hashClear;
385
+ Hash.prototype["delete"] = hashDelete;
386
+ Hash.prototype.get = hashGet;
387
+ Hash.prototype.has = hashHas;
388
+ Hash.prototype.set = hashSet;
389
+ function ListCache(entries) {
390
+ var index = -1, length = entries == null ? 0 : entries.length;
391
+ this.clear();
392
+ while (++index < length) {
393
+ var entry = entries[index];
394
+ this.set(entry[0], entry[1]);
395
+ }
396
+ }
397
+ function listCacheClear() {
398
+ this.__data__ = [];
399
+ this.size = 0;
400
+ }
401
+ function listCacheDelete(key) {
402
+ var data = this.__data__, index = assocIndexOf(data, key);
403
+ if (index < 0) {
404
+ return false;
405
+ }
406
+ var lastIndex = data.length - 1;
407
+ if (index == lastIndex) {
408
+ data.pop();
409
+ } else {
410
+ splice.call(data, index, 1);
411
+ }
412
+ --this.size;
413
+ return true;
414
+ }
415
+ function listCacheGet(key) {
416
+ var data = this.__data__, index = assocIndexOf(data, key);
417
+ return index < 0 ? void 0 : data[index][1];
418
+ }
419
+ function listCacheHas(key) {
420
+ return assocIndexOf(this.__data__, key) > -1;
421
+ }
422
+ function listCacheSet(key, value) {
423
+ var data = this.__data__, index = assocIndexOf(data, key);
424
+ if (index < 0) {
425
+ ++this.size;
426
+ data.push([key, value]);
427
+ } else {
428
+ data[index][1] = value;
429
+ }
430
+ return this;
431
+ }
432
+ ListCache.prototype.clear = listCacheClear;
433
+ ListCache.prototype["delete"] = listCacheDelete;
434
+ ListCache.prototype.get = listCacheGet;
435
+ ListCache.prototype.has = listCacheHas;
436
+ ListCache.prototype.set = listCacheSet;
437
+ function MapCache(entries) {
438
+ var index = -1, length = entries == null ? 0 : entries.length;
439
+ this.clear();
440
+ while (++index < length) {
441
+ var entry = entries[index];
442
+ this.set(entry[0], entry[1]);
443
+ }
444
+ }
445
+ function mapCacheClear() {
446
+ this.size = 0;
447
+ this.__data__ = {
448
+ "hash": new Hash(),
449
+ "map": new (Map2 || ListCache)(),
450
+ "string": new Hash()
451
+ };
452
+ }
453
+ function mapCacheDelete(key) {
454
+ var result = getMapData(this, key)["delete"](key);
455
+ this.size -= result ? 1 : 0;
456
+ return result;
457
+ }
458
+ function mapCacheGet(key) {
459
+ return getMapData(this, key).get(key);
460
+ }
461
+ function mapCacheHas(key) {
462
+ return getMapData(this, key).has(key);
463
+ }
464
+ function mapCacheSet(key, value) {
465
+ var data = getMapData(this, key), size = data.size;
466
+ data.set(key, value);
467
+ this.size += data.size == size ? 0 : 1;
468
+ return this;
469
+ }
470
+ MapCache.prototype.clear = mapCacheClear;
471
+ MapCache.prototype["delete"] = mapCacheDelete;
472
+ MapCache.prototype.get = mapCacheGet;
473
+ MapCache.prototype.has = mapCacheHas;
474
+ MapCache.prototype.set = mapCacheSet;
475
+ function SetCache(values) {
476
+ var index = -1, length = values == null ? 0 : values.length;
477
+ this.__data__ = new MapCache();
478
+ while (++index < length) {
479
+ this.add(values[index]);
480
+ }
481
+ }
482
+ function setCacheAdd(value) {
483
+ this.__data__.set(value, HASH_UNDEFINED);
484
+ return this;
485
+ }
486
+ function setCacheHas(value) {
487
+ return this.__data__.has(value);
488
+ }
489
+ SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
490
+ SetCache.prototype.has = setCacheHas;
491
+ function Stack(entries) {
492
+ var data = this.__data__ = new ListCache(entries);
493
+ this.size = data.size;
494
+ }
495
+ function stackClear() {
496
+ this.__data__ = new ListCache();
497
+ this.size = 0;
498
+ }
499
+ function stackDelete(key) {
500
+ var data = this.__data__, result = data["delete"](key);
501
+ this.size = data.size;
502
+ return result;
503
+ }
504
+ function stackGet(key) {
505
+ return this.__data__.get(key);
506
+ }
507
+ function stackHas(key) {
508
+ return this.__data__.has(key);
509
+ }
510
+ function stackSet(key, value) {
511
+ var data = this.__data__;
512
+ if (data instanceof ListCache) {
513
+ var pairs = data.__data__;
514
+ if (!Map2 || pairs.length < LARGE_ARRAY_SIZE - 1) {
515
+ pairs.push([key, value]);
516
+ this.size = ++data.size;
517
+ return this;
518
+ }
519
+ data = this.__data__ = new MapCache(pairs);
520
+ }
521
+ data.set(key, value);
522
+ this.size = data.size;
523
+ return this;
524
+ }
525
+ Stack.prototype.clear = stackClear;
526
+ Stack.prototype["delete"] = stackDelete;
527
+ Stack.prototype.get = stackGet;
528
+ Stack.prototype.has = stackHas;
529
+ Stack.prototype.set = stackSet;
530
+ function arrayLikeKeys(value, inherited) {
531
+ var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length;
532
+ for (var key in value) {
533
+ if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode.
534
+ (key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers.
535
+ isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays.
536
+ isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties.
537
+ isIndex(key, length)))) {
538
+ result.push(key);
539
+ }
540
+ }
541
+ return result;
542
+ }
543
+ function assocIndexOf(array, key) {
544
+ var length = array.length;
545
+ while (length--) {
546
+ if (eq(array[length][0], key)) {
547
+ return length;
548
+ }
549
+ }
550
+ return -1;
551
+ }
552
+ function baseGetAllKeys(object, keysFunc, symbolsFunc) {
553
+ var result = keysFunc(object);
554
+ return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
555
+ }
556
+ function baseGetTag(value) {
557
+ if (value == null) {
558
+ return value === void 0 ? undefinedTag : nullTag;
559
+ }
560
+ return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
561
+ }
562
+ function baseIsArguments(value) {
563
+ return isObjectLike(value) && baseGetTag(value) == argsTag;
564
+ }
565
+ function baseIsEqual(value, other, bitmask, customizer, stack) {
566
+ if (value === other) {
567
+ return true;
568
+ }
569
+ if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) {
570
+ return value !== value && other !== other;
571
+ }
572
+ return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
573
+ }
574
+ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
575
+ var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other);
576
+ objTag = objTag == argsTag ? objectTag : objTag;
577
+ othTag = othTag == argsTag ? objectTag : othTag;
578
+ var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag;
579
+ if (isSameTag && isBuffer(object)) {
580
+ if (!isBuffer(other)) {
581
+ return false;
582
+ }
583
+ objIsArr = true;
584
+ objIsObj = false;
585
+ }
586
+ if (isSameTag && !objIsObj) {
587
+ stack || (stack = new Stack());
588
+ return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
589
+ }
590
+ if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
591
+ var objIsWrapped = objIsObj && hasOwnProperty.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty.call(other, "__wrapped__");
592
+ if (objIsWrapped || othIsWrapped) {
593
+ var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
594
+ stack || (stack = new Stack());
595
+ return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
596
+ }
597
+ }
598
+ if (!isSameTag) {
599
+ return false;
600
+ }
601
+ stack || (stack = new Stack());
602
+ return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
603
+ }
604
+ function baseIsNative(value) {
605
+ if (!isObject(value) || isMasked(value)) {
606
+ return false;
607
+ }
608
+ var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
609
+ return pattern.test(toSource(value));
610
+ }
611
+ function baseIsTypedArray(value) {
612
+ return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
613
+ }
614
+ function baseKeys(object) {
615
+ if (!isPrototype(object)) {
616
+ return nativeKeys(object);
617
+ }
618
+ var result = [];
619
+ for (var key in Object(object)) {
620
+ if (hasOwnProperty.call(object, key) && key != "constructor") {
621
+ result.push(key);
622
+ }
623
+ }
624
+ return result;
625
+ }
626
+ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
627
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length;
628
+ if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
629
+ return false;
630
+ }
631
+ var stacked = stack.get(array);
632
+ if (stacked && stack.get(other)) {
633
+ return stacked == other;
634
+ }
635
+ var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : void 0;
636
+ stack.set(array, other);
637
+ stack.set(other, array);
638
+ while (++index < arrLength) {
639
+ var arrValue = array[index], othValue = other[index];
640
+ if (customizer) {
641
+ var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
642
+ }
643
+ if (compared !== void 0) {
644
+ if (compared) {
645
+ continue;
646
+ }
647
+ result = false;
648
+ break;
649
+ }
650
+ if (seen) {
651
+ if (!arraySome(other, function(othValue2, othIndex) {
652
+ if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) {
653
+ return seen.push(othIndex);
654
+ }
655
+ })) {
656
+ result = false;
657
+ break;
658
+ }
659
+ } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
660
+ result = false;
661
+ break;
662
+ }
663
+ }
664
+ stack["delete"](array);
665
+ stack["delete"](other);
666
+ return result;
667
+ }
668
+ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
669
+ switch (tag) {
670
+ case dataViewTag:
671
+ if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
672
+ return false;
673
+ }
674
+ object = object.buffer;
675
+ other = other.buffer;
676
+ case arrayBufferTag:
677
+ if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array2(object), new Uint8Array2(other))) {
678
+ return false;
679
+ }
680
+ return true;
681
+ case boolTag:
682
+ case dateTag:
683
+ case numberTag:
684
+ return eq(+object, +other);
685
+ case errorTag:
686
+ return object.name == other.name && object.message == other.message;
687
+ case regexpTag:
688
+ case stringTag:
689
+ return object == other + "";
690
+ case mapTag:
691
+ var convert = mapToArray;
692
+ case setTag:
693
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
694
+ convert || (convert = setToArray);
695
+ if (object.size != other.size && !isPartial) {
696
+ return false;
697
+ }
698
+ var stacked = stack.get(object);
699
+ if (stacked) {
700
+ return stacked == other;
701
+ }
702
+ bitmask |= COMPARE_UNORDERED_FLAG;
703
+ stack.set(object, other);
704
+ var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
705
+ stack["delete"](object);
706
+ return result;
707
+ case symbolTag:
708
+ if (symbolValueOf) {
709
+ return symbolValueOf.call(object) == symbolValueOf.call(other);
710
+ }
711
+ }
712
+ return false;
713
+ }
714
+ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
715
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length;
716
+ if (objLength != othLength && !isPartial) {
717
+ return false;
718
+ }
719
+ var index = objLength;
720
+ while (index--) {
721
+ var key = objProps[index];
722
+ if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
723
+ return false;
724
+ }
725
+ }
726
+ var stacked = stack.get(object);
727
+ if (stacked && stack.get(other)) {
728
+ return stacked == other;
729
+ }
730
+ var result = true;
731
+ stack.set(object, other);
732
+ stack.set(other, object);
733
+ var skipCtor = isPartial;
734
+ while (++index < objLength) {
735
+ key = objProps[index];
736
+ var objValue = object[key], othValue = other[key];
737
+ if (customizer) {
738
+ var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
739
+ }
740
+ if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
741
+ result = false;
742
+ break;
743
+ }
744
+ skipCtor || (skipCtor = key == "constructor");
745
+ }
746
+ if (result && !skipCtor) {
747
+ var objCtor = object.constructor, othCtor = other.constructor;
748
+ if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) {
749
+ result = false;
750
+ }
751
+ }
752
+ stack["delete"](object);
753
+ stack["delete"](other);
754
+ return result;
755
+ }
756
+ function getAllKeys(object) {
757
+ return baseGetAllKeys(object, keys, getSymbols);
758
+ }
759
+ function getMapData(map, key) {
760
+ var data = map.__data__;
761
+ return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
762
+ }
763
+ function getNative(object, key) {
764
+ var value = getValue(object, key);
765
+ return baseIsNative(value) ? value : void 0;
766
+ }
767
+ function getRawTag(value) {
768
+ var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
769
+ try {
770
+ value[symToStringTag] = void 0;
771
+ var unmasked = true;
772
+ } catch (e) {
773
+ }
774
+ var result = nativeObjectToString.call(value);
775
+ if (unmasked) {
776
+ if (isOwn) {
777
+ value[symToStringTag] = tag;
778
+ } else {
779
+ delete value[symToStringTag];
780
+ }
781
+ }
782
+ return result;
783
+ }
784
+ var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
785
+ if (object == null) {
786
+ return [];
787
+ }
788
+ object = Object(object);
789
+ return arrayFilter(nativeGetSymbols(object), function(symbol) {
790
+ return propertyIsEnumerable.call(object, symbol);
791
+ });
792
+ };
793
+ var getTag = baseGetTag;
794
+ if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map2 && getTag(new Map2()) != mapTag || Promise2 && getTag(Promise2.resolve()) != promiseTag || Set2 && getTag(new Set2()) != setTag || WeakMap2 && getTag(new WeakMap2()) != weakMapTag) {
795
+ getTag = function(value) {
796
+ var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : void 0, ctorString = Ctor ? toSource(Ctor) : "";
797
+ if (ctorString) {
798
+ switch (ctorString) {
799
+ case dataViewCtorString:
800
+ return dataViewTag;
801
+ case mapCtorString:
802
+ return mapTag;
803
+ case promiseCtorString:
804
+ return promiseTag;
805
+ case setCtorString:
806
+ return setTag;
807
+ case weakMapCtorString:
808
+ return weakMapTag;
809
+ }
810
+ }
811
+ return result;
812
+ };
813
+ }
814
+ function isIndex(value, length) {
815
+ length = length == null ? MAX_SAFE_INTEGER : length;
816
+ return !!length && (typeof value == "number" || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length);
817
+ }
818
+ function isKeyable(value) {
819
+ var type = typeof value;
820
+ return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
821
+ }
822
+ function isMasked(func) {
823
+ return !!maskSrcKey && maskSrcKey in func;
824
+ }
825
+ function isPrototype(value) {
826
+ var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto;
827
+ return value === proto;
828
+ }
829
+ function objectToString(value) {
830
+ return nativeObjectToString.call(value);
831
+ }
832
+ function toSource(func) {
833
+ if (func != null) {
834
+ try {
835
+ return funcToString.call(func);
836
+ } catch (e) {
837
+ }
838
+ try {
839
+ return func + "";
840
+ } catch (e) {
841
+ }
842
+ }
843
+ return "";
844
+ }
845
+ function eq(value, other) {
846
+ return value === other || value !== value && other !== other;
847
+ }
848
+ var isArguments = baseIsArguments(/* @__PURE__ */ (function() {
849
+ return arguments;
850
+ })()) ? baseIsArguments : function(value) {
851
+ return isObjectLike(value) && hasOwnProperty.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
852
+ };
853
+ var isArray = Array.isArray;
854
+ function isArrayLike(value) {
855
+ return value != null && isLength(value.length) && !isFunction(value);
856
+ }
857
+ var isBuffer = nativeIsBuffer || stubFalse;
858
+ function isEqual(value, other) {
859
+ return baseIsEqual(value, other);
860
+ }
861
+ function isFunction(value) {
862
+ if (!isObject(value)) {
863
+ return false;
864
+ }
865
+ var tag = baseGetTag(value);
866
+ return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
867
+ }
868
+ function isLength(value) {
869
+ return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
870
+ }
871
+ function isObject(value) {
872
+ var type = typeof value;
873
+ return value != null && (type == "object" || type == "function");
874
+ }
875
+ function isObjectLike(value) {
876
+ return value != null && typeof value == "object";
877
+ }
878
+ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
879
+ function keys(object) {
880
+ return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
881
+ }
882
+ function stubArray() {
883
+ return [];
884
+ }
885
+ function stubFalse() {
886
+ return false;
887
+ }
888
+ module2.exports = isEqual;
889
+ }
890
+ });
891
+
892
+ // node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/helpers.js
893
+ var require_helpers = __commonJS({
894
+ "node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/helpers.js"(exports2) {
895
+ "use strict";
896
+ var _a;
897
+ var _b;
898
+ Object.defineProperty(exports2, "__esModule", { value: true });
899
+ exports2.isString = exports2.defaultEqualityFn = exports2.isObj = exports2.isConstructor = exports2.printError = exports2.PROMPT = exports2.readFile = exports2.parseQueryEvent = exports2.repr = exports2.ancestors = void 0;
900
+ var util_1 = require("util");
901
+ var fs_1 = require("fs");
902
+ var errors_1 = require_errors();
903
+ var types_1 = require_types();
904
+ var isEqual = require_lodash();
905
+ function ancestors(cls) {
906
+ if (!isConstructor(cls))
907
+ return [];
908
+ const ancestors2 = [cls];
909
+ function next(current) {
910
+ const parent = Object.getPrototypeOf(current);
911
+ if (parent === Function.prototype)
912
+ return;
913
+ if (!isConstructor(parent))
914
+ return;
915
+ ancestors2.push(parent);
916
+ next(parent);
917
+ }
918
+ next(cls);
919
+ return ancestors2;
920
+ }
921
+ exports2.ancestors = ancestors;
922
+ function repr(x) {
923
+ return util_1.inspect(x);
924
+ }
925
+ exports2.repr = repr;
926
+ function parseQueryEvent(event) {
927
+ try {
928
+ if (exports2.isString(event))
929
+ throw new Error();
930
+ switch (true) {
931
+ case event["Done"] !== void 0:
932
+ return { kind: types_1.QueryEventKind.Done };
933
+ case event["Result"] !== void 0:
934
+ return parseResult(event["Result"]);
935
+ case event["MakeExternal"] !== void 0:
936
+ return parseMakeExternal(event["MakeExternal"]);
937
+ case event["NextExternal"] !== void 0:
938
+ return parseNextExternal(event["NextExternal"]);
939
+ case event["ExternalCall"] !== void 0:
940
+ return parseExternalCall(event["ExternalCall"]);
941
+ case event["ExternalIsSubSpecializer"] !== void 0:
942
+ return parseExternalIsSubspecializer(event["ExternalIsSubSpecializer"]);
943
+ case event["ExternalIsSubclass"] !== void 0:
944
+ return parseExternalIsSubclass(event["ExternalIsSubclass"]);
945
+ case event["ExternalIsa"] !== void 0:
946
+ return parseExternalIsa(event["ExternalIsa"]);
947
+ case event["ExternalIsaWithPath"] !== void 0:
948
+ return parseExternalIsaWithPath(event["ExternalIsaWithPath"]);
949
+ case event["Debug"] !== void 0:
950
+ return parseDebug(event["Debug"]);
951
+ case event["ExternalOp"] !== void 0:
952
+ return parseExternalOp(event["ExternalOp"]);
953
+ default:
954
+ throw new Error();
955
+ }
956
+ } catch (e) {
957
+ if (e instanceof errors_1.PolarError)
958
+ throw e;
959
+ throw new errors_1.InvalidQueryEventError(JSON.stringify(event));
960
+ }
961
+ }
962
+ exports2.parseQueryEvent = parseQueryEvent;
963
+ function parseResult(event) {
964
+ if (!isObj(event))
965
+ throw new Error();
966
+ const { bindings } = event;
967
+ if (!isMapOfPolarTerms(bindings))
968
+ throw new Error();
969
+ return { kind: types_1.QueryEventKind.Result, data: { bindings } };
970
+ }
971
+ function parseMakeExternal(event) {
972
+ if (!isObj(event))
973
+ throw new Error();
974
+ const { instance_id: instanceId } = event;
975
+ if (!isSafeInteger(instanceId))
976
+ throw new Error();
977
+ const ctor = event["constructor"];
978
+ if (!types_1.isPolarTerm(ctor))
979
+ throw new Error();
980
+ if (!types_1.isPolarPredicate(ctor.value))
981
+ throw new Error();
982
+ if (ctor.value.Call.kwargs)
983
+ throw new errors_1.KwargsError();
984
+ const { name: tag, args: fields } = ctor.value.Call;
985
+ if (!exports2.isString(tag))
986
+ throw new Error();
987
+ if (!isArrayOf(fields, types_1.isPolarTerm))
988
+ throw new Error();
989
+ return {
990
+ kind: types_1.QueryEventKind.MakeExternal,
991
+ data: { fields, instanceId, tag }
992
+ };
993
+ }
994
+ function parseNextExternal(event) {
995
+ if (!isObj(event))
996
+ throw new Error();
997
+ const { call_id: callId, iterable } = event;
998
+ if (!isSafeInteger(callId))
999
+ throw new Error();
1000
+ if (!types_1.isPolarTerm(iterable))
1001
+ throw new Error();
1002
+ return { kind: types_1.QueryEventKind.NextExternal, data: { callId, iterable } };
1003
+ }
1004
+ function parseExternalCall(event) {
1005
+ if (!isObj(event))
1006
+ throw new Error();
1007
+ const { args, kwargs, attribute, call_id: callId, instance } = event;
1008
+ if (args !== void 0 && !isArrayOf(args, types_1.isPolarTerm))
1009
+ throw new Error();
1010
+ if (kwargs)
1011
+ throw new errors_1.KwargsError();
1012
+ if (!exports2.isString(attribute))
1013
+ throw new Error();
1014
+ if (!isSafeInteger(callId))
1015
+ throw new Error();
1016
+ if (!types_1.isPolarTerm(instance))
1017
+ throw new Error();
1018
+ return {
1019
+ kind: types_1.QueryEventKind.ExternalCall,
1020
+ data: { args, attribute, callId, instance }
1021
+ };
1022
+ }
1023
+ function parseExternalIsSubspecializer(event) {
1024
+ if (!isObj(event))
1025
+ throw new Error();
1026
+ const { call_id: callId, instance_id: instanceId, left_class_tag: leftTag, right_class_tag: rightTag } = event;
1027
+ if (!isSafeInteger(callId))
1028
+ throw new Error();
1029
+ if (!isSafeInteger(instanceId))
1030
+ throw new Error();
1031
+ if (!exports2.isString(leftTag))
1032
+ throw new Error();
1033
+ if (!exports2.isString(rightTag))
1034
+ throw new Error();
1035
+ return {
1036
+ kind: types_1.QueryEventKind.ExternalIsSubspecializer,
1037
+ data: { callId, instanceId, leftTag, rightTag }
1038
+ };
1039
+ }
1040
+ function parseExternalIsSubclass(event) {
1041
+ if (!isObj(event))
1042
+ throw new Error();
1043
+ const { call_id: callId, left_class_tag: leftTag, right_class_tag: rightTag } = event;
1044
+ if (!isSafeInteger(callId))
1045
+ throw new Error();
1046
+ if (!exports2.isString(leftTag))
1047
+ throw new Error();
1048
+ if (!exports2.isString(rightTag))
1049
+ throw new Error();
1050
+ return {
1051
+ kind: types_1.QueryEventKind.ExternalIsSubclass,
1052
+ data: { callId, leftTag, rightTag }
1053
+ };
1054
+ }
1055
+ function parseExternalIsa(event) {
1056
+ if (!isObj(event))
1057
+ throw new Error();
1058
+ const { call_id: callId, instance, class_tag: tag } = event;
1059
+ if (!isSafeInteger(callId))
1060
+ throw new Error();
1061
+ if (!types_1.isPolarTerm(instance))
1062
+ throw new Error();
1063
+ if (!exports2.isString(tag))
1064
+ throw new Error();
1065
+ return { kind: types_1.QueryEventKind.ExternalIsa, data: { callId, instance, tag } };
1066
+ }
1067
+ function parseExternalIsaWithPath(event) {
1068
+ if (!isObj(event))
1069
+ throw new Error();
1070
+ const { path, call_id: callId, base_tag: baseTag, class_tag: classTag } = event;
1071
+ if (!isSafeInteger(callId))
1072
+ throw new Error();
1073
+ if (!exports2.isString(baseTag))
1074
+ throw new Error();
1075
+ if (!exports2.isString(classTag))
1076
+ throw new Error();
1077
+ if (!isArrayOf(path, types_1.isPolarTerm))
1078
+ throw new Error();
1079
+ return {
1080
+ kind: types_1.QueryEventKind.ExternalIsaWithPath,
1081
+ data: { callId, baseTag, path, classTag }
1082
+ };
1083
+ }
1084
+ function parseExternalOp(event) {
1085
+ if (!isObj(event))
1086
+ throw new Error();
1087
+ const { call_id: callId, args, operator } = event;
1088
+ if (!isSafeInteger(callId))
1089
+ throw new Error();
1090
+ if (!isArrayOf(args, types_1.isPolarTerm) || args.length !== 2)
1091
+ throw new Error();
1092
+ if (!exports2.isString(operator))
1093
+ throw new Error();
1094
+ if (!types_1.isPolarComparisonOperator(operator))
1095
+ throw new errors_1.PolarError(`Unsupported external operation '${repr(args[0])} ${operator} ${repr(args[1])}'`);
1096
+ return { kind: types_1.QueryEventKind.ExternalOp, data: { args, callId, operator } };
1097
+ }
1098
+ function parseDebug(event) {
1099
+ if (!isObj(event))
1100
+ throw new Error();
1101
+ const { message } = event;
1102
+ if (!exports2.isString(message))
1103
+ throw new Error();
1104
+ return { kind: types_1.QueryEventKind.Debug, data: { message } };
1105
+ }
1106
+ function readFile(file) {
1107
+ return new Promise((res, rej) => fs_1.readFile(file, { encoding: "utf8" }, (err, contents) => err === null ? res(contents) : rej(err)));
1108
+ }
1109
+ exports2.readFile = readFile;
1110
+ var RESET = "";
1111
+ var FG_BLUE = "";
1112
+ var FG_RED = "";
1113
+ if (typeof ((_a = process === null || process === void 0 ? void 0 : process.stdout) === null || _a === void 0 ? void 0 : _a.getColorDepth) === "function" && process.stdout.getColorDepth() >= 4 && typeof ((_b = process === null || process === void 0 ? void 0 : process.stderr) === null || _b === void 0 ? void 0 : _b.getColorDepth) === "function" && process.stderr.getColorDepth() >= 4) {
1114
+ RESET = "\x1B[0m";
1115
+ FG_BLUE = "\x1B[34m";
1116
+ FG_RED = "\x1B[31m";
1117
+ }
1118
+ exports2.PROMPT = FG_BLUE + "query> " + RESET;
1119
+ function printError(e) {
1120
+ console.error(FG_RED + e.name + RESET);
1121
+ console.error(e.message);
1122
+ }
1123
+ exports2.printError = printError;
1124
+ function isConstructor(f) {
1125
+ try {
1126
+ Reflect.construct(String, [], f);
1127
+ return true;
1128
+ } catch (e) {
1129
+ return false;
1130
+ }
1131
+ }
1132
+ exports2.isConstructor = isConstructor;
1133
+ function isObj(x) {
1134
+ return typeof x === "object" && x !== null;
1135
+ }
1136
+ exports2.isObj = isObj;
1137
+ function defaultEqualityFn(a, b) {
1138
+ return isEqual(a, b);
1139
+ }
1140
+ exports2.defaultEqualityFn = defaultEqualityFn;
1141
+ var isString = (x) => typeof x === "string";
1142
+ exports2.isString = isString;
1143
+ var isMapOfPolarTerms = (x) => x instanceof Map && [...x.keys()].every(exports2.isString) && [...x.values()].every(types_1.isPolarTerm);
1144
+ var isArrayOf = (x, p) => Array.isArray(x) && x.every(p);
1145
+ function isSafeInteger(x) {
1146
+ return Number.isSafeInteger(x);
1147
+ }
1148
+ }
1149
+ });
1150
+
1151
+ // node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/errors.js
1152
+ var require_errors = __commonJS({
1153
+ "node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/errors.js"(exports2) {
1154
+ "use strict";
1155
+ Object.defineProperty(exports2, "__esModule", { value: true });
1156
+ exports2.UnexpectedExpressionError = exports2.DataFilteringConfigurationError = exports2.UnregisteredInstanceError = exports2.UnregisteredClassError = exports2.PolarFileNotFoundError = exports2.PolarFileExtensionError = exports2.KwargsError = exports2.InvalidQueryEventError = exports2.InvalidConstructorError = exports2.InvalidIteratorError = exports2.InvalidCallError = exports2.InvalidAttributeError = exports2.InlineQueryFailedError = exports2.DuplicateInstanceRegistrationError = exports2.DuplicateClassAliasError = exports2.PolarError = exports2.ForbiddenError = exports2.NotFoundError = exports2.AuthorizationError = exports2.OsoError = void 0;
1157
+ var helpers_1 = require_helpers();
1158
+ var OsoError = class extends Error {
1159
+ constructor(message) {
1160
+ super(message);
1161
+ }
1162
+ };
1163
+ exports2.OsoError = OsoError;
1164
+ var AuthorizationError = class extends OsoError {
1165
+ };
1166
+ exports2.AuthorizationError = AuthorizationError;
1167
+ var NotFoundError = class extends AuthorizationError {
1168
+ constructor() {
1169
+ super("Oso NotFoundError -- The current user does not have permission to read the given resource. You should handle this error by returning a 404 error to the client.");
1170
+ }
1171
+ };
1172
+ exports2.NotFoundError = NotFoundError;
1173
+ var ForbiddenError = class extends AuthorizationError {
1174
+ constructor() {
1175
+ super("Oso ForbiddenError -- The requested action was not allowed for the given resource. You should handle this error by returning a 403 error to the client.");
1176
+ }
1177
+ };
1178
+ exports2.ForbiddenError = ForbiddenError;
1179
+ var PolarError = class extends OsoError {
1180
+ };
1181
+ exports2.PolarError = PolarError;
1182
+ var DuplicateClassAliasError = class extends PolarError {
1183
+ constructor({ name, cls, existing }) {
1184
+ super(`Attempted to alias ${cls.name} as '${name}', but ${existing.name} already has that alias.`);
1185
+ }
1186
+ };
1187
+ exports2.DuplicateClassAliasError = DuplicateClassAliasError;
1188
+ var DuplicateInstanceRegistrationError = class extends PolarError {
1189
+ constructor(id) {
1190
+ super(`Attempted to register instance ${id}, but an instance with that ID already exists.`);
1191
+ }
1192
+ };
1193
+ exports2.DuplicateInstanceRegistrationError = DuplicateInstanceRegistrationError;
1194
+ var InlineQueryFailedError = class extends PolarError {
1195
+ constructor(source) {
1196
+ super(`Inline query failed: ${source}`);
1197
+ }
1198
+ };
1199
+ exports2.InlineQueryFailedError = InlineQueryFailedError;
1200
+ var InvalidAttributeError = class extends PolarError {
1201
+ constructor(instance, field) {
1202
+ super(`${field} not found on ${helpers_1.repr(instance)}.`);
1203
+ }
1204
+ };
1205
+ exports2.InvalidAttributeError = InvalidAttributeError;
1206
+ var InvalidCallError = class extends PolarError {
1207
+ constructor(instance, field) {
1208
+ super(`${helpers_1.repr(instance)}.${field} is not a function`);
1209
+ }
1210
+ };
1211
+ exports2.InvalidCallError = InvalidCallError;
1212
+ var InvalidIteratorError = class extends PolarError {
1213
+ constructor(term) {
1214
+ super(`${helpers_1.repr(term)} is not iterable`);
1215
+ }
1216
+ };
1217
+ exports2.InvalidIteratorError = InvalidIteratorError;
1218
+ var InvalidConstructorError = class extends PolarError {
1219
+ constructor(ctor) {
1220
+ super(`${helpers_1.repr(ctor)} is not a constructor`);
1221
+ }
1222
+ };
1223
+ exports2.InvalidConstructorError = InvalidConstructorError;
1224
+ var InvalidQueryEventError = class extends PolarError {
1225
+ constructor(event) {
1226
+ super(`Invalid query event: ${event}`);
1227
+ }
1228
+ };
1229
+ exports2.InvalidQueryEventError = InvalidQueryEventError;
1230
+ var KwargsError = class extends PolarError {
1231
+ constructor() {
1232
+ super("JavaScript does not support keyword arguments");
1233
+ }
1234
+ };
1235
+ exports2.KwargsError = KwargsError;
1236
+ var PolarFileExtensionError = class extends PolarError {
1237
+ constructor(file) {
1238
+ super(`Polar files must have .polar extension. Offending file: ${file}`);
1239
+ }
1240
+ };
1241
+ exports2.PolarFileExtensionError = PolarFileExtensionError;
1242
+ var PolarFileNotFoundError = class extends PolarError {
1243
+ constructor(file) {
1244
+ super(`Could not find file: ${file}`);
1245
+ }
1246
+ };
1247
+ exports2.PolarFileNotFoundError = PolarFileNotFoundError;
1248
+ var UnregisteredClassError = class extends PolarError {
1249
+ constructor(name) {
1250
+ super(`Unregistered class: ${name}.`);
1251
+ }
1252
+ };
1253
+ exports2.UnregisteredClassError = UnregisteredClassError;
1254
+ var UnregisteredInstanceError = class extends PolarError {
1255
+ constructor(id) {
1256
+ super(`Unregistered instance: ${id}.`);
1257
+ }
1258
+ };
1259
+ exports2.UnregisteredInstanceError = UnregisteredInstanceError;
1260
+ var DataFilteringConfigurationError = class extends PolarError {
1261
+ constructor() {
1262
+ super("Missing 'adapter' implementation. Did you forget to call `Oso.setDataFilteringAdapter()`?");
1263
+ }
1264
+ };
1265
+ exports2.DataFilteringConfigurationError = DataFilteringConfigurationError;
1266
+ var UnexpectedExpressionError = class extends PolarError {
1267
+ constructor() {
1268
+ super(`Received Expression from Polar VM. The Expression type is only supported when
1269
+ using data filtering features. Did you perform an
1270
+ operation over an unbound variable in your policy?
1271
+
1272
+ To silence this error and receive an Expression result, pass the
1273
+ \`{ acceptExpression: true }\` option to \`Oso.query()\` or \`Oso.queryRule()\`.`);
1274
+ }
1275
+ };
1276
+ exports2.UnexpectedExpressionError = UnexpectedExpressionError;
1277
+ }
1278
+ });
1279
+
1280
+ // node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/messages.js
1281
+ var require_messages = __commonJS({
1282
+ "node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/messages.js"(exports2) {
1283
+ "use strict";
1284
+ Object.defineProperty(exports2, "__esModule", { value: true });
1285
+ exports2.processMessage = void 0;
1286
+ var MessageKind;
1287
+ (function(MessageKind2) {
1288
+ MessageKind2["Print"] = "Print";
1289
+ MessageKind2["Warning"] = "Warning";
1290
+ })(MessageKind || (MessageKind = {}));
1291
+ function processMessage(message) {
1292
+ switch (message.kind) {
1293
+ case MessageKind.Print:
1294
+ console.log(message.msg);
1295
+ break;
1296
+ case MessageKind.Warning:
1297
+ console.warn("[warning]", message.msg);
1298
+ break;
1299
+ }
1300
+ }
1301
+ exports2.processMessage = processMessage;
1302
+ }
1303
+ });
1304
+
1305
+ // node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/filter.js
1306
+ var require_filter = __commonJS({
1307
+ "node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/filter.js"(exports2) {
1308
+ "use strict";
1309
+ Object.defineProperty(exports2, "__esModule", { value: true });
1310
+ exports2.parseFilter = exports2.isProjection = exports2.Relation = void 0;
1311
+ var errors_1 = require_errors();
1312
+ var Relation = class {
1313
+ constructor(kind, otherType, myField, otherField) {
1314
+ this.kind = kind;
1315
+ this.otherType = otherType;
1316
+ this.myField = myField;
1317
+ this.otherField = otherField;
1318
+ }
1319
+ serialize() {
1320
+ return {
1321
+ Relation: {
1322
+ kind: this.kind,
1323
+ other_class_tag: this.otherType,
1324
+ my_field: this.myField,
1325
+ other_field: this.otherField
1326
+ }
1327
+ };
1328
+ }
1329
+ };
1330
+ exports2.Relation = Relation;
1331
+ function isProjection(x) {
1332
+ return x.typeName !== void 0;
1333
+ }
1334
+ exports2.isProjection = isProjection;
1335
+ async function parseFilter(filter_json, host) {
1336
+ const filter = {
1337
+ model: filter_json.root,
1338
+ relations: [],
1339
+ conditions: [],
1340
+ types: host.types
1341
+ };
1342
+ for (const [fromTypeName, fromFieldName, toTypeName] of filter_json.relations)
1343
+ filter.relations.push({ fromTypeName, fromFieldName, toTypeName });
1344
+ async function parseDatum(d, host2) {
1345
+ const k = Object.getOwnPropertyNames(d)[0];
1346
+ switch (k) {
1347
+ case "Field": {
1348
+ const [typeName, fieldName] = d[k];
1349
+ return { typeName, fieldName };
1350
+ }
1351
+ case "Immediate":
1352
+ return { value: await host2.toJs({ value: d[k] }) };
1353
+ default: {
1354
+ throw new errors_1.OsoError("Invalid filter json.");
1355
+ }
1356
+ }
1357
+ }
1358
+ for (const cs of filter_json.conditions) {
1359
+ const and_group = [];
1360
+ for (const [l, op, r] of cs) {
1361
+ const condition = {
1362
+ lhs: await parseDatum(l, host),
1363
+ cmp: op,
1364
+ rhs: await parseDatum(r, host)
1365
+ };
1366
+ and_group.push(condition);
1367
+ }
1368
+ filter.conditions.push(and_group);
1369
+ }
1370
+ return filter;
1371
+ }
1372
+ exports2.parseFilter = parseFilter;
1373
+ }
1374
+ });
1375
+
1376
+ // node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/Query.js
1377
+ var require_Query = __commonJS({
1378
+ "node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/Query.js"(exports2) {
1379
+ "use strict";
1380
+ var __classPrivateFieldSet = exports2 && exports2.__classPrivateFieldSet || function(receiver, state, value, kind, f) {
1381
+ if (kind === "m") throw new TypeError("Private method is not writable");
1382
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
1383
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
1384
+ return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
1385
+ };
1386
+ var __classPrivateFieldGet = exports2 && exports2.__classPrivateFieldGet || function(receiver, state, kind, f) {
1387
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
1388
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
1389
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
1390
+ };
1391
+ var _Query_ffiQuery;
1392
+ var _Query_calls;
1393
+ var _Query_host;
1394
+ Object.defineProperty(exports2, "__esModule", { value: true });
1395
+ exports2.Query = void 0;
1396
+ var readline_1 = require("readline");
1397
+ var helpers_1 = require_helpers();
1398
+ var errors_1 = require_errors();
1399
+ var messages_1 = require_messages();
1400
+ var types_1 = require_types();
1401
+ var filter_1 = require_filter();
1402
+ function getLogLevelsFromEnv() {
1403
+ if (typeof (process === null || process === void 0 ? void 0 : process.env) === "undefined")
1404
+ return [void 0, void 0];
1405
+ return [process.env.RUST_LOG, process.env.POLAR_LOG];
1406
+ }
1407
+ var Query = class {
1408
+ constructor(ffiQuery, host, bindings) {
1409
+ _Query_ffiQuery.set(this, void 0);
1410
+ _Query_calls.set(this, void 0);
1411
+ _Query_host.set(this, void 0);
1412
+ ffiQuery.setLoggingOptions(...getLogLevelsFromEnv());
1413
+ __classPrivateFieldSet(this, _Query_ffiQuery, ffiQuery, "f");
1414
+ __classPrivateFieldSet(this, _Query_calls, /* @__PURE__ */ new Map(), "f");
1415
+ __classPrivateFieldSet(this, _Query_host, host, "f");
1416
+ if (bindings)
1417
+ for (const [k, v] of bindings)
1418
+ this.bind(k, v);
1419
+ this.results = this.start();
1420
+ }
1421
+ /**
1422
+ * Process messages received from the Polar VM.
1423
+ *
1424
+ * @internal
1425
+ */
1426
+ bind(name, value) {
1427
+ __classPrivateFieldGet(this, _Query_ffiQuery, "f").bind(name, __classPrivateFieldGet(this, _Query_host, "f").toPolar(value));
1428
+ }
1429
+ /**
1430
+ * Process messages received from the Polar VM.
1431
+ *
1432
+ * @internal
1433
+ */
1434
+ processMessages() {
1435
+ for (; ; ) {
1436
+ const msg = __classPrivateFieldGet(this, _Query_ffiQuery, "f").nextMessage();
1437
+ if (msg === void 0)
1438
+ break;
1439
+ messages_1.processMessage(msg);
1440
+ }
1441
+ }
1442
+ /**
1443
+ * Send result of predicate check back to the Polar VM.
1444
+ *
1445
+ * @internal
1446
+ */
1447
+ questionResult(result, callId) {
1448
+ __classPrivateFieldGet(this, _Query_ffiQuery, "f").questionResult(callId, result);
1449
+ }
1450
+ /**
1451
+ * Send next result of JavaScript method call or property lookup to the Polar
1452
+ * VM.
1453
+ *
1454
+ * @internal
1455
+ */
1456
+ callResult(callId, result) {
1457
+ __classPrivateFieldGet(this, _Query_ffiQuery, "f").callResult(callId, result);
1458
+ }
1459
+ /**
1460
+ * Retrieve the next result from a registered call and prepare it for
1461
+ * transmission back to the Polar VM.
1462
+ *
1463
+ * @internal
1464
+ */
1465
+ async nextCallResult(callId) {
1466
+ const call = __classPrivateFieldGet(this, _Query_calls, "f").get(callId);
1467
+ if (call === void 0)
1468
+ throw new Error("invalid call");
1469
+ const { done, value } = await call.next();
1470
+ if (done)
1471
+ return void 0;
1472
+ return __classPrivateFieldGet(this, _Query_host, "f").toPolar(value);
1473
+ }
1474
+ /**
1475
+ * Send application error back to the Polar VM.
1476
+ *
1477
+ * @internal
1478
+ */
1479
+ applicationError(message) {
1480
+ __classPrivateFieldGet(this, _Query_ffiQuery, "f").appError(message);
1481
+ }
1482
+ /**
1483
+ * Handle an external call on a relation.
1484
+ *
1485
+ * @internal
1486
+ */
1487
+ async handleRelation(receiver, rel) {
1488
+ const typ = __classPrivateFieldGet(this, _Query_host, "f").getType(rel.otherType);
1489
+ if (typ === void 0)
1490
+ throw new errors_1.UnregisteredClassError(rel.otherType);
1491
+ const value = receiver[rel.myField];
1492
+ const condition = {
1493
+ lhs: {
1494
+ typeName: rel.otherType,
1495
+ fieldName: rel.otherField
1496
+ },
1497
+ cmp: "Eq",
1498
+ rhs: { value }
1499
+ };
1500
+ const filter = {
1501
+ model: rel.otherType,
1502
+ relations: [],
1503
+ conditions: [[condition]],
1504
+ types: __classPrivateFieldGet(this, _Query_host, "f").types
1505
+ };
1506
+ const query = __classPrivateFieldGet(this, _Query_host, "f").adapter.buildQuery(filter);
1507
+ const results = await __classPrivateFieldGet(this, _Query_host, "f").adapter.executeQuery(query);
1508
+ if (rel.kind === "one") {
1509
+ if (results.length !== 1)
1510
+ throw new Error(`Wrong number of parents: ${results.length}`);
1511
+ return results[0];
1512
+ } else {
1513
+ return results;
1514
+ }
1515
+ }
1516
+ /**
1517
+ * Handle an application call.
1518
+ *
1519
+ * @internal
1520
+ */
1521
+ async handleCall(attr, callId, instance, args) {
1522
+ var _a, _b;
1523
+ let value;
1524
+ try {
1525
+ const receiver = await __classPrivateFieldGet(this, _Query_host, "f").toJs(instance);
1526
+ if (receiver === null || receiver === void 0)
1527
+ throw new (args ? errors_1.InvalidCallError : errors_1.InvalidAttributeError)(receiver, attr);
1528
+ const rel = (_b = (_a = __classPrivateFieldGet(this, _Query_host, "f").getType(receiver.constructor)) === null || _a === void 0 ? void 0 : _a.fields) === null || _b === void 0 ? void 0 : _b.get(attr);
1529
+ const self2 = receiver;
1530
+ if (rel instanceof filter_1.Relation)
1531
+ value = await this.handleRelation(self2, rel);
1532
+ else if (args) {
1533
+ if (typeof self2[attr] !== "function")
1534
+ throw new errors_1.InvalidCallError(receiver, attr);
1535
+ const jsArgs = await Promise.all(args.map((a) => __classPrivateFieldGet(this, _Query_host, "f").toJs(a)));
1536
+ value = self2[attr](...jsArgs);
1537
+ } else if (!(attr in self2))
1538
+ throw new errors_1.InvalidAttributeError(receiver, attr);
1539
+ else
1540
+ value = self2[attr];
1541
+ } catch (e) {
1542
+ if (e instanceof TypeError || e instanceof errors_1.InvalidCallError || e instanceof errors_1.InvalidAttributeError) {
1543
+ this.applicationError(e.message);
1544
+ } else {
1545
+ throw e;
1546
+ }
1547
+ } finally {
1548
+ value = await Promise.resolve(value);
1549
+ value = __classPrivateFieldGet(this, _Query_host, "f").toPolar(value);
1550
+ this.callResult(callId, value);
1551
+ }
1552
+ }
1553
+ async handleNextExternal(callId, iterable) {
1554
+ if (!__classPrivateFieldGet(this, _Query_calls, "f").has(callId)) {
1555
+ const value = await __classPrivateFieldGet(this, _Query_host, "f").toJs(iterable);
1556
+ const generator = (async function* () {
1557
+ if (types_1.isIterableIterator(value)) {
1558
+ yield* value;
1559
+ } else if (types_1.isAsyncIterable(value)) {
1560
+ for await (const result2 of value) {
1561
+ yield result2;
1562
+ }
1563
+ } else if (types_1.isIterable(value)) {
1564
+ for (const result2 of value) {
1565
+ yield result2;
1566
+ }
1567
+ } else {
1568
+ throw new errors_1.InvalidIteratorError(typeof value);
1569
+ }
1570
+ })();
1571
+ __classPrivateFieldGet(this, _Query_calls, "f").set(callId, generator);
1572
+ }
1573
+ const result = await this.nextCallResult(callId);
1574
+ this.callResult(callId, result);
1575
+ }
1576
+ /**
1577
+ * Create an `AsyncGenerator` that can be polled to advance the query loop.
1578
+ *
1579
+ * @internal
1580
+ */
1581
+ async *start() {
1582
+ try {
1583
+ while (true) {
1584
+ const nextEvent = __classPrivateFieldGet(this, _Query_ffiQuery, "f").nextEvent();
1585
+ this.processMessages();
1586
+ const event = helpers_1.parseQueryEvent(nextEvent);
1587
+ switch (event.kind) {
1588
+ case types_1.QueryEventKind.Done:
1589
+ return;
1590
+ case types_1.QueryEventKind.Result: {
1591
+ const { bindings } = event.data;
1592
+ const transformed = /* @__PURE__ */ new Map();
1593
+ for (const [k, v] of bindings) {
1594
+ transformed.set(k, await __classPrivateFieldGet(this, _Query_host, "f").toJs(v));
1595
+ }
1596
+ yield transformed;
1597
+ break;
1598
+ }
1599
+ case types_1.QueryEventKind.MakeExternal: {
1600
+ const { instanceId, tag, fields } = event.data;
1601
+ if (__classPrivateFieldGet(this, _Query_host, "f").hasInstance(instanceId))
1602
+ throw new errors_1.DuplicateInstanceRegistrationError(instanceId);
1603
+ await __classPrivateFieldGet(this, _Query_host, "f").makeInstance(tag, fields, instanceId);
1604
+ break;
1605
+ }
1606
+ case types_1.QueryEventKind.ExternalCall: {
1607
+ const { attribute, callId, instance, args } = event.data;
1608
+ await this.handleCall(attribute, callId, instance, args);
1609
+ break;
1610
+ }
1611
+ case types_1.QueryEventKind.ExternalIsSubspecializer: {
1612
+ const { instanceId, leftTag, rightTag, callId } = event.data;
1613
+ const answer = await __classPrivateFieldGet(this, _Query_host, "f").isSubspecializer(instanceId, leftTag, rightTag);
1614
+ this.questionResult(answer, callId);
1615
+ break;
1616
+ }
1617
+ case types_1.QueryEventKind.ExternalIsSubclass: {
1618
+ const { leftTag, rightTag, callId } = event.data;
1619
+ const answer = __classPrivateFieldGet(this, _Query_host, "f").isSubclass(leftTag, rightTag);
1620
+ this.questionResult(answer, callId);
1621
+ break;
1622
+ }
1623
+ case types_1.QueryEventKind.ExternalOp: {
1624
+ const { args, callId, operator } = event.data;
1625
+ const answer = await __classPrivateFieldGet(this, _Query_host, "f").externalOp(operator, args[0], args[1]);
1626
+ this.questionResult(answer, callId);
1627
+ break;
1628
+ }
1629
+ case types_1.QueryEventKind.ExternalIsa: {
1630
+ const { instance, tag, callId } = event.data;
1631
+ const answer = await __classPrivateFieldGet(this, _Query_host, "f").isa(instance, tag);
1632
+ this.questionResult(answer, callId);
1633
+ break;
1634
+ }
1635
+ case types_1.QueryEventKind.ExternalIsaWithPath: {
1636
+ const { baseTag, path, classTag, callId } = event.data;
1637
+ const answer = await __classPrivateFieldGet(this, _Query_host, "f").isaWithPath(baseTag, path, classTag);
1638
+ this.questionResult(answer, callId);
1639
+ break;
1640
+ }
1641
+ case types_1.QueryEventKind.NextExternal: {
1642
+ const { callId, iterable } = event.data;
1643
+ await this.handleNextExternal(callId, iterable);
1644
+ break;
1645
+ }
1646
+ case types_1.QueryEventKind.Debug: {
1647
+ if (typeof readline_1.createInterface !== "function") {
1648
+ console.warn("debug events not supported in browser Oso");
1649
+ break;
1650
+ }
1651
+ const { message } = event.data;
1652
+ if (message)
1653
+ console.log(message);
1654
+ readline_1.createInterface({
1655
+ input: process.stdin,
1656
+ output: process.stdout,
1657
+ prompt: "debug> ",
1658
+ tabSize: 4
1659
+ }).on("line", (line) => {
1660
+ const trimmed = line.trim().replace(/;+$/, "");
1661
+ const command = __classPrivateFieldGet(this, _Query_host, "f").toPolar(trimmed);
1662
+ __classPrivateFieldGet(this, _Query_ffiQuery, "f").debugCommand(JSON.stringify(command));
1663
+ this.processMessages();
1664
+ });
1665
+ break;
1666
+ }
1667
+ default: {
1668
+ const _ = event.kind;
1669
+ return _;
1670
+ }
1671
+ }
1672
+ }
1673
+ } finally {
1674
+ __classPrivateFieldGet(this, _Query_ffiQuery, "f").free();
1675
+ }
1676
+ }
1677
+ };
1678
+ exports2.Query = Query;
1679
+ _Query_ffiQuery = /* @__PURE__ */ new WeakMap(), _Query_calls = /* @__PURE__ */ new WeakMap(), _Query_host = /* @__PURE__ */ new WeakMap();
1680
+ }
1681
+ });
1682
+
1683
+ // node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/Expression.js
1684
+ var require_Expression = __commonJS({
1685
+ "node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/Expression.js"(exports2) {
1686
+ "use strict";
1687
+ Object.defineProperty(exports2, "__esModule", { value: true });
1688
+ exports2.Expression = void 0;
1689
+ var Expression = class {
1690
+ constructor(operator, args) {
1691
+ this.operator = operator;
1692
+ this.args = args;
1693
+ }
1694
+ };
1695
+ exports2.Expression = Expression;
1696
+ }
1697
+ });
1698
+
1699
+ // node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/Pattern.js
1700
+ var require_Pattern = __commonJS({
1701
+ "node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/Pattern.js"(exports2) {
1702
+ "use strict";
1703
+ Object.defineProperty(exports2, "__esModule", { value: true });
1704
+ exports2.Pattern = void 0;
1705
+ var Pattern = class {
1706
+ constructor({ tag, fields }) {
1707
+ this.tag = tag;
1708
+ this.fields = fields;
1709
+ }
1710
+ };
1711
+ exports2.Pattern = Pattern;
1712
+ }
1713
+ });
1714
+
1715
+ // node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/Predicate.js
1716
+ var require_Predicate = __commonJS({
1717
+ "node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/Predicate.js"(exports2) {
1718
+ "use strict";
1719
+ Object.defineProperty(exports2, "__esModule", { value: true });
1720
+ exports2.Predicate = void 0;
1721
+ var Predicate = class {
1722
+ constructor(name, args) {
1723
+ this.name = name;
1724
+ this.args = args;
1725
+ }
1726
+ };
1727
+ exports2.Predicate = Predicate;
1728
+ }
1729
+ });
1730
+
1731
+ // node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/Variable.js
1732
+ var require_Variable = __commonJS({
1733
+ "node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/Variable.js"(exports2) {
1734
+ "use strict";
1735
+ Object.defineProperty(exports2, "__esModule", { value: true });
1736
+ exports2.Variable = void 0;
1737
+ var Variable = class {
1738
+ constructor(name) {
1739
+ this.name = name;
1740
+ }
1741
+ };
1742
+ exports2.Variable = Variable;
1743
+ }
1744
+ });
1745
+
1746
+ // node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/Host.js
1747
+ var require_Host = __commonJS({
1748
+ "node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/Host.js"(exports2) {
1749
+ "use strict";
1750
+ var __classPrivateFieldSet = exports2 && exports2.__classPrivateFieldSet || function(receiver, state, value, kind, f) {
1751
+ if (kind === "m") throw new TypeError("Private method is not writable");
1752
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
1753
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
1754
+ return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
1755
+ };
1756
+ var __classPrivateFieldGet = exports2 && exports2.__classPrivateFieldGet || function(receiver, state, kind, f) {
1757
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
1758
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
1759
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
1760
+ };
1761
+ var _Host_ffiPolar;
1762
+ var _Host_instances;
1763
+ var _Host_opts;
1764
+ Object.defineProperty(exports2, "__esModule", { value: true });
1765
+ exports2.Host = void 0;
1766
+ var errors_1 = require_errors();
1767
+ var helpers_1 = require_helpers();
1768
+ var Expression_1 = require_Expression();
1769
+ var Pattern_1 = require_Pattern();
1770
+ var Predicate_1 = require_Predicate();
1771
+ var Variable_1 = require_Variable();
1772
+ var types_1 = require_types();
1773
+ var types_2 = require_types();
1774
+ var filter_1 = require_filter();
1775
+ var Host = class _Host {
1776
+ /** @internal */
1777
+ constructor(ffiPolar, opts) {
1778
+ _Host_ffiPolar.set(this, void 0);
1779
+ _Host_instances.set(this, void 0);
1780
+ _Host_opts.set(this, void 0);
1781
+ __classPrivateFieldSet(this, _Host_ffiPolar, ffiPolar, "f");
1782
+ __classPrivateFieldSet(this, _Host_opts, opts, "f");
1783
+ __classPrivateFieldSet(this, _Host_instances, /* @__PURE__ */ new Map(), "f");
1784
+ this.types = /* @__PURE__ */ new Map();
1785
+ this.adapter = {
1786
+ buildQuery: () => {
1787
+ throw new errors_1.DataFilteringConfigurationError();
1788
+ },
1789
+ executeQuery: () => {
1790
+ throw new errors_1.DataFilteringConfigurationError();
1791
+ }
1792
+ };
1793
+ }
1794
+ /**
1795
+ * Shallow clone a host to extend its state for the duration of a particular
1796
+ * query without modifying the longer-lived [[`Polar`]] host state.
1797
+ *
1798
+ * @internal
1799
+ */
1800
+ static clone(host, opts) {
1801
+ const options = { ...__classPrivateFieldGet(host, _Host_opts, "f"), ...opts };
1802
+ const clone = new _Host(__classPrivateFieldGet(host, _Host_ffiPolar, "f"), options);
1803
+ __classPrivateFieldSet(clone, _Host_instances, new Map(__classPrivateFieldGet(host, _Host_instances, "f")), "f");
1804
+ clone.types = new Map(host.types);
1805
+ clone.adapter = host.adapter;
1806
+ return clone;
1807
+ }
1808
+ /**
1809
+ * Fetch a JavaScript class from the class cache.
1810
+ *
1811
+ * @param name Class name to look up.
1812
+ *
1813
+ * @internal
1814
+ */
1815
+ getClass(name) {
1816
+ const typ = this.types.get(name);
1817
+ if (typ === void 0)
1818
+ throw new errors_1.UnregisteredClassError(name);
1819
+ return typ.cls;
1820
+ }
1821
+ /**
1822
+ * Get user type for `cls`.
1823
+ *
1824
+ * @param cls Class or class name.
1825
+ */
1826
+ getType(cls) {
1827
+ if (cls === void 0)
1828
+ return void 0;
1829
+ return this.types.get(cls);
1830
+ }
1831
+ /**
1832
+ * Return user types that are registered with Host.
1833
+ */
1834
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1835
+ *distinctUserTypes() {
1836
+ for (const [name, typ] of this.types)
1837
+ if (helpers_1.isString(name))
1838
+ yield typ;
1839
+ }
1840
+ serializeTypes() {
1841
+ var _a;
1842
+ const polarTypes = {};
1843
+ for (const [tag, userType] of this.types) {
1844
+ if (helpers_1.isString(tag)) {
1845
+ const fields = userType.fields;
1846
+ const fieldTypes = {};
1847
+ for (const [k, v] of fields) {
1848
+ if (v instanceof filter_1.Relation) {
1849
+ fieldTypes[k] = v.serialize();
1850
+ } else {
1851
+ const class_tag = (_a = this.getType(v)) === null || _a === void 0 ? void 0 : _a.name;
1852
+ if (class_tag === void 0)
1853
+ throw new errors_1.UnregisteredClassError(v.name);
1854
+ fieldTypes[k] = { Base: { class_tag } };
1855
+ }
1856
+ }
1857
+ polarTypes[tag] = fieldTypes;
1858
+ }
1859
+ }
1860
+ return polarTypes;
1861
+ }
1862
+ /**
1863
+ * Store a JavaScript class in the class cache.
1864
+ *
1865
+ * @param cls Class to cache.
1866
+ * @param params Optional parameters.
1867
+ *
1868
+ * @internal
1869
+ */
1870
+ cacheClass(cls, params) {
1871
+ params = params ? params : {};
1872
+ let fields = params.fields || {};
1873
+ if (!(fields instanceof Map))
1874
+ fields = new Map(Object.entries(fields));
1875
+ const { name } = params;
1876
+ if (!helpers_1.isConstructor(cls))
1877
+ throw new errors_1.InvalidConstructorError(cls);
1878
+ const clsName = name ? name : cls.name;
1879
+ const existing = this.types.get(clsName);
1880
+ if (existing) {
1881
+ throw new errors_1.DuplicateClassAliasError({
1882
+ name: clsName,
1883
+ cls,
1884
+ existing: existing.cls
1885
+ });
1886
+ }
1887
+ function defaultCheck(instance) {
1888
+ return instance instanceof cls || (instance === null || instance === void 0 ? void 0 : instance.constructor) === cls;
1889
+ }
1890
+ const userType = new types_1.UserType({
1891
+ name: clsName,
1892
+ cls,
1893
+ fields,
1894
+ id: this.cacheInstance(cls),
1895
+ isaCheck: params.isaCheck || defaultCheck
1896
+ });
1897
+ this.types.set(cls, userType);
1898
+ this.types.set(clsName, userType);
1899
+ return clsName;
1900
+ }
1901
+ /**
1902
+ * Return cached instances.
1903
+ *
1904
+ * Only used by the test suite.
1905
+ *
1906
+ * @internal
1907
+ */
1908
+ instances() {
1909
+ return Array.from(__classPrivateFieldGet(this, _Host_instances, "f").values());
1910
+ }
1911
+ /**
1912
+ * Check if an instance exists in the instance cache.
1913
+ *
1914
+ * @internal
1915
+ */
1916
+ hasInstance(id) {
1917
+ return __classPrivateFieldGet(this, _Host_instances, "f").has(id);
1918
+ }
1919
+ /**
1920
+ * Fetch a JavaScript instance from the instance cache.
1921
+ *
1922
+ * Public for the test suite.
1923
+ *
1924
+ * @internal
1925
+ */
1926
+ getInstance(id) {
1927
+ if (!this.hasInstance(id))
1928
+ throw new errors_1.UnregisteredInstanceError(id);
1929
+ return __classPrivateFieldGet(this, _Host_instances, "f").get(id);
1930
+ }
1931
+ /**
1932
+ * Store a JavaScript instance in the instance cache, fetching a new instance
1933
+ * ID from the Polar VM if an ID is not provided.
1934
+ *
1935
+ * @internal
1936
+ */
1937
+ cacheInstance(instance, id) {
1938
+ let instanceId = id;
1939
+ if (instanceId === void 0) {
1940
+ instanceId = __classPrivateFieldGet(this, _Host_ffiPolar, "f").newId();
1941
+ }
1942
+ __classPrivateFieldGet(this, _Host_instances, "f").set(instanceId, instance);
1943
+ return instanceId;
1944
+ }
1945
+ /**
1946
+ * Register the MROs of all registered classes.
1947
+ */
1948
+ registerMros() {
1949
+ for (const typ of this.distinctUserTypes()) {
1950
+ const mro = helpers_1.ancestors(typ.cls).map((c) => {
1951
+ var _a;
1952
+ return (_a = this.getType(c)) === null || _a === void 0 ? void 0 : _a.id;
1953
+ }).filter((id) => id !== void 0);
1954
+ __classPrivateFieldGet(this, _Host_ffiPolar, "f").registerMro(typ.name, mro);
1955
+ }
1956
+ }
1957
+ /**
1958
+ * Construct a JavaScript instance and store it in the instance cache.
1959
+ *
1960
+ * @internal
1961
+ */
1962
+ async makeInstance(name, fields, id) {
1963
+ const cls = this.getClass(name);
1964
+ const args = await Promise.all(fields.map((f) => this.toJs(f)));
1965
+ const instance = new cls(...args);
1966
+ this.cacheInstance(instance, id);
1967
+ }
1968
+ /**
1969
+ * Check if the left class is more specific than the right class with respect
1970
+ * to the given instance.
1971
+ *
1972
+ * @internal
1973
+ */
1974
+ async isSubspecializer(id, left, right) {
1975
+ let instance = this.getInstance(id);
1976
+ instance = instance instanceof Promise ? await instance : instance;
1977
+ const mro = helpers_1.ancestors(instance === null || instance === void 0 ? void 0 : instance.constructor);
1978
+ const leftIndex = mro.indexOf(this.getClass(left));
1979
+ const rightIndex = mro.indexOf(this.getClass(right));
1980
+ if (leftIndex === -1) {
1981
+ return false;
1982
+ } else if (rightIndex === -1) {
1983
+ return true;
1984
+ } else {
1985
+ return leftIndex < rightIndex;
1986
+ }
1987
+ }
1988
+ /**
1989
+ * Check if the left class is a subclass of the right class.
1990
+ *
1991
+ * @internal
1992
+ */
1993
+ isSubclass(left, right) {
1994
+ const leftCls = this.getClass(left);
1995
+ const rightCls = this.getClass(right);
1996
+ const mro = helpers_1.ancestors(leftCls);
1997
+ return mro.includes(rightCls);
1998
+ }
1999
+ /**
2000
+ * Check if the given instance is an instance of a particular class.
2001
+ *
2002
+ * @internal
2003
+ */
2004
+ async isa(polarInstance, name) {
2005
+ const instance = await this.toJs(polarInstance);
2006
+ const userType = this.types.get(name);
2007
+ if (userType !== void 0) {
2008
+ return userType.isaCheck(instance);
2009
+ } else {
2010
+ const cls = this.getClass(name);
2011
+ const inst = instance;
2012
+ return inst instanceof cls || (inst === null || inst === void 0 ? void 0 : inst.constructor) === cls;
2013
+ }
2014
+ }
2015
+ /**
2016
+ * Check if a sequence of field accesses on the given class is an
2017
+ * instance of another class.
2018
+ *
2019
+ * @internal
2020
+ */
2021
+ async isaWithPath(baseTag, path, classTag) {
2022
+ var _a;
2023
+ let tag = baseTag;
2024
+ for (const fld of path) {
2025
+ const field = await this.toJs(fld);
2026
+ if (!helpers_1.isString(field))
2027
+ throw new Error(`Not a field name: ${helpers_1.repr(field)}`);
2028
+ const userType = this.types.get(tag);
2029
+ if (userType === void 0)
2030
+ return false;
2031
+ let fieldType = userType.fields.get(field);
2032
+ if (fieldType === void 0)
2033
+ return false;
2034
+ if (fieldType instanceof filter_1.Relation) {
2035
+ switch (fieldType.kind) {
2036
+ case "one": {
2037
+ const otherCls = (_a = this.getType(fieldType.otherType)) === null || _a === void 0 ? void 0 : _a.cls;
2038
+ if (otherCls === void 0)
2039
+ throw new errors_1.UnregisteredClassError(fieldType.otherType);
2040
+ fieldType = otherCls;
2041
+ break;
2042
+ }
2043
+ case "many":
2044
+ fieldType = Array;
2045
+ break;
2046
+ }
2047
+ }
2048
+ const newBase = this.getType(fieldType);
2049
+ if (newBase === void 0)
2050
+ return false;
2051
+ tag = newBase.name;
2052
+ }
2053
+ return classTag === tag;
2054
+ }
2055
+ /**
2056
+ * Check if the given instances conform to the operator.
2057
+ *
2058
+ * @internal
2059
+ */
2060
+ async externalOp(op, leftTerm, rightTerm) {
2061
+ const left = await this.toJs(leftTerm);
2062
+ const right = await this.toJs(rightTerm);
2063
+ switch (op) {
2064
+ case "Eq":
2065
+ return __classPrivateFieldGet(this, _Host_opts, "f").equalityFn(left, right);
2066
+ case "Geq":
2067
+ return left >= right;
2068
+ case "Gt":
2069
+ return left > right;
2070
+ case "Leq":
2071
+ return left <= right;
2072
+ case "Lt":
2073
+ return left < right;
2074
+ case "Neq":
2075
+ return !__classPrivateFieldGet(this, _Host_opts, "f").equalityFn(left, right);
2076
+ default: {
2077
+ const _ = op;
2078
+ return _;
2079
+ }
2080
+ }
2081
+ }
2082
+ /**
2083
+ * Turn a JavaScript value into a Polar term that's ready to be sent to the
2084
+ * Polar VM.
2085
+ *
2086
+ * @internal
2087
+ */
2088
+ toPolar(v) {
2089
+ var _a, _b, _c, _d;
2090
+ switch (true) {
2091
+ case typeof v === "boolean":
2092
+ return { value: { Boolean: v } };
2093
+ case Number.isInteger(v):
2094
+ return { value: { Number: { Integer: v } } };
2095
+ case typeof v === "number":
2096
+ if (v === Infinity) {
2097
+ v = "Infinity";
2098
+ } else if (v === -Infinity) {
2099
+ v = "-Infinity";
2100
+ } else if (Number.isNaN(v)) {
2101
+ v = "NaN";
2102
+ }
2103
+ return { value: { Number: { Float: v } } };
2104
+ case helpers_1.isString(v):
2105
+ return { value: { String: v } };
2106
+ case Array.isArray(v): {
2107
+ const polarTermList = v.map((a) => this.toPolar(a));
2108
+ return { value: { List: polarTermList } };
2109
+ }
2110
+ case v instanceof Predicate_1.Predicate: {
2111
+ const { name, args } = v;
2112
+ const polarArgs = args.map((a) => this.toPolar(a));
2113
+ return { value: { Call: { name, args: polarArgs } } };
2114
+ }
2115
+ case v instanceof Variable_1.Variable:
2116
+ return { value: { Variable: v.name } };
2117
+ case v instanceof Expression_1.Expression: {
2118
+ const { operator, args } = v;
2119
+ const polarArgs = args.map((a) => this.toPolar(a));
2120
+ return { value: { Expression: { operator, args: polarArgs } } };
2121
+ }
2122
+ case v instanceof Pattern_1.Pattern: {
2123
+ const { tag, fields } = v;
2124
+ let dict = this.toPolar(fields).value;
2125
+ if (!types_2.isPolarDict(dict))
2126
+ dict = { Dictionary: { fields: /* @__PURE__ */ new Map() } };
2127
+ if (tag === void 0)
2128
+ return { value: { Pattern: dict } };
2129
+ return {
2130
+ value: { Pattern: { Instance: { tag, fields: dict.Dictionary } } }
2131
+ };
2132
+ }
2133
+ case v instanceof types_2.Dict: {
2134
+ const fields = new Map(Object.entries(v).map(([k, v2]) => [k, this.toPolar(v2)]));
2135
+ return { value: { Dictionary: { fields } } };
2136
+ }
2137
+ default: {
2138
+ let instanceId = void 0;
2139
+ let classId = void 0;
2140
+ const v_cast = v;
2141
+ let classRepr = void 0;
2142
+ if (helpers_1.isConstructor(v)) {
2143
+ instanceId = (_a = this.getType(v)) === null || _a === void 0 ? void 0 : _a.id;
2144
+ classId = instanceId;
2145
+ classRepr = (_b = this.getType(v)) === null || _b === void 0 ? void 0 : _b.name;
2146
+ } else {
2147
+ const v_constructor = v_cast === null || v_cast === void 0 ? void 0 : v_cast.constructor;
2148
+ if (v_constructor !== void 0 && this.types.has(v_constructor)) {
2149
+ classId = (_c = this.getType(v_constructor)) === null || _c === void 0 ? void 0 : _c.id;
2150
+ classRepr = (_d = this.getType(v_constructor)) === null || _d === void 0 ? void 0 : _d.name;
2151
+ }
2152
+ }
2153
+ if (classRepr !== void 0 && !this.types.has(classRepr)) {
2154
+ classRepr = void 0;
2155
+ }
2156
+ const instance_id = this.cacheInstance(v, instanceId);
2157
+ return {
2158
+ value: {
2159
+ ExternalInstance: {
2160
+ instance_id,
2161
+ constructor: void 0,
2162
+ repr: helpers_1.repr(v),
2163
+ class_repr: classRepr,
2164
+ class_id: classId
2165
+ }
2166
+ }
2167
+ };
2168
+ }
2169
+ }
2170
+ }
2171
+ /**
2172
+ * Turn a Polar term from the Polar VM into a JavaScript value.
2173
+ *
2174
+ * @internal
2175
+ */
2176
+ async toJs(v) {
2177
+ const t = v.value;
2178
+ if (types_2.isPolarStr(t)) {
2179
+ return t.String;
2180
+ } else if (types_2.isPolarNum(t)) {
2181
+ if ("Float" in t.Number) {
2182
+ const f = t.Number.Float;
2183
+ switch (f) {
2184
+ case "Infinity":
2185
+ return Infinity;
2186
+ case "-Infinity":
2187
+ return -Infinity;
2188
+ case "NaN":
2189
+ return NaN;
2190
+ default:
2191
+ if (typeof f !== "number")
2192
+ throw new errors_1.PolarError('Expected a floating point number, got "' + f + '"');
2193
+ return f;
2194
+ }
2195
+ } else {
2196
+ return t.Number.Integer;
2197
+ }
2198
+ } else if (types_2.isPolarBool(t)) {
2199
+ return t.Boolean;
2200
+ } else if (types_2.isPolarList(t)) {
2201
+ return await Promise.all(t.List.map(async (el) => await this.toJs(el)));
2202
+ } else if (types_2.isPolarDict(t)) {
2203
+ const valueToJs = ([k, v2]) => this.toJs(v2).then((v3) => [k, v3]);
2204
+ const { fields } = t.Dictionary;
2205
+ const entries = await Promise.all([...fields.entries()].map(valueToJs));
2206
+ return entries.reduce((dict, [k, v2]) => {
2207
+ dict[k] = v2;
2208
+ return dict;
2209
+ }, new types_2.Dict({}));
2210
+ } else if (types_2.isPolarInstance(t)) {
2211
+ const i = this.getInstance(t.ExternalInstance.instance_id);
2212
+ return i instanceof Promise ? await i : i;
2213
+ } else if (types_2.isPolarPredicate(t)) {
2214
+ const { name, args } = t.Call;
2215
+ const jsArgs = await Promise.all(args.map((a) => this.toJs(a)));
2216
+ return new Predicate_1.Predicate(name, jsArgs);
2217
+ } else if (types_2.isPolarVariable(t)) {
2218
+ return new Variable_1.Variable(t.Variable);
2219
+ } else if (types_2.isPolarExpression(t)) {
2220
+ if (!__classPrivateFieldGet(this, _Host_opts, "f").acceptExpression)
2221
+ throw new errors_1.UnexpectedExpressionError();
2222
+ const { operator, args: argTerms } = t.Expression;
2223
+ const args = await Promise.all(argTerms.map((a) => this.toJs(a)));
2224
+ return new Expression_1.Expression(operator, args);
2225
+ } else if (types_2.isPolarPattern(t)) {
2226
+ if ("Dictionary" in t.Pattern) {
2227
+ const fields = await this.toJs({ value: t.Pattern });
2228
+ return new Pattern_1.Pattern({ fields });
2229
+ } else {
2230
+ const { tag, fields: { fields } } = t.Pattern.Instance;
2231
+ const dict = await this.toJs({ value: { Dictionary: { fields } } });
2232
+ return new Pattern_1.Pattern({ tag, fields: dict });
2233
+ }
2234
+ } else {
2235
+ const _ = t;
2236
+ return _;
2237
+ }
2238
+ }
2239
+ };
2240
+ exports2.Host = Host;
2241
+ _Host_ffiPolar = /* @__PURE__ */ new WeakMap(), _Host_instances = /* @__PURE__ */ new WeakMap(), _Host_opts = /* @__PURE__ */ new WeakMap();
2242
+ }
2243
+ });
2244
+
2245
+ // node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/polar_wasm_api.js
2246
+ var require_polar_wasm_api = __commonJS({
2247
+ "node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/polar_wasm_api.js"(exports2, module2) {
2248
+ "use strict";
2249
+ var imports = {};
2250
+ imports["__wbindgen_placeholder__"] = module2.exports;
2251
+ var wasm;
2252
+ var { TextEncoder, TextDecoder } = require("util");
2253
+ var heap = new Array(32).fill(void 0);
2254
+ heap.push(void 0, null, true, false);
2255
+ function getObject(idx) {
2256
+ return heap[idx];
2257
+ }
2258
+ var WASM_VECTOR_LEN = 0;
2259
+ var cachedUint8Memory0 = new Uint8Array();
2260
+ function getUint8Memory0() {
2261
+ if (cachedUint8Memory0.byteLength === 0) {
2262
+ cachedUint8Memory0 = new Uint8Array(wasm.memory.buffer);
2263
+ }
2264
+ return cachedUint8Memory0;
2265
+ }
2266
+ var cachedTextEncoder = new TextEncoder("utf-8");
2267
+ var encodeString = typeof cachedTextEncoder.encodeInto === "function" ? function(arg, view) {
2268
+ return cachedTextEncoder.encodeInto(arg, view);
2269
+ } : function(arg, view) {
2270
+ const buf = cachedTextEncoder.encode(arg);
2271
+ view.set(buf);
2272
+ return {
2273
+ read: arg.length,
2274
+ written: buf.length
2275
+ };
2276
+ };
2277
+ function passStringToWasm0(arg, malloc, realloc) {
2278
+ if (realloc === void 0) {
2279
+ const buf = cachedTextEncoder.encode(arg);
2280
+ const ptr2 = malloc(buf.length);
2281
+ getUint8Memory0().subarray(ptr2, ptr2 + buf.length).set(buf);
2282
+ WASM_VECTOR_LEN = buf.length;
2283
+ return ptr2;
2284
+ }
2285
+ let len = arg.length;
2286
+ let ptr = malloc(len);
2287
+ const mem = getUint8Memory0();
2288
+ let offset = 0;
2289
+ for (; offset < len; offset++) {
2290
+ const code = arg.charCodeAt(offset);
2291
+ if (code > 127) break;
2292
+ mem[ptr + offset] = code;
2293
+ }
2294
+ if (offset !== len) {
2295
+ if (offset !== 0) {
2296
+ arg = arg.slice(offset);
2297
+ }
2298
+ ptr = realloc(ptr, len, len = offset + arg.length * 3);
2299
+ const view = getUint8Memory0().subarray(ptr + offset, ptr + len);
2300
+ const ret = encodeString(arg, view);
2301
+ offset += ret.written;
2302
+ }
2303
+ WASM_VECTOR_LEN = offset;
2304
+ return ptr;
2305
+ }
2306
+ function isLikeNone(x) {
2307
+ return x === void 0 || x === null;
2308
+ }
2309
+ var cachedInt32Memory0 = new Int32Array();
2310
+ function getInt32Memory0() {
2311
+ if (cachedInt32Memory0.byteLength === 0) {
2312
+ cachedInt32Memory0 = new Int32Array(wasm.memory.buffer);
2313
+ }
2314
+ return cachedInt32Memory0;
2315
+ }
2316
+ var heap_next = heap.length;
2317
+ function dropObject(idx) {
2318
+ if (idx < 36) return;
2319
+ heap[idx] = heap_next;
2320
+ heap_next = idx;
2321
+ }
2322
+ function takeObject(idx) {
2323
+ const ret = getObject(idx);
2324
+ dropObject(idx);
2325
+ return ret;
2326
+ }
2327
+ var cachedFloat64Memory0 = new Float64Array();
2328
+ function getFloat64Memory0() {
2329
+ if (cachedFloat64Memory0.byteLength === 0) {
2330
+ cachedFloat64Memory0 = new Float64Array(wasm.memory.buffer);
2331
+ }
2332
+ return cachedFloat64Memory0;
2333
+ }
2334
+ function addHeapObject(obj) {
2335
+ if (heap_next === heap.length) heap.push(heap.length + 1);
2336
+ const idx = heap_next;
2337
+ heap_next = heap[idx];
2338
+ heap[idx] = obj;
2339
+ return idx;
2340
+ }
2341
+ var cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true });
2342
+ cachedTextDecoder.decode();
2343
+ function getStringFromWasm0(ptr, len) {
2344
+ return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len));
2345
+ }
2346
+ function debugString(val) {
2347
+ const type = typeof val;
2348
+ if (type == "number" || type == "boolean" || val == null) {
2349
+ return `${val}`;
2350
+ }
2351
+ if (type == "string") {
2352
+ return `"${val}"`;
2353
+ }
2354
+ if (type == "symbol") {
2355
+ const description = val.description;
2356
+ if (description == null) {
2357
+ return "Symbol";
2358
+ } else {
2359
+ return `Symbol(${description})`;
2360
+ }
2361
+ }
2362
+ if (type == "function") {
2363
+ const name = val.name;
2364
+ if (typeof name == "string" && name.length > 0) {
2365
+ return `Function(${name})`;
2366
+ } else {
2367
+ return "Function";
2368
+ }
2369
+ }
2370
+ if (Array.isArray(val)) {
2371
+ const length = val.length;
2372
+ let debug = "[";
2373
+ if (length > 0) {
2374
+ debug += debugString(val[0]);
2375
+ }
2376
+ for (let i = 1; i < length; i++) {
2377
+ debug += ", " + debugString(val[i]);
2378
+ }
2379
+ debug += "]";
2380
+ return debug;
2381
+ }
2382
+ const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val));
2383
+ let className;
2384
+ if (builtInMatches.length > 1) {
2385
+ className = builtInMatches[1];
2386
+ } else {
2387
+ return toString.call(val);
2388
+ }
2389
+ if (className == "Object") {
2390
+ try {
2391
+ return "Object(" + JSON.stringify(val) + ")";
2392
+ } catch (_) {
2393
+ return "Object";
2394
+ }
2395
+ }
2396
+ if (val instanceof Error) {
2397
+ return `${val.name}: ${val.message}
2398
+ ${val.stack}`;
2399
+ }
2400
+ return className;
2401
+ }
2402
+ function handleError(f, args) {
2403
+ try {
2404
+ return f.apply(this, args);
2405
+ } catch (e) {
2406
+ wasm.__wbindgen_exn_store(addHeapObject(e));
2407
+ }
2408
+ }
2409
+ var Polar = class _Polar {
2410
+ static __wrap(ptr) {
2411
+ const obj = Object.create(_Polar.prototype);
2412
+ obj.ptr = ptr;
2413
+ return obj;
2414
+ }
2415
+ __destroy_into_raw() {
2416
+ const ptr = this.ptr;
2417
+ this.ptr = 0;
2418
+ return ptr;
2419
+ }
2420
+ free() {
2421
+ const ptr = this.__destroy_into_raw();
2422
+ wasm.__wbg_polar_free(ptr);
2423
+ }
2424
+ /**
2425
+ */
2426
+ constructor() {
2427
+ const ret = wasm.polar_wasm_new();
2428
+ return _Polar.__wrap(ret);
2429
+ }
2430
+ /**
2431
+ * @param {any} sources
2432
+ */
2433
+ load(sources) {
2434
+ try {
2435
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
2436
+ wasm.polar_load(retptr, this.ptr, addHeapObject(sources));
2437
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
2438
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
2439
+ if (r1) {
2440
+ throw takeObject(r0);
2441
+ }
2442
+ } finally {
2443
+ wasm.__wbindgen_add_to_stack_pointer(16);
2444
+ }
2445
+ }
2446
+ /**
2447
+ */
2448
+ clearRules() {
2449
+ wasm.polar_clearRules(this.ptr);
2450
+ }
2451
+ /**
2452
+ * @param {string} name
2453
+ * @param {any} term
2454
+ */
2455
+ registerConstant(name, term) {
2456
+ try {
2457
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
2458
+ const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
2459
+ const len0 = WASM_VECTOR_LEN;
2460
+ wasm.polar_registerConstant(retptr, this.ptr, ptr0, len0, addHeapObject(term));
2461
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
2462
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
2463
+ if (r1) {
2464
+ throw takeObject(r0);
2465
+ }
2466
+ } finally {
2467
+ wasm.__wbindgen_add_to_stack_pointer(16);
2468
+ }
2469
+ }
2470
+ /**
2471
+ * @returns {Query | undefined}
2472
+ */
2473
+ nextInlineQuery() {
2474
+ const ret = wasm.polar_nextInlineQuery(this.ptr);
2475
+ return ret === 0 ? void 0 : Query.__wrap(ret);
2476
+ }
2477
+ /**
2478
+ * @param {string} src
2479
+ * @returns {Query}
2480
+ */
2481
+ newQueryFromStr(src) {
2482
+ try {
2483
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
2484
+ const ptr0 = passStringToWasm0(src, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
2485
+ const len0 = WASM_VECTOR_LEN;
2486
+ wasm.polar_newQueryFromStr(retptr, this.ptr, ptr0, len0);
2487
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
2488
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
2489
+ var r2 = getInt32Memory0()[retptr / 4 + 2];
2490
+ if (r2) {
2491
+ throw takeObject(r1);
2492
+ }
2493
+ return Query.__wrap(r0);
2494
+ } finally {
2495
+ wasm.__wbindgen_add_to_stack_pointer(16);
2496
+ }
2497
+ }
2498
+ /**
2499
+ * @param {any} term
2500
+ * @returns {Query}
2501
+ */
2502
+ newQueryFromTerm(term) {
2503
+ try {
2504
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
2505
+ wasm.polar_newQueryFromTerm(retptr, this.ptr, addHeapObject(term));
2506
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
2507
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
2508
+ var r2 = getInt32Memory0()[retptr / 4 + 2];
2509
+ if (r2) {
2510
+ throw takeObject(r1);
2511
+ }
2512
+ return Query.__wrap(r0);
2513
+ } finally {
2514
+ wasm.__wbindgen_add_to_stack_pointer(16);
2515
+ }
2516
+ }
2517
+ /**
2518
+ * @returns {number}
2519
+ */
2520
+ newId() {
2521
+ const ret = wasm.polar_newId(this.ptr);
2522
+ return ret;
2523
+ }
2524
+ /**
2525
+ * @returns {any}
2526
+ */
2527
+ nextMessage() {
2528
+ try {
2529
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
2530
+ wasm.polar_nextMessage(retptr, this.ptr);
2531
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
2532
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
2533
+ var r2 = getInt32Memory0()[retptr / 4 + 2];
2534
+ if (r2) {
2535
+ throw takeObject(r1);
2536
+ }
2537
+ return takeObject(r0);
2538
+ } finally {
2539
+ wasm.__wbindgen_add_to_stack_pointer(16);
2540
+ }
2541
+ }
2542
+ /**
2543
+ * @param {string} name
2544
+ * @param {any} mro
2545
+ */
2546
+ registerMro(name, mro) {
2547
+ try {
2548
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
2549
+ const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
2550
+ const len0 = WASM_VECTOR_LEN;
2551
+ wasm.polar_registerMro(retptr, this.ptr, ptr0, len0, addHeapObject(mro));
2552
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
2553
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
2554
+ if (r1) {
2555
+ throw takeObject(r0);
2556
+ }
2557
+ } finally {
2558
+ wasm.__wbindgen_add_to_stack_pointer(16);
2559
+ }
2560
+ }
2561
+ /**
2562
+ * @param {any} types
2563
+ * @param {any} partial_results
2564
+ * @param {string} variable
2565
+ * @param {string} class_tag
2566
+ * @returns {any}
2567
+ */
2568
+ buildDataFilter(types, partial_results, variable, class_tag) {
2569
+ try {
2570
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
2571
+ const ptr0 = passStringToWasm0(variable, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
2572
+ const len0 = WASM_VECTOR_LEN;
2573
+ const ptr1 = passStringToWasm0(class_tag, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
2574
+ const len1 = WASM_VECTOR_LEN;
2575
+ wasm.polar_buildDataFilter(retptr, this.ptr, addHeapObject(types), addHeapObject(partial_results), ptr0, len0, ptr1, len1);
2576
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
2577
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
2578
+ var r2 = getInt32Memory0()[retptr / 4 + 2];
2579
+ if (r2) {
2580
+ throw takeObject(r1);
2581
+ }
2582
+ return takeObject(r0);
2583
+ } finally {
2584
+ wasm.__wbindgen_add_to_stack_pointer(16);
2585
+ }
2586
+ }
2587
+ /**
2588
+ * @param {boolean} ignore_no_allow_warning
2589
+ */
2590
+ setIgnoreNoAllowWarning(ignore_no_allow_warning) {
2591
+ wasm.polar_setIgnoreNoAllowWarning(this.ptr, ignore_no_allow_warning);
2592
+ }
2593
+ };
2594
+ module2.exports.Polar = Polar;
2595
+ var Query = class _Query {
2596
+ static __wrap(ptr) {
2597
+ const obj = Object.create(_Query.prototype);
2598
+ obj.ptr = ptr;
2599
+ return obj;
2600
+ }
2601
+ __destroy_into_raw() {
2602
+ const ptr = this.ptr;
2603
+ this.ptr = 0;
2604
+ return ptr;
2605
+ }
2606
+ free() {
2607
+ const ptr = this.__destroy_into_raw();
2608
+ wasm.__wbg_query_free(ptr);
2609
+ }
2610
+ /**
2611
+ * @returns {any}
2612
+ */
2613
+ nextEvent() {
2614
+ try {
2615
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
2616
+ wasm.query_nextEvent(retptr, this.ptr);
2617
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
2618
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
2619
+ var r2 = getInt32Memory0()[retptr / 4 + 2];
2620
+ if (r2) {
2621
+ throw takeObject(r1);
2622
+ }
2623
+ return takeObject(r0);
2624
+ } finally {
2625
+ wasm.__wbindgen_add_to_stack_pointer(16);
2626
+ }
2627
+ }
2628
+ /**
2629
+ * @param {number} call_id
2630
+ * @param {any} term
2631
+ */
2632
+ callResult(call_id, term) {
2633
+ try {
2634
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
2635
+ wasm.query_callResult(retptr, this.ptr, call_id, addHeapObject(term));
2636
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
2637
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
2638
+ if (r1) {
2639
+ throw takeObject(r0);
2640
+ }
2641
+ } finally {
2642
+ wasm.__wbindgen_add_to_stack_pointer(16);
2643
+ }
2644
+ }
2645
+ /**
2646
+ * @param {number} call_id
2647
+ * @param {boolean} result
2648
+ */
2649
+ questionResult(call_id, result) {
2650
+ try {
2651
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
2652
+ wasm.query_questionResult(retptr, this.ptr, call_id, result);
2653
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
2654
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
2655
+ if (r1) {
2656
+ throw takeObject(r0);
2657
+ }
2658
+ } finally {
2659
+ wasm.__wbindgen_add_to_stack_pointer(16);
2660
+ }
2661
+ }
2662
+ /**
2663
+ * @param {string} command
2664
+ */
2665
+ debugCommand(command) {
2666
+ try {
2667
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
2668
+ const ptr0 = passStringToWasm0(command, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
2669
+ const len0 = WASM_VECTOR_LEN;
2670
+ wasm.query_debugCommand(retptr, this.ptr, ptr0, len0);
2671
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
2672
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
2673
+ if (r1) {
2674
+ throw takeObject(r0);
2675
+ }
2676
+ } finally {
2677
+ wasm.__wbindgen_add_to_stack_pointer(16);
2678
+ }
2679
+ }
2680
+ /**
2681
+ * @param {string} msg
2682
+ */
2683
+ appError(msg) {
2684
+ try {
2685
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
2686
+ const ptr0 = passStringToWasm0(msg, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
2687
+ const len0 = WASM_VECTOR_LEN;
2688
+ wasm.query_appError(retptr, this.ptr, ptr0, len0);
2689
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
2690
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
2691
+ if (r1) {
2692
+ throw takeObject(r0);
2693
+ }
2694
+ } finally {
2695
+ wasm.__wbindgen_add_to_stack_pointer(16);
2696
+ }
2697
+ }
2698
+ /**
2699
+ * @returns {any}
2700
+ */
2701
+ nextMessage() {
2702
+ try {
2703
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
2704
+ wasm.query_nextMessage(retptr, this.ptr);
2705
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
2706
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
2707
+ var r2 = getInt32Memory0()[retptr / 4 + 2];
2708
+ if (r2) {
2709
+ throw takeObject(r1);
2710
+ }
2711
+ return takeObject(r0);
2712
+ } finally {
2713
+ wasm.__wbindgen_add_to_stack_pointer(16);
2714
+ }
2715
+ }
2716
+ /**
2717
+ * @returns {string}
2718
+ */
2719
+ source() {
2720
+ try {
2721
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
2722
+ wasm.query_source(retptr, this.ptr);
2723
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
2724
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
2725
+ return getStringFromWasm0(r0, r1);
2726
+ } finally {
2727
+ wasm.__wbindgen_add_to_stack_pointer(16);
2728
+ wasm.__wbindgen_free(r0, r1);
2729
+ }
2730
+ }
2731
+ /**
2732
+ * @param {string} name
2733
+ * @param {any} term
2734
+ */
2735
+ bind(name, term) {
2736
+ try {
2737
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
2738
+ const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
2739
+ const len0 = WASM_VECTOR_LEN;
2740
+ wasm.query_bind(retptr, this.ptr, ptr0, len0, addHeapObject(term));
2741
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
2742
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
2743
+ if (r1) {
2744
+ throw takeObject(r0);
2745
+ }
2746
+ } finally {
2747
+ wasm.__wbindgen_add_to_stack_pointer(16);
2748
+ }
2749
+ }
2750
+ /**
2751
+ * @param {string | undefined} rust_log
2752
+ * @param {string | undefined} polar_log
2753
+ */
2754
+ setLoggingOptions(rust_log, polar_log) {
2755
+ var ptr0 = isLikeNone(rust_log) ? 0 : passStringToWasm0(rust_log, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
2756
+ var len0 = WASM_VECTOR_LEN;
2757
+ var ptr1 = isLikeNone(polar_log) ? 0 : passStringToWasm0(polar_log, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
2758
+ var len1 = WASM_VECTOR_LEN;
2759
+ wasm.query_setLoggingOptions(this.ptr, ptr0, len0, ptr1, len1);
2760
+ }
2761
+ };
2762
+ module2.exports.Query = Query;
2763
+ module2.exports.__wbindgen_string_get = function(arg0, arg1) {
2764
+ const obj = getObject(arg1);
2765
+ const ret = typeof obj === "string" ? obj : void 0;
2766
+ var ptr0 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
2767
+ var len0 = WASM_VECTOR_LEN;
2768
+ getInt32Memory0()[arg0 / 4 + 1] = len0;
2769
+ getInt32Memory0()[arg0 / 4 + 0] = ptr0;
2770
+ };
2771
+ module2.exports.__wbindgen_object_drop_ref = function(arg0) {
2772
+ takeObject(arg0);
2773
+ };
2774
+ module2.exports.__wbindgen_boolean_get = function(arg0) {
2775
+ const v = getObject(arg0);
2776
+ const ret = typeof v === "boolean" ? v ? 1 : 0 : 2;
2777
+ return ret;
2778
+ };
2779
+ module2.exports.__wbindgen_number_get = function(arg0, arg1) {
2780
+ const obj = getObject(arg1);
2781
+ const ret = typeof obj === "number" ? obj : void 0;
2782
+ getFloat64Memory0()[arg0 / 8 + 1] = isLikeNone(ret) ? 0 : ret;
2783
+ getInt32Memory0()[arg0 / 4 + 0] = !isLikeNone(ret);
2784
+ };
2785
+ module2.exports.__wbindgen_is_object = function(arg0) {
2786
+ const val = getObject(arg0);
2787
+ const ret = typeof val === "object" && val !== null;
2788
+ return ret;
2789
+ };
2790
+ module2.exports.__wbindgen_is_string = function(arg0) {
2791
+ const ret = typeof getObject(arg0) === "string";
2792
+ return ret;
2793
+ };
2794
+ module2.exports.__wbindgen_is_null = function(arg0) {
2795
+ const ret = getObject(arg0) === null;
2796
+ return ret;
2797
+ };
2798
+ module2.exports.__wbindgen_is_undefined = function(arg0) {
2799
+ const ret = getObject(arg0) === void 0;
2800
+ return ret;
2801
+ };
2802
+ module2.exports.__wbindgen_number_new = function(arg0) {
2803
+ const ret = arg0;
2804
+ return addHeapObject(ret);
2805
+ };
2806
+ module2.exports.__wbindgen_object_clone_ref = function(arg0) {
2807
+ const ret = getObject(arg0);
2808
+ return addHeapObject(ret);
2809
+ };
2810
+ module2.exports.__wbindgen_string_new = function(arg0, arg1) {
2811
+ const ret = getStringFromWasm0(arg0, arg1);
2812
+ return addHeapObject(ret);
2813
+ };
2814
+ module2.exports.__wbg_String_9aa17d6248d519a5 = function(arg0, arg1) {
2815
+ const ret = String(getObject(arg1));
2816
+ const ptr0 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
2817
+ const len0 = WASM_VECTOR_LEN;
2818
+ getInt32Memory0()[arg0 / 4 + 1] = len0;
2819
+ getInt32Memory0()[arg0 / 4 + 0] = ptr0;
2820
+ };
2821
+ module2.exports.__wbg_get_723f83ba0c34871a = function(arg0, arg1) {
2822
+ const ret = getObject(arg0)[takeObject(arg1)];
2823
+ return addHeapObject(ret);
2824
+ };
2825
+ module2.exports.__wbg_set_ce5827ace4c694dc = function(arg0, arg1, arg2) {
2826
+ getObject(arg0)[takeObject(arg1)] = takeObject(arg2);
2827
+ };
2828
+ module2.exports.__wbg_new_abda76e883ba8a5f = function() {
2829
+ const ret = new Error();
2830
+ return addHeapObject(ret);
2831
+ };
2832
+ module2.exports.__wbg_stack_658279fe44541cf6 = function(arg0, arg1) {
2833
+ const ret = getObject(arg1).stack;
2834
+ const ptr0 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
2835
+ const len0 = WASM_VECTOR_LEN;
2836
+ getInt32Memory0()[arg0 / 4 + 1] = len0;
2837
+ getInt32Memory0()[arg0 / 4 + 0] = ptr0;
2838
+ };
2839
+ module2.exports.__wbg_error_f851667af71bcfc6 = function(arg0, arg1) {
2840
+ try {
2841
+ console.error(getStringFromWasm0(arg0, arg1));
2842
+ } finally {
2843
+ wasm.__wbindgen_free(arg0, arg1);
2844
+ }
2845
+ };
2846
+ module2.exports.__wbg_error_06ae29e21839d332 = function(arg0, arg1) {
2847
+ console.error(getStringFromWasm0(arg0, arg1));
2848
+ };
2849
+ module2.exports.__wbg_get_57245cc7d7c7619d = function(arg0, arg1) {
2850
+ const ret = getObject(arg0)[arg1 >>> 0];
2851
+ return addHeapObject(ret);
2852
+ };
2853
+ module2.exports.__wbg_length_6e3bbe7c8bd4dbd8 = function(arg0) {
2854
+ const ret = getObject(arg0).length;
2855
+ return ret;
2856
+ };
2857
+ module2.exports.__wbg_new_1d9a920c6bfc44a8 = function() {
2858
+ const ret = new Array();
2859
+ return addHeapObject(ret);
2860
+ };
2861
+ module2.exports.__wbindgen_is_function = function(arg0) {
2862
+ const ret = typeof getObject(arg0) === "function";
2863
+ return ret;
2864
+ };
2865
+ module2.exports.__wbg_new_268f7b7dd3430798 = function() {
2866
+ const ret = /* @__PURE__ */ new Map();
2867
+ return addHeapObject(ret);
2868
+ };
2869
+ module2.exports.__wbg_next_579e583d33566a86 = function(arg0) {
2870
+ const ret = getObject(arg0).next;
2871
+ return addHeapObject(ret);
2872
+ };
2873
+ module2.exports.__wbg_next_aaef7c8aa5e212ac = function() {
2874
+ return handleError(function(arg0) {
2875
+ const ret = getObject(arg0).next();
2876
+ return addHeapObject(ret);
2877
+ }, arguments);
2878
+ };
2879
+ module2.exports.__wbg_done_1b73b0672e15f234 = function(arg0) {
2880
+ const ret = getObject(arg0).done;
2881
+ return ret;
2882
+ };
2883
+ module2.exports.__wbg_value_1ccc36bc03462d71 = function(arg0) {
2884
+ const ret = getObject(arg0).value;
2885
+ return addHeapObject(ret);
2886
+ };
2887
+ module2.exports.__wbg_iterator_6f9d4f28845f426c = function() {
2888
+ const ret = Symbol.iterator;
2889
+ return addHeapObject(ret);
2890
+ };
2891
+ module2.exports.__wbg_get_765201544a2b6869 = function() {
2892
+ return handleError(function(arg0, arg1) {
2893
+ const ret = Reflect.get(getObject(arg0), getObject(arg1));
2894
+ return addHeapObject(ret);
2895
+ }, arguments);
2896
+ };
2897
+ module2.exports.__wbg_call_97ae9d8645dc388b = function() {
2898
+ return handleError(function(arg0, arg1) {
2899
+ const ret = getObject(arg0).call(getObject(arg1));
2900
+ return addHeapObject(ret);
2901
+ }, arguments);
2902
+ };
2903
+ module2.exports.__wbg_new_0b9bfdd97583284e = function() {
2904
+ const ret = new Object();
2905
+ return addHeapObject(ret);
2906
+ };
2907
+ module2.exports.__wbg_isArray_27c46c67f498e15d = function(arg0) {
2908
+ const ret = Array.isArray(getObject(arg0));
2909
+ return ret;
2910
+ };
2911
+ module2.exports.__wbg_push_740e4b286702d964 = function(arg0, arg1) {
2912
+ const ret = getObject(arg0).push(getObject(arg1));
2913
+ return ret;
2914
+ };
2915
+ module2.exports.__wbg_instanceof_ArrayBuffer_e5e48f4762c5610b = function(arg0) {
2916
+ let result;
2917
+ try {
2918
+ result = getObject(arg0) instanceof ArrayBuffer;
2919
+ } catch {
2920
+ result = false;
2921
+ }
2922
+ const ret = result;
2923
+ return ret;
2924
+ };
2925
+ module2.exports.__wbg_values_e42671acbf11ec04 = function(arg0) {
2926
+ const ret = getObject(arg0).values();
2927
+ return addHeapObject(ret);
2928
+ };
2929
+ module2.exports.__wbg_new_8d2af00bc1e329ee = function(arg0, arg1) {
2930
+ const ret = new Error(getStringFromWasm0(arg0, arg1));
2931
+ return addHeapObject(ret);
2932
+ };
2933
+ module2.exports.__wbg_setname_d26cefd43ea3a082 = function(arg0, arg1, arg2) {
2934
+ getObject(arg0).name = getStringFromWasm0(arg1, arg2);
2935
+ };
2936
+ module2.exports.__wbg_set_933729cf5b66ac11 = function(arg0, arg1, arg2) {
2937
+ const ret = getObject(arg0).set(getObject(arg1), getObject(arg2));
2938
+ return addHeapObject(ret);
2939
+ };
2940
+ module2.exports.__wbg_isSafeInteger_dfa0593e8d7ac35a = function(arg0) {
2941
+ const ret = Number.isSafeInteger(getObject(arg0));
2942
+ return ret;
2943
+ };
2944
+ module2.exports.__wbg_now_58886682b7e790d7 = function() {
2945
+ const ret = Date.now();
2946
+ return ret;
2947
+ };
2948
+ module2.exports.__wbg_entries_65a76a413fc91037 = function(arg0) {
2949
+ const ret = Object.entries(getObject(arg0));
2950
+ return addHeapObject(ret);
2951
+ };
2952
+ module2.exports.__wbg_buffer_3f3d764d4747d564 = function(arg0) {
2953
+ const ret = getObject(arg0).buffer;
2954
+ return addHeapObject(ret);
2955
+ };
2956
+ module2.exports.__wbg_new_8c3f0052272a457a = function(arg0) {
2957
+ const ret = new Uint8Array(getObject(arg0));
2958
+ return addHeapObject(ret);
2959
+ };
2960
+ module2.exports.__wbg_set_83db9690f9353e79 = function(arg0, arg1, arg2) {
2961
+ getObject(arg0).set(getObject(arg1), arg2 >>> 0);
2962
+ };
2963
+ module2.exports.__wbg_length_9e1ae1900cb0fbd5 = function(arg0) {
2964
+ const ret = getObject(arg0).length;
2965
+ return ret;
2966
+ };
2967
+ module2.exports.__wbg_instanceof_Uint8Array_971eeda69eb75003 = function(arg0) {
2968
+ let result;
2969
+ try {
2970
+ result = getObject(arg0) instanceof Uint8Array;
2971
+ } catch {
2972
+ result = false;
2973
+ }
2974
+ const ret = result;
2975
+ return ret;
2976
+ };
2977
+ module2.exports.__wbg_has_8359f114ce042f5a = function() {
2978
+ return handleError(function(arg0, arg1) {
2979
+ const ret = Reflect.has(getObject(arg0), getObject(arg1));
2980
+ return ret;
2981
+ }, arguments);
2982
+ };
2983
+ module2.exports.__wbindgen_debug_string = function(arg0, arg1) {
2984
+ const ret = debugString(getObject(arg1));
2985
+ const ptr0 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
2986
+ const len0 = WASM_VECTOR_LEN;
2987
+ getInt32Memory0()[arg0 / 4 + 1] = len0;
2988
+ getInt32Memory0()[arg0 / 4 + 0] = ptr0;
2989
+ };
2990
+ module2.exports.__wbindgen_throw = function(arg0, arg1) {
2991
+ throw new Error(getStringFromWasm0(arg0, arg1));
2992
+ };
2993
+ module2.exports.__wbindgen_memory = function() {
2994
+ const ret = wasm.memory;
2995
+ return addHeapObject(ret);
2996
+ };
2997
+ var path = require("path").join(__dirname, "polar_wasm_api_bg.wasm");
2998
+ var bytes = require("fs").readFileSync(path);
2999
+ var wasmModule = new WebAssembly.Module(bytes);
3000
+ var wasmInstance = new WebAssembly.Instance(wasmModule, imports);
3001
+ wasm = wasmInstance.exports;
3002
+ module2.exports.__wasm = wasm;
3003
+ }
3004
+ });
3005
+
3006
+ // node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/Polar.js
3007
+ var require_Polar = __commonJS({
3008
+ "node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/Polar.js"(exports2) {
3009
+ "use strict";
3010
+ var __classPrivateFieldSet = exports2 && exports2.__classPrivateFieldSet || function(receiver, state, value, kind, f) {
3011
+ if (kind === "m") throw new TypeError("Private method is not writable");
3012
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
3013
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
3014
+ return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
3015
+ };
3016
+ var __classPrivateFieldGet = exports2 && exports2.__classPrivateFieldGet || function(receiver, state, kind, f) {
3017
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3018
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
3019
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
3020
+ };
3021
+ var _Polar_ffiPolar;
3022
+ var _Polar_host;
3023
+ Object.defineProperty(exports2, "__esModule", { value: true });
3024
+ exports2.Polar = void 0;
3025
+ var path_1 = require("path");
3026
+ var readline_1 = require("readline");
3027
+ var repl_1 = require("repl");
3028
+ var errors_1 = require_errors();
3029
+ var Query_1 = require_Query();
3030
+ var Host_1 = require_Host();
3031
+ var polar_wasm_api_1 = require_polar_wasm_api();
3032
+ var Predicate_1 = require_Predicate();
3033
+ var messages_1 = require_messages();
3034
+ var types_1 = require_types();
3035
+ var helpers_1 = require_helpers();
3036
+ var Source = class {
3037
+ constructor(src, filename) {
3038
+ this.src = src;
3039
+ this.filename = filename;
3040
+ }
3041
+ };
3042
+ var Polar = class {
3043
+ constructor(opts = {}) {
3044
+ _Polar_ffiPolar.set(this, void 0);
3045
+ _Polar_host.set(this, void 0);
3046
+ __classPrivateFieldSet(this, _Polar_ffiPolar, new polar_wasm_api_1.Polar(), "f");
3047
+ __classPrivateFieldGet(this, _Polar_ffiPolar, "f").setIgnoreNoAllowWarning(!!(process === null || process === void 0 ? void 0 : process.env.POLAR_IGNORE_NO_ALLOW_WARNING));
3048
+ __classPrivateFieldSet(this, _Polar_host, new Host_1.Host(__classPrivateFieldGet(this, _Polar_ffiPolar, "f"), {
3049
+ acceptExpression: false,
3050
+ equalityFn: opts.equalityFn || helpers_1.defaultEqualityFn
3051
+ }), "f");
3052
+ this.registerConstant(null, "nil");
3053
+ this.registerClass(Boolean);
3054
+ this.registerClass(Number, { name: "Integer" });
3055
+ this.registerClass(Number, { name: "Float" });
3056
+ this.registerClass(String);
3057
+ this.registerClass(Array, { name: "List" });
3058
+ this.registerClass(types_1.Dict, { name: "Dictionary" });
3059
+ }
3060
+ /**
3061
+ * Free the underlying WASM instance.
3062
+ *
3063
+ * Invariant: ensure that you do *not* do anything else with an instance
3064
+ * after calling `free()` on it.
3065
+ *
3066
+ * This should *not* be something you need to do during the course of regular
3067
+ * usage. It's generally only useful for scenarios where large numbers of
3068
+ * instances are spun up and not cleanly reaped by the GC, such as during a
3069
+ * long-running test process in 'watch' mode.
3070
+ */
3071
+ free() {
3072
+ __classPrivateFieldGet(this, _Polar_ffiPolar, "f").free();
3073
+ }
3074
+ /**
3075
+ * Process messages received from the Polar VM.
3076
+ *
3077
+ * @internal
3078
+ */
3079
+ processMessages() {
3080
+ for (; ; ) {
3081
+ const msg = __classPrivateFieldGet(this, _Polar_ffiPolar, "f").nextMessage();
3082
+ if (msg === void 0)
3083
+ break;
3084
+ messages_1.processMessage(msg);
3085
+ }
3086
+ }
3087
+ /**
3088
+ * Clear rules from the Polar KB, but
3089
+ * retain all registered classes and constants.
3090
+ */
3091
+ clearRules() {
3092
+ __classPrivateFieldGet(this, _Polar_ffiPolar, "f").clearRules();
3093
+ this.processMessages();
3094
+ }
3095
+ /**
3096
+ * Load Polar policy files.
3097
+ */
3098
+ async loadFiles(filenames) {
3099
+ if (filenames.length === 0)
3100
+ return;
3101
+ if (!path_1.extname) {
3102
+ throw new errors_1.PolarError("loadFiles is not supported in the browser");
3103
+ }
3104
+ const sources = await Promise.all(filenames.map(async (filename) => {
3105
+ if (path_1.extname(filename) !== ".polar")
3106
+ throw new errors_1.PolarFileExtensionError(filename);
3107
+ try {
3108
+ const contents = await helpers_1.readFile(filename);
3109
+ return new Source(contents, filename);
3110
+ } catch (e) {
3111
+ if (e.code === "ENOENT")
3112
+ throw new errors_1.PolarFileNotFoundError(filename);
3113
+ throw e;
3114
+ }
3115
+ }));
3116
+ return this.loadSources(sources);
3117
+ }
3118
+ /**
3119
+ * Load a Polar policy file.
3120
+ *
3121
+ * @deprecated `Oso.loadFile` has been deprecated in favor of `Oso.loadFiles`
3122
+ * as of the 0.20 release. Please see changelog for migration instructions:
3123
+ * https://docs.osohq.com/project/changelogs/2021-09-15.html
3124
+ */
3125
+ async loadFile(filename) {
3126
+ console.error("`Oso.loadFile` has been deprecated in favor of `Oso.loadFiles` as of the 0.20 release.\n\nPlease see changelog for migration instructions: https://docs.osohq.com/project/changelogs/2021-09-15.html");
3127
+ return this.loadFiles([filename]);
3128
+ }
3129
+ /**
3130
+ * Load a Polar policy string.
3131
+ */
3132
+ async loadStr(contents, filename) {
3133
+ return this.loadSources([new Source(contents, filename)]);
3134
+ }
3135
+ // Register MROs, load Polar code, and check inline queries.
3136
+ async loadSources(sources) {
3137
+ __classPrivateFieldGet(this, _Polar_ffiPolar, "f").load(sources);
3138
+ this.processMessages();
3139
+ return this.checkInlineQueries();
3140
+ }
3141
+ async checkInlineQueries() {
3142
+ for (; ; ) {
3143
+ const query = __classPrivateFieldGet(this, _Polar_ffiPolar, "f").nextInlineQuery();
3144
+ this.processMessages();
3145
+ if (query === void 0)
3146
+ break;
3147
+ const source = query.source();
3148
+ const { results } = new Query_1.Query(query, this.getHost());
3149
+ const { done } = await results.next();
3150
+ await results.return();
3151
+ if (done)
3152
+ throw new errors_1.InlineQueryFailedError(source);
3153
+ }
3154
+ }
3155
+ /**
3156
+ * Query for a Polar predicate or string.
3157
+ */
3158
+ query(q, opts) {
3159
+ const host = Host_1.Host.clone(this.getHost(), {
3160
+ acceptExpression: (opts === null || opts === void 0 ? void 0 : opts.acceptExpression) || false
3161
+ });
3162
+ let ffiQuery;
3163
+ if (helpers_1.isString(q)) {
3164
+ ffiQuery = __classPrivateFieldGet(this, _Polar_ffiPolar, "f").newQueryFromStr(q);
3165
+ } else {
3166
+ const term = host.toPolar(q);
3167
+ ffiQuery = __classPrivateFieldGet(this, _Polar_ffiPolar, "f").newQueryFromTerm(term);
3168
+ }
3169
+ this.processMessages();
3170
+ return new Query_1.Query(ffiQuery, host, opts === null || opts === void 0 ? void 0 : opts.bindings).results;
3171
+ }
3172
+ queryRule(nameOrOpts, ...args) {
3173
+ if (typeof nameOrOpts === "string")
3174
+ return this.query(new Predicate_1.Predicate(nameOrOpts, args), {});
3175
+ if (typeof args[0] !== "string")
3176
+ throw new errors_1.PolarError("Invalid call of queryRule(): missing rule name");
3177
+ const [ruleName, ...ruleArgs] = args;
3178
+ return this.query(new Predicate_1.Predicate(ruleName, ruleArgs), nameOrOpts);
3179
+ }
3180
+ /**
3181
+ * Query for a Polar rule, returning true if there are any results.
3182
+ */
3183
+ async queryRuleOnce(name, ...args) {
3184
+ const results = this.query(new Predicate_1.Predicate(name, args));
3185
+ const { done } = await results.next();
3186
+ await results.return();
3187
+ return !done;
3188
+ }
3189
+ /**
3190
+ * Register a JavaScript class for use in Polar policies.
3191
+ *
3192
+ * @param cls The class to register.
3193
+ * @param params An optional object with extra parameters.
3194
+ */
3195
+ registerClass(cls, params) {
3196
+ const clsName = this.getHost().cacheClass(cls, params);
3197
+ this.registerConstant(cls, clsName);
3198
+ this.getHost().registerMros();
3199
+ }
3200
+ /**
3201
+ * Register a JavaScript value for use in Polar policies.
3202
+ */
3203
+ registerConstant(value, name) {
3204
+ const term = this.getHost().toPolar(value);
3205
+ __classPrivateFieldGet(this, _Polar_ffiPolar, "f").registerConstant(name, term);
3206
+ }
3207
+ getHost() {
3208
+ return __classPrivateFieldGet(this, _Polar_host, "f");
3209
+ }
3210
+ getFfi() {
3211
+ return __classPrivateFieldGet(this, _Polar_ffiPolar, "f");
3212
+ }
3213
+ /** Start a REPL session. */
3214
+ async repl(files) {
3215
+ var _a;
3216
+ if (typeof readline_1.createInterface !== "function")
3217
+ throw new errors_1.PolarError("REPL is not supported in the browser");
3218
+ try {
3219
+ if (files === null || files === void 0 ? void 0 : files.length)
3220
+ await this.loadFiles(files);
3221
+ } catch (e) {
3222
+ helpers_1.printError(e);
3223
+ }
3224
+ const repl = (_a = global.repl) === null || _a === void 0 ? void 0 : _a.repl;
3225
+ if (repl) {
3226
+ repl.setPrompt(helpers_1.PROMPT);
3227
+ const evalQuery = this.evalReplInput.bind(this);
3228
+ repl.eval = async (evalCmd, _ctx, _file, cb) => cb(null, await evalQuery(evalCmd));
3229
+ const listeners = repl.listeners("exit");
3230
+ repl.removeAllListeners("exit");
3231
+ repl.prependOnceListener("exit", () => {
3232
+ listeners.forEach((l) => repl.addListener("exit", l));
3233
+ repl_1.start({ useGlobal: true });
3234
+ });
3235
+ } else {
3236
+ const rl = readline_1.createInterface({
3237
+ input: process.stdin,
3238
+ output: process.stdout,
3239
+ prompt: helpers_1.PROMPT,
3240
+ tabSize: 4
3241
+ });
3242
+ rl.prompt();
3243
+ rl.on("line", async (line) => {
3244
+ const result = await this.evalReplInput(line);
3245
+ if (result !== void 0)
3246
+ console.log(result);
3247
+ rl.prompt();
3248
+ });
3249
+ }
3250
+ }
3251
+ /**
3252
+ * Evaluate REPL input.
3253
+ *
3254
+ * @internal
3255
+ */
3256
+ async evalReplInput(query) {
3257
+ const input = query.trim().replace(/;+$/, "");
3258
+ try {
3259
+ if (input !== "") {
3260
+ const ffiQuery = __classPrivateFieldGet(this, _Polar_ffiPolar, "f").newQueryFromStr(input);
3261
+ const query2 = new Query_1.Query(ffiQuery, this.getHost());
3262
+ const results = [];
3263
+ for await (const result of query2.results) {
3264
+ results.push(result);
3265
+ }
3266
+ if (results.length === 0) {
3267
+ return false;
3268
+ } else {
3269
+ for (const result of results) {
3270
+ for (const [variable, value] of result) {
3271
+ console.log(variable + " = " + helpers_1.repr(value));
3272
+ }
3273
+ }
3274
+ return true;
3275
+ }
3276
+ }
3277
+ } catch (e) {
3278
+ helpers_1.printError(e);
3279
+ }
3280
+ }
3281
+ };
3282
+ exports2.Polar = Polar;
3283
+ _Polar_ffiPolar = /* @__PURE__ */ new WeakMap(), _Polar_host = /* @__PURE__ */ new WeakMap();
3284
+ }
3285
+ });
3286
+
3287
+ // node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/Oso.js
3288
+ var require_Oso = __commonJS({
3289
+ "node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/Oso.js"(exports2) {
3290
+ "use strict";
3291
+ var __classPrivateFieldSet = exports2 && exports2.__classPrivateFieldSet || function(receiver, state, value, kind, f) {
3292
+ if (kind === "m") throw new TypeError("Private method is not writable");
3293
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
3294
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
3295
+ return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
3296
+ };
3297
+ var __classPrivateFieldGet = exports2 && exports2.__classPrivateFieldGet || function(receiver, state, kind, f) {
3298
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3299
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
3300
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
3301
+ };
3302
+ var _Oso_notFoundError;
3303
+ var _Oso_forbiddenError;
3304
+ var _Oso_readAction;
3305
+ Object.defineProperty(exports2, "__esModule", { value: true });
3306
+ exports2.Oso = void 0;
3307
+ var Polar_1 = require_Polar();
3308
+ var Variable_1 = require_Variable();
3309
+ var Expression_1 = require_Expression();
3310
+ var Pattern_1 = require_Pattern();
3311
+ var errors_1 = require_errors();
3312
+ var filter_1 = require_filter();
3313
+ var Oso = class extends Polar_1.Polar {
3314
+ constructor(opts = {}) {
3315
+ super(opts);
3316
+ _Oso_notFoundError.set(this, errors_1.NotFoundError);
3317
+ _Oso_forbiddenError.set(this, errors_1.ForbiddenError);
3318
+ _Oso_readAction.set(this, "read");
3319
+ if (opts.notFoundError)
3320
+ __classPrivateFieldSet(this, _Oso_notFoundError, opts.notFoundError, "f");
3321
+ if (opts.forbiddenError)
3322
+ __classPrivateFieldSet(this, _Oso_forbiddenError, opts.forbiddenError, "f");
3323
+ if (opts.readAction)
3324
+ __classPrivateFieldSet(this, _Oso_readAction, opts.readAction, "f");
3325
+ }
3326
+ /**
3327
+ * Query the knowledge base to determine whether an actor is allowed to
3328
+ * perform an action upon a resource.
3329
+ *
3330
+ * @param actor Subject.
3331
+ * @param action Verb.
3332
+ * @param resource Object.
3333
+ * @returns An access control decision.
3334
+ */
3335
+ async isAllowed(actor, action, resource) {
3336
+ return this.queryRuleOnce("allow", actor, action, resource);
3337
+ }
3338
+ /**
3339
+ * Ensure that `actor` is allowed to perform `action` on
3340
+ * `resource`.
3341
+ *
3342
+ * If the action is permitted with an `allow` rule in the policy, then
3343
+ * this method returns `None`. If the action is not permitted by the
3344
+ * policy, this method will raise an error.
3345
+ *
3346
+ * The error raised by this method depends on whether the actor can perform
3347
+ * the `"read"` action on the resource. If they cannot read the resource,
3348
+ * then a `NotFound` error is raised. Otherwise, a `ForbiddenError` is
3349
+ * raised.
3350
+ *
3351
+ * @param actor The actor performing the request.
3352
+ * @param action The action the actor is attempting to perform.
3353
+ * @param resource The resource being accessed.
3354
+ * @param checkRead If set to `false`, a `ForbiddenError` is always
3355
+ * thrown on authorization failures, regardless of whether the actor can
3356
+ * read the resource. Default is `true`.
3357
+ */
3358
+ async authorize(actor, action, resource, options = {}) {
3359
+ if (typeof options.checkRead === "undefined")
3360
+ options.checkRead = true;
3361
+ if (await this.queryRuleOnce("allow", actor, action, resource)) {
3362
+ return;
3363
+ }
3364
+ let isNotFound = false;
3365
+ if (options.checkRead) {
3366
+ if (action === __classPrivateFieldGet(this, _Oso_readAction, "f")) {
3367
+ isNotFound = true;
3368
+ } else {
3369
+ const canRead = await this.queryRuleOnce("allow", actor, __classPrivateFieldGet(this, _Oso_readAction, "f"), resource);
3370
+ if (!canRead) {
3371
+ isNotFound = true;
3372
+ }
3373
+ }
3374
+ }
3375
+ const ErrorClass = isNotFound ? __classPrivateFieldGet(this, _Oso_notFoundError, "f") : __classPrivateFieldGet(this, _Oso_forbiddenError, "f");
3376
+ throw new ErrorClass();
3377
+ }
3378
+ /**
3379
+ * Determine the actions `actor` is allowed to take on `resource`.
3380
+ *
3381
+ * Collects all actions allowed by allow rules in the Polar policy for the
3382
+ * given combination of actor and resource.
3383
+ *
3384
+ * @param actor The actor for whom to collect allowed actions
3385
+ * @param resource The resource being accessed
3386
+ * @param allowWildcard Flag to determine behavior if the policy
3387
+ * includes a wildcard action. E.g., a rule allowing any action:
3388
+ * `allow(_actor, _action, _resource)`. If `true`, the method will
3389
+ * return `["*"]`, if `false`, the method will raise an exception.
3390
+ * @returns A list of the unique allowed actions.
3391
+ */
3392
+ async authorizedActions(actor, resource, options = {}) {
3393
+ const results = this.queryRule("allow", actor, new Variable_1.Variable("action"), resource);
3394
+ const actions = /* @__PURE__ */ new Set();
3395
+ for await (const result of results) {
3396
+ const action = result.get("action");
3397
+ if (action instanceof Variable_1.Variable) {
3398
+ if (!options.allowWildcard) {
3399
+ throw new errors_1.OsoError(`
3400
+ The result of authorizedActions() contained an "unconstrained" action that could represent any action, but allowWildcard was set to False. To fix, set allowWildcard to True and compare with the "*" string.
3401
+ `);
3402
+ } else {
3403
+ return /* @__PURE__ */ new Set(["*"]);
3404
+ }
3405
+ }
3406
+ actions.add(action);
3407
+ }
3408
+ return actions;
3409
+ }
3410
+ /**
3411
+ * Ensure that `actor` is allowed to send `request` to the server.
3412
+ *
3413
+ * Checks the `allow_request` rule of a policy.
3414
+ *
3415
+ * If the request is permitted with an `allow_request` rule in the
3416
+ * policy, then this method returns nothing. Otherwise, this method raises
3417
+ * a `ForbiddenError`.
3418
+ *
3419
+ * @param actor The actor performing the request.
3420
+ * @param request An object representing the request that was sent by the
3421
+ * actor.
3422
+ */
3423
+ async authorizeRequest(actor, request) {
3424
+ const isAllowed = await this.queryRuleOnce("allow_request", actor, request);
3425
+ if (!isAllowed) {
3426
+ throw new (__classPrivateFieldGet(this, _Oso_forbiddenError, "f"))();
3427
+ }
3428
+ }
3429
+ /**
3430
+ * Ensure that `actor` is allowed to perform `action` on a given
3431
+ * `resource`'s `field`.
3432
+ *
3433
+ * If the action is permitted by an `allow_field` rule in the policy,
3434
+ * then this method returns nothing. If the action is not permitted by the
3435
+ * policy, this method will raise a `ForbiddenError`.
3436
+ *
3437
+ * @param actor The actor performing the request.
3438
+ * @param action The action the actor is attempting to perform on the
3439
+ * field.
3440
+ * @param resource The resource being accessed.
3441
+ * @param field The name of the field being accessed.
3442
+ */
3443
+ async authorizeField(actor, action, resource, field) {
3444
+ const isAllowed = await this.queryRuleOnce("allow_field", actor, action, resource, field);
3445
+ if (!isAllowed) {
3446
+ throw new (__classPrivateFieldGet(this, _Oso_forbiddenError, "f"))();
3447
+ }
3448
+ }
3449
+ /**
3450
+ * Determine the fields of `resource` on which `actor` is allowed to
3451
+ * perform `action`.
3452
+ *
3453
+ * Uses `allow_field` rules in the policy to find all allowed fields.
3454
+ *
3455
+ * @param actor The actor for whom to collect allowed fields.
3456
+ * @param action The action being taken on the field.
3457
+ * @param resource The resource being accessed.
3458
+ * @param allowWildcard Flag to determine behavior if the policy \
3459
+ * includes a wildcard field. E.g., a rule allowing any field: \
3460
+ * `allow_field(_actor, _action, _resource, _field)`. If `true`, the \
3461
+ * method will return `["*"]`, if `false`, the method will raise an \
3462
+ * exception.
3463
+ * @returns A list of the unique allowed fields.
3464
+ */
3465
+ async authorizedFields(actor, action, resource, options = {}) {
3466
+ const results = this.queryRule("allow_field", actor, action, resource, new Variable_1.Variable("field"));
3467
+ const fields = /* @__PURE__ */ new Set();
3468
+ for await (const result of results) {
3469
+ const field = result.get("field");
3470
+ if (field instanceof Variable_1.Variable) {
3471
+ if (!options.allowWildcard) {
3472
+ throw new errors_1.OsoError(`
3473
+ The result of authorizedFields() contained an "unconstrained" field that could represent any field, but allowWildcard was set to False. To fix, set allowWildcard to True and compare with the "*" string.
3474
+ `);
3475
+ } else {
3476
+ return /* @__PURE__ */ new Set(["*"]);
3477
+ }
3478
+ }
3479
+ fields.add(field);
3480
+ }
3481
+ return fields;
3482
+ }
3483
+ /**
3484
+ * Create a query for all the resources of type `resourceCls` that `actor` is
3485
+ * allowed to perform `action` on.
3486
+ *
3487
+ * @param actor Subject.
3488
+ * @param action Verb.
3489
+ * @param resourceCls Object type.
3490
+ * @returns A query that selects authorized resources of type `resourceCls`
3491
+ */
3492
+ async authorizedQuery(actor, action, resourceCls) {
3493
+ var _a;
3494
+ const resource = new Variable_1.Variable("resource");
3495
+ const host = this.getHost();
3496
+ let clsName;
3497
+ if (typeof resourceCls === "string") {
3498
+ clsName = resourceCls;
3499
+ } else {
3500
+ clsName = (_a = host.getType(resourceCls)) === null || _a === void 0 ? void 0 : _a.name;
3501
+ if (clsName === void 0)
3502
+ throw new errors_1.UnregisteredClassError(resourceCls.name);
3503
+ }
3504
+ const constraint = new Expression_1.Expression("And", [
3505
+ new Expression_1.Expression("Isa", [
3506
+ resource,
3507
+ new Pattern_1.Pattern({ tag: clsName, fields: {} })
3508
+ ])
3509
+ ]);
3510
+ const bindings = /* @__PURE__ */ new Map();
3511
+ bindings.set("resource", constraint);
3512
+ const results = this.queryRule({
3513
+ bindings,
3514
+ acceptExpression: true
3515
+ }, "allow", actor, action, resource);
3516
+ const queryResults = [];
3517
+ for await (const result of results) {
3518
+ queryResults.push({
3519
+ // convert bindings back into Polar
3520
+ bindings: new Map([...result.entries()].map(([k, v]) => [k, host.toPolar(v)]))
3521
+ });
3522
+ }
3523
+ const dataFilter = this.getFfi().buildDataFilter(host.serializeTypes(), queryResults, "resource", clsName);
3524
+ const filter = await filter_1.parseFilter(dataFilter, host);
3525
+ return host.adapter.buildQuery(filter);
3526
+ }
3527
+ /**
3528
+ * Determine the resources of type `resourceCls` that `actor`
3529
+ * is allowed to perform `action` on.
3530
+ *
3531
+ * @param actor Subject.
3532
+ * @param action Verb.
3533
+ * @param resourceCls Object type or string name of class
3534
+ * @returns An array of authorized resources.
3535
+ */
3536
+ async authorizedResources(actor, action, resourceCls) {
3537
+ const query = await this.authorizedQuery(actor, action, resourceCls);
3538
+ if (!query)
3539
+ return [];
3540
+ return this.getHost().adapter.executeQuery(query);
3541
+ }
3542
+ /**
3543
+ * Register adapter for data filtering query functions.
3544
+ */
3545
+ setDataFilteringAdapter(adapter) {
3546
+ this.getHost().adapter = adapter;
3547
+ }
3548
+ };
3549
+ exports2.Oso = Oso;
3550
+ _Oso_notFoundError = /* @__PURE__ */ new WeakMap(), _Oso_forbiddenError = /* @__PURE__ */ new WeakMap(), _Oso_readAction = /* @__PURE__ */ new WeakMap();
3551
+ }
3552
+ });
3553
+
3554
+ // node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/index.js
3555
+ var require_src = __commonJS({
3556
+ "node_modules/.pnpm/oso@0.27.3/node_modules/oso/dist/src/index.js"(exports2) {
3557
+ "use strict";
3558
+ Object.defineProperty(exports2, "__esModule", { value: true });
3559
+ exports2.defaultEqualityFn = exports2.Relation = exports2.NotFoundError = exports2.ForbiddenError = exports2.AuthorizationError = exports2.Variable = exports2.Oso = void 0;
3560
+ var Oso_1 = require_Oso();
3561
+ Object.defineProperty(exports2, "Oso", { enumerable: true, get: function() {
3562
+ return Oso_1.Oso;
3563
+ } });
3564
+ var Variable_1 = require_Variable();
3565
+ Object.defineProperty(exports2, "Variable", { enumerable: true, get: function() {
3566
+ return Variable_1.Variable;
3567
+ } });
3568
+ var errors_1 = require_errors();
3569
+ Object.defineProperty(exports2, "AuthorizationError", { enumerable: true, get: function() {
3570
+ return errors_1.AuthorizationError;
3571
+ } });
3572
+ Object.defineProperty(exports2, "ForbiddenError", { enumerable: true, get: function() {
3573
+ return errors_1.ForbiddenError;
3574
+ } });
3575
+ Object.defineProperty(exports2, "NotFoundError", { enumerable: true, get: function() {
3576
+ return errors_1.NotFoundError;
3577
+ } });
3578
+ var filter_1 = require_filter();
3579
+ Object.defineProperty(exports2, "Relation", { enumerable: true, get: function() {
3580
+ return filter_1.Relation;
3581
+ } });
3582
+ var helpers_1 = require_helpers();
3583
+ Object.defineProperty(exports2, "defaultEqualityFn", { enumerable: true, get: function() {
3584
+ return helpers_1.defaultEqualityFn;
3585
+ } });
3586
+ }
3587
+ });
3588
+
3589
+ // src/lib/policy/oso-engine.ts
3590
+ var oso_engine_exports = {};
3591
+ __export(oso_engine_exports, {
3592
+ OsoPolicyEngine: () => OsoPolicyEngine
3593
+ });
3594
+ var User, Tool, FilePath, AgentSession, OsoPolicyEngine;
3595
+ var init_oso_engine = __esm({
3596
+ "src/lib/policy/oso-engine.ts"() {
3597
+ "use strict";
3598
+ User = class {
3599
+ constructor(role, orgUnit) {
3600
+ this.role = role;
3601
+ this.orgUnit = orgUnit;
3602
+ }
3603
+ };
3604
+ Tool = class {
3605
+ constructor(name) {
3606
+ this.name = name;
3607
+ }
3608
+ };
3609
+ FilePath = class {
3610
+ constructor(path, orgUnit) {
3611
+ this.path = path;
3612
+ this.orgUnit = orgUnit;
3613
+ }
3614
+ };
3615
+ AgentSession = class {
3616
+ };
3617
+ OsoPolicyEngine = class _OsoPolicyEngine {
3618
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
3619
+ oso;
3620
+ roleConfigs = /* @__PURE__ */ new Map();
3621
+ constructor() {
3622
+ }
3623
+ static async create(polarFiles, factStore) {
3624
+ let OsoClass;
3625
+ try {
3626
+ const osoModule = await Promise.resolve().then(() => __toESM(require_src(), 1));
3627
+ OsoClass = osoModule.Oso;
3628
+ } catch {
3629
+ throw new Error(
3630
+ "oso package is not installed. Install it with: npm install oso\nOr switch to the YAML policy engine: policy.engine: yaml"
3631
+ );
3632
+ }
3633
+ const engine = new _OsoPolicyEngine();
3634
+ engine.oso = new OsoClass();
3635
+ engine.oso.registerClass(User);
3636
+ engine.oso.registerClass(Tool);
3637
+ engine.oso.registerClass(FilePath);
3638
+ engine.oso.registerClass(AgentSession);
3639
+ for (const file of polarFiles) {
3640
+ await engine.oso.loadFiles([file]);
3641
+ }
3642
+ const bindings = await factStore.getAllRoleBindings();
3643
+ for (const binding of bindings) {
3644
+ if (binding.config) {
3645
+ engine.roleConfigs.set(binding.role, binding.config);
3646
+ }
3647
+ }
3648
+ return engine;
3649
+ }
3650
+ evaluateTool(role, tool) {
3651
+ const user = new User(role);
3652
+ const toolResource = new Tool(tool);
3653
+ try {
3654
+ const result = this.oso.isAllowedSync?.(user, "invoke", toolResource);
3655
+ if (result !== void 0) {
3656
+ return result ? "allow" : "deny";
3657
+ }
3658
+ } catch {
3659
+ }
3660
+ return "deny";
3661
+ }
3662
+ async evaluateToolAsync(role, tool) {
3663
+ const user = new User(role);
3664
+ const toolResource = new Tool(tool);
3665
+ const allowed = await this.oso.isAllowed(user, "invoke", toolResource);
3666
+ return allowed ? "allow" : "deny";
3667
+ }
3668
+ evaluatePath(role, orgUnit, operation, _path) {
3669
+ const user = new User(role, orgUnit);
3670
+ const filePath = new FilePath(_path, orgUnit);
3671
+ try {
3672
+ const result = this.oso.isAllowedSync?.(user, operation, filePath);
3673
+ if (result !== void 0) {
3674
+ return result ? "allow" : "deny";
3675
+ }
3676
+ } catch {
3677
+ }
3678
+ return "deny";
3679
+ }
3680
+ async evaluatePathAsync(role, orgUnit, operation, path) {
3681
+ const user = new User(role, orgUnit);
3682
+ const filePath = new FilePath(path, orgUnit);
3683
+ const allowed = await this.oso.isAllowed(user, operation, filePath);
3684
+ return allowed ? "allow" : "deny";
3685
+ }
3686
+ requiresApproval(role, tool) {
3687
+ try {
3688
+ const user = new User(role);
3689
+ const toolResource = new Tool(tool);
3690
+ const result = this.oso.isAllowedSync?.(user, "auto_approve", toolResource);
3691
+ if (result !== void 0) return !result;
3692
+ } catch {
3693
+ }
3694
+ return true;
3695
+ }
3696
+ getExecutionMode(role) {
3697
+ const config = this.roleConfigs.get(role);
3698
+ return config?.execution_mode ?? "supervised";
3699
+ }
3700
+ getTemplateName(role) {
3701
+ const config = this.roleConfigs.get(role);
3702
+ return config?.prompt_template ?? "project-lead";
3703
+ }
3704
+ getBashOverrides(role) {
3705
+ const config = this.roleConfigs.get(role);
3706
+ const overrides = config?.bash_overrides;
3707
+ if (!overrides) return {};
3708
+ return {
3709
+ additionalBlocked: overrides.additional_blocked?.map((p) => new RegExp(p)),
3710
+ additionalAllowed: overrides.additional_allowed?.map((p) => new RegExp(p))
3711
+ };
3712
+ }
3713
+ getTokenBudget(role) {
3714
+ const config = this.roleConfigs.get(role);
3715
+ return config?.token_budget_daily ?? -1;
3716
+ }
3717
+ };
3718
+ }
3719
+ });
3720
+
3721
+ // src/lib/facts/oso-memory-store.ts
3722
+ var oso_memory_store_exports = {};
3723
+ __export(oso_memory_store_exports, {
3724
+ OsoMemoryFactStore: () => OsoMemoryFactStore
3725
+ });
3726
+ var OsoMemoryFactStore;
3727
+ var init_oso_memory_store = __esm({
3728
+ "src/lib/facts/oso-memory-store.ts"() {
3729
+ "use strict";
3730
+ OsoMemoryFactStore = class {
3731
+ bindings = [];
3732
+ relations = [];
3733
+ addRoleBinding(binding) {
3734
+ this.bindings.push(binding);
3735
+ }
3736
+ addRelation(relation) {
3737
+ this.relations.push(relation);
3738
+ }
3739
+ async getRoles(userId) {
3740
+ return this.bindings.filter((b) => b.userId === userId);
3741
+ }
3742
+ async getAllRoleBindings() {
3743
+ return [...this.bindings];
3744
+ }
3745
+ async getRelations(subject, predicate) {
3746
+ return this.relations.filter((r) => r.subject === subject && r.predicate === predicate);
3747
+ }
3748
+ };
3749
+ }
3750
+ });
19
3751
 
20
3752
  // src/index.ts
21
3753
  var index_exports = {};
22
3754
  __export(index_exports, {
3755
+ AuditLogger: () => AuditLogger,
3756
+ BashClassifier: () => BashClassifier,
3757
+ BudgetTracker: () => BudgetTracker,
3758
+ CliApprover: () => CliApprover,
23
3759
  ConfigValidationError: () => ConfigValidationError,
24
- loadConfig: () => loadConfig
3760
+ ConfigWatcher: () => ConfigWatcher,
3761
+ DANGEROUS_PATTERNS: () => DANGEROUS_PATTERNS,
3762
+ EnvIdentityProvider: () => EnvIdentityProvider,
3763
+ IdentityChain: () => IdentityChain,
3764
+ JsonlAuditSink: () => JsonlAuditSink,
3765
+ LocalIdentityProvider: () => LocalIdentityProvider,
3766
+ OsoMemoryFactStore: () => OsoMemoryFactStore,
3767
+ SAFE_PATTERNS: () => SAFE_PATTERNS,
3768
+ TemplateSelector: () => TemplateSelector,
3769
+ WebhookApprover: () => WebhookApprover,
3770
+ WebhookAuditSink: () => WebhookAuditSink,
3771
+ YamlFactStore: () => YamlFactStore,
3772
+ YamlPolicyEngine: () => YamlPolicyEngine,
3773
+ createApprovalFlow: () => createApprovalFlow,
3774
+ createIdentityChain: () => createIdentityChain,
3775
+ createPolicyEngine: () => createPolicyEngine,
3776
+ loadConfig: () => loadConfig,
3777
+ renderTemplate: () => render
25
3778
  });
26
3779
  module.exports = __toCommonJS(index_exports);
27
3780
 
@@ -143,13 +3896,15 @@ var DEFAULTS = {
143
3896
  };
144
3897
 
145
3898
  // src/lib/config/loader.ts
146
- var CONFIG_PATHS = [
147
- process.env.GRWND_GOVERNANCE_CONFIG,
148
- ".pi/governance.yaml",
149
- `${process.env.HOME}/.pi/agent/governance.yaml`
150
- ];
3899
+ function getConfigPaths() {
3900
+ return [
3901
+ process.env["GRWND_GOVERNANCE_CONFIG"],
3902
+ ".pi/governance.yaml",
3903
+ `${process.env["HOME"]}/.pi/agent/governance.yaml`
3904
+ ];
3905
+ }
151
3906
  function loadConfig() {
152
- for (const path of CONFIG_PATHS) {
3907
+ for (const path of getConfigPaths()) {
153
3908
  if (path && (0, import_fs.existsSync)(path)) {
154
3909
  const raw = (0, import_fs.readFileSync)(path, "utf-8");
155
3910
  const parsed = (0, import_yaml.parse)(raw);
@@ -187,9 +3942,788 @@ ${details}`);
187
3942
  this.name = "ConfigValidationError";
188
3943
  }
189
3944
  };
3945
+
3946
+ // src/lib/policy/yaml-engine.ts
3947
+ var import_fs2 = require("fs");
3948
+ var import_yaml2 = require("yaml");
3949
+ var import_minimatch = require("minimatch");
3950
+ var YamlPolicyEngine = class {
3951
+ rules;
3952
+ constructor(rulesFilePathOrRules) {
3953
+ if (typeof rulesFilePathOrRules === "string") {
3954
+ const raw = (0, import_fs2.readFileSync)(rulesFilePathOrRules, "utf-8");
3955
+ this.rules = (0, import_yaml2.parse)(raw);
3956
+ } else {
3957
+ this.rules = rulesFilePathOrRules;
3958
+ }
3959
+ }
3960
+ getRole(role) {
3961
+ const r = this.rules.roles[role];
3962
+ if (!r) {
3963
+ throw new Error(
3964
+ `Unknown role: ${role}. Available roles: ${Object.keys(this.rules.roles).join(", ")}`
3965
+ );
3966
+ }
3967
+ return r;
3968
+ }
3969
+ evaluateTool(role, tool) {
3970
+ const r = this.getRole(role);
3971
+ if (r.blocked_tools.includes(tool)) return "deny";
3972
+ if (r.allowed_tools.includes("all") || r.allowed_tools.includes(tool)) {
3973
+ return "allow";
3974
+ }
3975
+ return "deny";
3976
+ }
3977
+ evaluatePath(role, _orgUnit, _operation, path) {
3978
+ const r = this.getRole(role);
3979
+ for (const pattern of r.blocked_paths) {
3980
+ if ((0, import_minimatch.minimatch)(path, pattern, { dot: true })) {
3981
+ return "deny";
3982
+ }
3983
+ }
3984
+ for (const pattern of r.allowed_paths) {
3985
+ const resolved = pattern.replace("{{project_path}}", process.cwd());
3986
+ if ((0, import_minimatch.minimatch)(path, resolved, { dot: true })) {
3987
+ return "allow";
3988
+ }
3989
+ }
3990
+ return "deny";
3991
+ }
3992
+ requiresApproval(role, tool) {
3993
+ const r = this.getRole(role);
3994
+ if (r.human_approval.auto_approve?.includes(tool)) return false;
3995
+ if (r.human_approval.required_for.includes("all")) return true;
3996
+ return r.human_approval.required_for.includes(tool);
3997
+ }
3998
+ getExecutionMode(role) {
3999
+ return this.getRole(role).execution_mode;
4000
+ }
4001
+ getTemplateName(role) {
4002
+ return this.getRole(role).prompt_template;
4003
+ }
4004
+ getBashOverrides(role) {
4005
+ const r = this.getRole(role);
4006
+ const overrides = r.bash_overrides;
4007
+ if (!overrides) return {};
4008
+ return {
4009
+ additionalBlocked: overrides.additional_blocked?.map((p) => new RegExp(p)),
4010
+ additionalAllowed: overrides.additional_allowed?.map((p) => new RegExp(p))
4011
+ };
4012
+ }
4013
+ getTokenBudget(role) {
4014
+ return this.getRole(role).token_budget_daily;
4015
+ }
4016
+ };
4017
+
4018
+ // src/lib/policy/factory.ts
4019
+ async function createPolicyEngine(config) {
4020
+ const engine = config?.engine ?? "yaml";
4021
+ if (engine === "yaml") {
4022
+ const rulesFile = config?.yaml?.rules_file ?? "./governance-rules.yaml";
4023
+ return new YamlPolicyEngine(rulesFile);
4024
+ }
4025
+ if (engine === "oso") {
4026
+ const { OsoPolicyEngine: OsoPolicyEngine2 } = await Promise.resolve().then(() => (init_oso_engine(), oso_engine_exports));
4027
+ const { OsoMemoryFactStore: OsoMemoryFactStore2 } = await Promise.resolve().then(() => (init_oso_memory_store(), oso_memory_store_exports));
4028
+ const polarFiles = config?.oso?.polar_files ?? [
4029
+ "./policies/base.polar",
4030
+ "./policies/tools.polar"
4031
+ ];
4032
+ const factStore = new OsoMemoryFactStore2();
4033
+ return OsoPolicyEngine2.create(polarFiles, factStore);
4034
+ }
4035
+ throw new Error(`Unknown policy engine: ${engine}. Must be 'yaml' or 'oso'.`);
4036
+ }
4037
+
4038
+ // src/lib/identity/env-provider.ts
4039
+ var EnvIdentityProvider = class {
4040
+ constructor(userVar = "GRWND_USER", roleVar = "GRWND_ROLE", orgUnitVar = "GRWND_ORG_UNIT") {
4041
+ this.userVar = userVar;
4042
+ this.roleVar = roleVar;
4043
+ this.orgUnitVar = orgUnitVar;
4044
+ }
4045
+ name = "env";
4046
+ async resolve() {
4047
+ const userId = process.env[this.userVar];
4048
+ const role = process.env[this.roleVar];
4049
+ const orgUnit = process.env[this.orgUnitVar];
4050
+ if (!userId || !role) return null;
4051
+ return {
4052
+ userId,
4053
+ role,
4054
+ orgUnit: orgUnit ?? "default",
4055
+ source: "env"
4056
+ };
4057
+ }
4058
+ };
4059
+
4060
+ // src/lib/identity/local-provider.ts
4061
+ var import_fs3 = require("fs");
4062
+ var import_yaml3 = require("yaml");
4063
+ var LocalIdentityProvider = class {
4064
+ name = "local";
4065
+ users;
4066
+ constructor(usersFilePath) {
4067
+ const raw = (0, import_fs3.readFileSync)(usersFilePath, "utf-8");
4068
+ this.users = (0, import_yaml3.parse)(raw);
4069
+ }
4070
+ async resolve() {
4071
+ const username = process.env.USER || process.env.USERNAME;
4072
+ if (!username) return null;
4073
+ const entry = this.users[username];
4074
+ if (!entry) return null;
4075
+ return {
4076
+ userId: username,
4077
+ role: entry.role,
4078
+ orgUnit: entry.org_unit ?? "default",
4079
+ source: "local"
4080
+ };
4081
+ }
4082
+ };
4083
+
4084
+ // src/lib/identity/chain.ts
4085
+ var IdentityChain = class {
4086
+ providers;
4087
+ constructor(providers) {
4088
+ this.providers = providers;
4089
+ }
4090
+ async resolve() {
4091
+ for (const provider of this.providers) {
4092
+ const identity = await provider.resolve();
4093
+ if (identity) return identity;
4094
+ }
4095
+ return {
4096
+ userId: "unknown",
4097
+ role: "analyst",
4098
+ // most restrictive role by default
4099
+ orgUnit: "default",
4100
+ source: "fallback"
4101
+ };
4102
+ }
4103
+ };
4104
+ function createIdentityChain(config) {
4105
+ const providers = [];
4106
+ providers.push(
4107
+ new EnvIdentityProvider(
4108
+ config?.env?.user_var,
4109
+ config?.env?.role_var,
4110
+ config?.env?.org_unit_var
4111
+ )
4112
+ );
4113
+ if (config?.provider === "local" && config.local?.users_file) {
4114
+ try {
4115
+ providers.push(new LocalIdentityProvider(config.local.users_file));
4116
+ } catch {
4117
+ }
4118
+ }
4119
+ return new IdentityChain(providers);
4120
+ }
4121
+
4122
+ // src/lib/facts/yaml-store.ts
4123
+ var import_node_fs = require("fs");
4124
+ var import_yaml4 = require("yaml");
4125
+ var YamlFactStore = class {
4126
+ bindings;
4127
+ constructor(input) {
4128
+ if (typeof input === "string") {
4129
+ const raw = (0, import_node_fs.readFileSync)(input, "utf-8");
4130
+ const parsed = (0, import_yaml4.parse)(raw);
4131
+ this.bindings = this.parseUsers(parsed);
4132
+ } else {
4133
+ this.bindings = this.parseUsers(input);
4134
+ }
4135
+ }
4136
+ parseUsers(users) {
4137
+ return Object.entries(users).map(([userId, entry]) => ({
4138
+ userId,
4139
+ role: entry.role,
4140
+ orgUnit: entry.org_unit ?? "default",
4141
+ config: entry.config
4142
+ }));
4143
+ }
4144
+ async getRoles(userId) {
4145
+ return this.bindings.filter((b) => b.userId === userId);
4146
+ }
4147
+ async getAllRoleBindings() {
4148
+ return [...this.bindings];
4149
+ }
4150
+ async getRelations(_subject, _predicate) {
4151
+ return [];
4152
+ }
4153
+ };
4154
+
4155
+ // src/index.ts
4156
+ init_oso_memory_store();
4157
+
4158
+ // src/lib/bash/patterns.ts
4159
+ var SAFE_PATTERNS = [
4160
+ // File viewing
4161
+ /^(cat|head|tail|less|more)\s/,
4162
+ /^(file|stat|wc|md5sum|sha256sum)\s/,
4163
+ // Directory listing
4164
+ /^(ls|ll|la|tree|du|df)\b/,
4165
+ /^(pwd|cd)\b/,
4166
+ // Searching
4167
+ /^(grep|rg|ag|ack|find|fd|locate)\s/,
4168
+ /^(which|whereis|type|command)\s/,
4169
+ // Text processing (read-only)
4170
+ /^(sort|uniq|cut|awk|sed)\s.*(?!-i)/,
4171
+ // sed without -i (in-place)
4172
+ /^(tr|diff|comm|join|paste)\s/,
4173
+ /^(jq|yq|xmlstarlet)\s/,
4174
+ // Git (read-only operations)
4175
+ /^git\s+(log|status|diff|show|blame|branch|tag|remote|stash list)\b/,
4176
+ /^git\s+(ls-files|ls-tree|rev-parse|describe)\b/,
4177
+ // System info
4178
+ /^(whoami|id|groups|uname|hostname|date|uptime|env|printenv)\b/,
4179
+ /^(echo|printf)\s/,
4180
+ // Package info (not install)
4181
+ /^(npm|yarn|pnpm)\s+(list|ls|info|show|view|outdated|audit)\b/,
4182
+ /^pip\s+(list|show|freeze)\b/,
4183
+ /^(node|python|ruby|go)\s+--version\b/,
4184
+ /^(node|python|ruby)\s+-e\s/,
4185
+ // Networking (read-only)
4186
+ /^(ping|dig|nslookup|host|traceroute|tracepath)\s/,
4187
+ /^curl\s.*--head\b/,
4188
+ /^curl\s.*-I\b/,
4189
+ // Additional file viewing / inspection
4190
+ /^(basename|dirname|realpath|readlink)\s/,
4191
+ /^(xxd|od|hexdump)\s/,
4192
+ /^(strings|nm|objdump)\s/,
4193
+ // Additional search / navigation
4194
+ /^(xargs)\s/,
4195
+ /^(tee)\s/,
4196
+ // Additional text processing (read-only)
4197
+ /^(fmt|fold|column|expand|unexpand)\s/,
4198
+ /^(tac|rev|nl)\s/,
4199
+ /^(yes|seq|shuf)\s/,
4200
+ // Additional system info
4201
+ /^(lsof|ps|top|htop|vmstat|iostat|free|df)\b/,
4202
+ /^(lscpu|lsblk|lsusb|lspci)\b/,
4203
+ /^(nproc|getconf)\b/,
4204
+ // Additional git read-only
4205
+ /^git\s+(config\s+--get|config\s+-l|shortlog|reflog|cherry)\b/,
4206
+ /^git\s+(cat-file|count-objects|fsck|verify-pack)\b/
4207
+ ];
4208
+ var DANGEROUS_PATTERNS = [
4209
+ // Destructive file operations
4210
+ /\brm\s+(-[a-zA-Z]*r|-[a-zA-Z]*f|--recursive|--force)\b/,
4211
+ /\brm\s+-[a-zA-Z]*rf\b/,
4212
+ /\bshred\b/,
4213
+ // Privilege escalation
4214
+ /\bsudo\b/,
4215
+ /\bsu\s+-?\s*\w/,
4216
+ /\bdoas\b/,
4217
+ // Permission/ownership changes
4218
+ /\bchmod\b/,
4219
+ /\bchown\b/,
4220
+ /\bchgrp\b/,
4221
+ // Disk/partition operations
4222
+ /\bdd\b.*\bof=/,
4223
+ /\bmkfs\b/,
4224
+ /\bfdisk\b/,
4225
+ /\bparted\b/,
4226
+ /\bmount\b/,
4227
+ /\bumount\b/,
4228
+ // Remote code execution
4229
+ /\bcurl\b.*\|\s*(bash|sh|zsh|python|perl|ruby)\b/,
4230
+ /\bwget\b.*\|\s*(bash|sh|zsh|python|perl|ruby)\b/,
4231
+ /\bcurl\b.*>\s*.*\.sh\s*&&/,
4232
+ // Remote access
4233
+ /\bssh\b/,
4234
+ /\bscp\b/,
4235
+ /\brsync\b.*:\//,
4236
+ /\bnc\s+(-[a-zA-Z]*l|-[a-zA-Z]*p|--listen)\b/,
4237
+ /\bncat\b/,
4238
+ /\bsocat\b/,
4239
+ /\btelnet\b/,
4240
+ // System modification
4241
+ /\bsystemctl\s+(start|stop|restart|enable|disable)\b/,
4242
+ /\bservice\s+\w+\s+(start|stop|restart)\b/,
4243
+ /\biptables\b/,
4244
+ /\bufw\b/,
4245
+ /\bfirewall-cmd\b/,
4246
+ // Package installation (can run arbitrary post-install scripts)
4247
+ /\bnpm\s+(install|i|add|ci)\b/,
4248
+ /\byarn\s+(add|install)\b/,
4249
+ /\bpnpm\s+(add|install|i)\b/,
4250
+ /\bpip\s+install\b/,
4251
+ /\bapt(-get)?\s+install\b/,
4252
+ /\bbrew\s+install\b/,
4253
+ /\bcargo\s+install\b/,
4254
+ // Environment variable manipulation (can leak secrets)
4255
+ /\bexport\b.*(KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/i,
4256
+ // Cron / scheduled tasks
4257
+ /\bcrontab\b/,
4258
+ /\bat\s+/,
4259
+ // Container escape vectors
4260
+ /\bdocker\s+(run|exec|build|push|pull)\b/,
4261
+ /\bkubectl\s+(exec|run|apply|delete)\b/,
4262
+ // Process manipulation
4263
+ /\bkill\b/,
4264
+ /\bkillall\b/,
4265
+ /\bpkill\b/,
4266
+ // History manipulation
4267
+ /\bhistory\s+-c\b/,
4268
+ /\bunset\s+HISTFILE\b/,
4269
+ // Compiler/build (can execute arbitrary code)
4270
+ /\bmake\s/,
4271
+ /\bgcc\b/,
4272
+ /\bg\+\+/
4273
+ ];
4274
+
4275
+ // src/lib/bash/classifier.ts
4276
+ var BashClassifier = class {
4277
+ safePatterns;
4278
+ dangerousPatterns;
4279
+ constructor(overrides) {
4280
+ this.safePatterns = [...SAFE_PATTERNS, ...overrides?.additionalAllowed ?? []];
4281
+ this.dangerousPatterns = [...DANGEROUS_PATTERNS, ...overrides?.additionalBlocked ?? []];
4282
+ }
4283
+ classify(command) {
4284
+ const trimmed = command.trim();
4285
+ for (const pattern of this.dangerousPatterns) {
4286
+ if (pattern.test(trimmed)) return "dangerous";
4287
+ }
4288
+ const segments = this.splitCommand(trimmed);
4289
+ if (segments.length > 1) {
4290
+ const classifications = segments.map((s) => this.classifySingle(s));
4291
+ if (classifications.includes("dangerous")) return "dangerous";
4292
+ if (classifications.includes("needs_review")) return "needs_review";
4293
+ return "safe";
4294
+ }
4295
+ return this.classifySingle(trimmed);
4296
+ }
4297
+ classifySingle(command) {
4298
+ const trimmed = command.trim();
4299
+ for (const pattern of this.dangerousPatterns) {
4300
+ if (pattern.test(trimmed)) return "dangerous";
4301
+ }
4302
+ for (const pattern of this.safePatterns) {
4303
+ if (pattern.test(trimmed)) return "safe";
4304
+ }
4305
+ return "needs_review";
4306
+ }
4307
+ splitCommand(command) {
4308
+ const segments = [];
4309
+ let current = "";
4310
+ let inSingleQuote = false;
4311
+ let inDoubleQuote = false;
4312
+ let escaped = false;
4313
+ for (let i = 0; i < command.length; i++) {
4314
+ const char = command[i];
4315
+ if (escaped) {
4316
+ current += char;
4317
+ escaped = false;
4318
+ continue;
4319
+ }
4320
+ if (char === "\\") {
4321
+ escaped = true;
4322
+ current += char;
4323
+ continue;
4324
+ }
4325
+ if (char === "'" && !inDoubleQuote) {
4326
+ inSingleQuote = !inSingleQuote;
4327
+ current += char;
4328
+ continue;
4329
+ }
4330
+ if (char === '"' && !inSingleQuote) {
4331
+ inDoubleQuote = !inDoubleQuote;
4332
+ current += char;
4333
+ continue;
4334
+ }
4335
+ if (!inSingleQuote && !inDoubleQuote) {
4336
+ if (char === "|" && command[i + 1] !== "|") {
4337
+ segments.push(current.trim());
4338
+ current = "";
4339
+ continue;
4340
+ }
4341
+ if (char === ";") {
4342
+ segments.push(current.trim());
4343
+ current = "";
4344
+ continue;
4345
+ }
4346
+ if (char === "&" && command[i + 1] === "&") {
4347
+ segments.push(current.trim());
4348
+ current = "";
4349
+ i++;
4350
+ continue;
4351
+ }
4352
+ if (char === "|" && command[i + 1] === "|") {
4353
+ segments.push(current.trim());
4354
+ current = "";
4355
+ i++;
4356
+ continue;
4357
+ }
4358
+ }
4359
+ current += char;
4360
+ }
4361
+ if (current.trim()) segments.push(current.trim());
4362
+ return segments.filter((s) => s.length > 0);
4363
+ }
4364
+ };
4365
+
4366
+ // src/lib/budget/tracker.ts
4367
+ var BudgetTracker = class {
4368
+ _used = 0;
4369
+ _budget;
4370
+ constructor(budget) {
4371
+ this._budget = budget;
4372
+ }
4373
+ /** Returns false if consuming would exceed the budget. On success, increments the counter. */
4374
+ consume(amount = 1) {
4375
+ if (this._budget === -1) {
4376
+ this._used += amount;
4377
+ return true;
4378
+ }
4379
+ if (this._used + amount > this._budget) return false;
4380
+ this._used += amount;
4381
+ return true;
4382
+ }
4383
+ remaining() {
4384
+ if (this._budget === -1) return Infinity;
4385
+ return Math.max(0, this._budget - this._used);
4386
+ }
4387
+ used() {
4388
+ return this._used;
4389
+ }
4390
+ isUnlimited() {
4391
+ return this._budget === -1;
4392
+ }
4393
+ };
4394
+
4395
+ // src/lib/config/watcher.ts
4396
+ var import_node_fs2 = require("fs");
4397
+ var import_yaml5 = require("yaml");
4398
+ var import_value2 = require("@sinclair/typebox/value");
4399
+ var ConfigWatcher = class {
4400
+ watcher;
4401
+ debounceTimer;
4402
+ configPath;
4403
+ onChange;
4404
+ onError;
4405
+ constructor(configPath, onChange, onError) {
4406
+ this.configPath = configPath;
4407
+ this.onChange = onChange;
4408
+ this.onError = onError;
4409
+ }
4410
+ start() {
4411
+ if (this.watcher) return;
4412
+ this.watcher = (0, import_node_fs2.watch)(this.configPath, () => this.handleChange());
4413
+ }
4414
+ stop() {
4415
+ if (this.debounceTimer) {
4416
+ clearTimeout(this.debounceTimer);
4417
+ this.debounceTimer = void 0;
4418
+ }
4419
+ if (this.watcher) {
4420
+ this.watcher.close();
4421
+ this.watcher = void 0;
4422
+ }
4423
+ }
4424
+ handleChange() {
4425
+ if (this.debounceTimer) clearTimeout(this.debounceTimer);
4426
+ this.debounceTimer = setTimeout(() => this.reload(), 500);
4427
+ }
4428
+ reload() {
4429
+ try {
4430
+ const raw = (0, import_node_fs2.readFileSync)(this.configPath, "utf-8");
4431
+ const parsed = (0, import_yaml5.parse)(raw);
4432
+ const errors = [...import_value2.Value.Errors(GovernanceConfigSchema, parsed)];
4433
+ if (errors.length > 0) {
4434
+ const msg = errors.map((e) => `${e.path}: ${e.message}`).join("; ");
4435
+ this.onError?.(new Error(`Config validation failed: ${msg}`));
4436
+ return;
4437
+ }
4438
+ const config = import_value2.Value.Default(GovernanceConfigSchema, parsed);
4439
+ this.onChange(config);
4440
+ } catch (err) {
4441
+ this.onError?.(err instanceof Error ? err : new Error(String(err)));
4442
+ }
4443
+ }
4444
+ };
4445
+
4446
+ // src/lib/templates/selector.ts
4447
+ var import_node_fs3 = require("fs");
4448
+ var import_node_path = require("path");
4449
+ var import_node_url = require("url");
4450
+ var import_meta = {};
4451
+ function getBundledDir() {
4452
+ try {
4453
+ return (0, import_node_path.resolve)((0, import_node_path.dirname)((0, import_node_url.fileURLToPath)(import_meta.url)), "../../../prompts");
4454
+ } catch {
4455
+ return (0, import_node_path.resolve)(__dirname, "../../../prompts");
4456
+ }
4457
+ }
4458
+ var TemplateSelector = class {
4459
+ userDirectory;
4460
+ bundledDirectory;
4461
+ constructor(config) {
4462
+ this.userDirectory = config?.directory ?? "./templates/";
4463
+ this.bundledDirectory = getBundledDir();
4464
+ }
4465
+ /**
4466
+ * Resolve a template name to an absolute file path.
4467
+ * User templates take precedence over bundled templates.
4468
+ */
4469
+ resolve(templateName) {
4470
+ const userPath = (0, import_node_path.resolve)((0, import_node_path.join)(this.userDirectory, `${templateName}.md`));
4471
+ if ((0, import_node_fs3.existsSync)(userPath)) return userPath;
4472
+ const bundledPath = (0, import_node_path.resolve)((0, import_node_path.join)(this.bundledDirectory, `${templateName}.md`));
4473
+ if ((0, import_node_fs3.existsSync)(bundledPath)) return bundledPath;
4474
+ throw new Error(
4475
+ `Prompt template '${templateName}' not found. Searched: ${userPath}, ${bundledPath}`
4476
+ );
4477
+ }
4478
+ };
4479
+
4480
+ // src/lib/templates/renderer.ts
4481
+ function render(templateContent, variables) {
4482
+ return templateContent.replace(/\{\{(\w+)\}\}/g, (match, key) => {
4483
+ const value = variables[key];
4484
+ if (value === void 0) return match;
4485
+ if (Array.isArray(value)) return value.join("\n");
4486
+ return value;
4487
+ });
4488
+ }
4489
+
4490
+ // src/lib/audit/logger.ts
4491
+ var import_node_crypto = require("crypto");
4492
+
4493
+ // src/lib/audit/sinks/jsonl.ts
4494
+ var import_promises = require("fs/promises");
4495
+ var import_node_path2 = require("path");
4496
+ var import_node_os = require("os");
4497
+ var JsonlAuditSink = class {
4498
+ path;
4499
+ buffer = [];
4500
+ flushThreshold = 10;
4501
+ constructor(path) {
4502
+ this.path = path.replace(/^~/, (0, import_node_os.homedir)());
4503
+ }
4504
+ async write(record) {
4505
+ this.buffer.push(record);
4506
+ if (this.buffer.length >= this.flushThreshold) {
4507
+ await this.flush();
4508
+ }
4509
+ }
4510
+ async flush() {
4511
+ if (this.buffer.length === 0) return;
4512
+ const lines = this.buffer.map((r) => JSON.stringify(r)).join("\n") + "\n";
4513
+ this.buffer = [];
4514
+ await (0, import_promises.mkdir)((0, import_node_path2.dirname)(this.path), { recursive: true });
4515
+ await (0, import_promises.appendFile)(this.path, lines, "utf-8");
4516
+ }
4517
+ };
4518
+
4519
+ // src/lib/audit/sinks/webhook.ts
4520
+ var WebhookAuditSink = class {
4521
+ url;
4522
+ buffer = [];
4523
+ flushThreshold = 10;
4524
+ constructor(url) {
4525
+ this.url = url;
4526
+ }
4527
+ async write(record) {
4528
+ this.buffer.push(record);
4529
+ if (this.buffer.length >= this.flushThreshold) {
4530
+ await this.flush();
4531
+ }
4532
+ }
4533
+ async flush() {
4534
+ if (this.buffer.length === 0) return;
4535
+ const records = [...this.buffer];
4536
+ this.buffer = [];
4537
+ try {
4538
+ await this.send(records);
4539
+ } catch {
4540
+ try {
4541
+ await this.send(records);
4542
+ } catch {
4543
+ }
4544
+ }
4545
+ }
4546
+ async send(records) {
4547
+ const controller = new AbortController();
4548
+ const timeout = setTimeout(() => controller.abort(), 1e4);
4549
+ try {
4550
+ const response = await fetch(this.url, {
4551
+ method: "POST",
4552
+ headers: { "Content-Type": "application/json" },
4553
+ body: JSON.stringify(records),
4554
+ signal: controller.signal
4555
+ });
4556
+ if (!response.ok) {
4557
+ throw new Error(`Webhook returned ${response.status}`);
4558
+ }
4559
+ } finally {
4560
+ clearTimeout(timeout);
4561
+ }
4562
+ }
4563
+ };
4564
+
4565
+ // src/lib/audit/logger.ts
4566
+ var AuditLogger = class {
4567
+ sinks;
4568
+ counts = /* @__PURE__ */ new Map();
4569
+ constructor(config) {
4570
+ const sinkConfigs = config?.sinks ?? [
4571
+ { type: "jsonl", path: "~/.pi/agent/audit.jsonl" }
4572
+ ];
4573
+ this.sinks = [];
4574
+ for (const sc of sinkConfigs) {
4575
+ if (sc.type === "jsonl") {
4576
+ this.sinks.push(new JsonlAuditSink(sc.path ?? "~/.pi/agent/audit.jsonl"));
4577
+ } else if (sc.type === "webhook" && sc.url) {
4578
+ this.sinks.push(new WebhookAuditSink(sc.url));
4579
+ }
4580
+ }
4581
+ if (this.sinks.length === 0) {
4582
+ this.sinks.push(new JsonlAuditSink("~/.pi/agent/audit.jsonl"));
4583
+ }
4584
+ }
4585
+ async log(record) {
4586
+ const full = {
4587
+ ...record,
4588
+ id: (0, import_node_crypto.randomUUID)(),
4589
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
4590
+ };
4591
+ this.counts.set(full.event, (this.counts.get(full.event) ?? 0) + 1);
4592
+ await Promise.all(this.sinks.map((s) => s.write(full)));
4593
+ }
4594
+ async flush() {
4595
+ await Promise.all(this.sinks.map((s) => s.flush()));
4596
+ }
4597
+ getSummary() {
4598
+ return new Map(this.counts);
4599
+ }
4600
+ };
4601
+
4602
+ // src/lib/hitl/cli-approver.ts
4603
+ var CliApprover = class {
4604
+ ui;
4605
+ timeoutSeconds;
4606
+ constructor(ui, timeoutSeconds = 300) {
4607
+ this.ui = ui;
4608
+ this.timeoutSeconds = timeoutSeconds;
4609
+ }
4610
+ async requestApproval(toolCall, context) {
4611
+ const title = `Approval Required: ${toolCall.toolName}`;
4612
+ const inputSummary = Object.entries(toolCall.input).map(
4613
+ ([k, v]) => ` ${k}: ${typeof v === "string" ? v.slice(0, 200) : JSON.stringify(v).slice(0, 200)}`
4614
+ ).join("\n");
4615
+ const message = `User: ${context.userId} (${context.role})
4616
+ Org: ${context.orgUnit}
4617
+
4618
+ Tool: ${toolCall.toolName}
4619
+ Input:
4620
+ ${inputSummary}`;
4621
+ const start = Date.now();
4622
+ try {
4623
+ const approved = await this.ui.confirm(title, message, {
4624
+ timeout: this.timeoutSeconds * 1e3
4625
+ });
4626
+ return {
4627
+ approved,
4628
+ approver: "cli",
4629
+ duration: Date.now() - start,
4630
+ reason: approved ? void 0 : "Denied by user"
4631
+ };
4632
+ } catch {
4633
+ return {
4634
+ approved: false,
4635
+ approver: "cli",
4636
+ duration: Date.now() - start,
4637
+ reason: "Approval timed out"
4638
+ };
4639
+ }
4640
+ }
4641
+ };
4642
+
4643
+ // src/lib/hitl/webhook-approver.ts
4644
+ var WebhookApprover = class {
4645
+ url;
4646
+ timeoutMs;
4647
+ constructor(url, timeoutSeconds = 300) {
4648
+ this.url = url;
4649
+ this.timeoutMs = timeoutSeconds * 1e3;
4650
+ }
4651
+ async requestApproval(toolCall, context) {
4652
+ const start = Date.now();
4653
+ const controller = new AbortController();
4654
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
4655
+ try {
4656
+ const response = await fetch(this.url, {
4657
+ method: "POST",
4658
+ headers: { "Content-Type": "application/json" },
4659
+ body: JSON.stringify({
4660
+ toolCall: { toolName: toolCall.toolName, input: toolCall.input },
4661
+ context
4662
+ }),
4663
+ signal: controller.signal
4664
+ });
4665
+ if (!response.ok) {
4666
+ return {
4667
+ approved: false,
4668
+ approver: "webhook",
4669
+ duration: Date.now() - start,
4670
+ reason: `Webhook returned ${response.status}`
4671
+ };
4672
+ }
4673
+ const body = await response.json();
4674
+ return {
4675
+ approved: body.approved,
4676
+ approver: "webhook",
4677
+ duration: Date.now() - start,
4678
+ reason: body.reason
4679
+ };
4680
+ } catch (err) {
4681
+ return {
4682
+ approved: false,
4683
+ approver: "webhook",
4684
+ duration: Date.now() - start,
4685
+ reason: err instanceof Error && err.name === "AbortError" ? "Webhook timed out" : "Webhook request failed"
4686
+ };
4687
+ } finally {
4688
+ clearTimeout(timeout);
4689
+ }
4690
+ }
4691
+ };
4692
+
4693
+ // src/lib/hitl/approval.ts
4694
+ function createApprovalFlow(config, ui) {
4695
+ if (config.approval_channel === "webhook" && config.webhook?.url) {
4696
+ return new WebhookApprover(config.webhook.url, config.timeout_seconds);
4697
+ }
4698
+ if (!ui) {
4699
+ throw new Error("CLI approval channel requires a ConfirmUI (ExtensionContext.ui)");
4700
+ }
4701
+ return new CliApprover(ui, config.timeout_seconds);
4702
+ }
190
4703
  // Annotate the CommonJS export names for ESM import in node:
191
4704
  0 && (module.exports = {
4705
+ AuditLogger,
4706
+ BashClassifier,
4707
+ BudgetTracker,
4708
+ CliApprover,
192
4709
  ConfigValidationError,
193
- loadConfig
4710
+ ConfigWatcher,
4711
+ DANGEROUS_PATTERNS,
4712
+ EnvIdentityProvider,
4713
+ IdentityChain,
4714
+ JsonlAuditSink,
4715
+ LocalIdentityProvider,
4716
+ OsoMemoryFactStore,
4717
+ SAFE_PATTERNS,
4718
+ TemplateSelector,
4719
+ WebhookApprover,
4720
+ WebhookAuditSink,
4721
+ YamlFactStore,
4722
+ YamlPolicyEngine,
4723
+ createApprovalFlow,
4724
+ createIdentityChain,
4725
+ createPolicyEngine,
4726
+ loadConfig,
4727
+ renderTemplate
194
4728
  });
195
4729
  //# sourceMappingURL=index.cjs.map